routerparse.c 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char routerparse_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file routerparse.c
  11. * \brief Code to parse and validate router descriptors and directories.
  12. **/
  13. #include "or.h"
  14. #include "memarea.h"
  15. /****************************************************************************/
  16. /** Enumeration of possible token types. The ones starting with K_ correspond
  17. * to directory 'keywords'. _ERR is an error in the tokenizing process, _EOF
  18. * is an end-of-file marker, and _NIL is used to encode not-a-token.
  19. */
  20. typedef enum {
  21. K_ACCEPT = 0,
  22. K_ACCEPT6,
  23. K_DIRECTORY_SIGNATURE,
  24. K_RECOMMENDED_SOFTWARE,
  25. K_REJECT,
  26. K_REJECT6,
  27. K_ROUTER,
  28. K_SIGNED_DIRECTORY,
  29. K_SIGNING_KEY,
  30. K_ONION_KEY,
  31. K_ROUTER_SIGNATURE,
  32. K_PUBLISHED,
  33. K_RUNNING_ROUTERS,
  34. K_ROUTER_STATUS,
  35. K_PLATFORM,
  36. K_OPT,
  37. K_BANDWIDTH,
  38. K_CONTACT,
  39. K_NETWORK_STATUS,
  40. K_UPTIME,
  41. K_DIR_SIGNING_KEY,
  42. K_FAMILY,
  43. K_FINGERPRINT,
  44. K_HIBERNATING,
  45. K_READ_HISTORY,
  46. K_WRITE_HISTORY,
  47. K_NETWORK_STATUS_VERSION,
  48. K_DIR_SOURCE,
  49. K_DIR_OPTIONS,
  50. K_CLIENT_VERSIONS,
  51. K_SERVER_VERSIONS,
  52. K_P,
  53. K_R,
  54. K_S,
  55. K_V,
  56. K_W,
  57. K_EVENTDNS,
  58. K_EXTRA_INFO,
  59. K_EXTRA_INFO_DIGEST,
  60. K_CACHES_EXTRA_INFO,
  61. K_HIDDEN_SERVICE_DIR,
  62. K_ALLOW_SINGLE_HOP_EXITS,
  63. K_DIR_KEY_CERTIFICATE_VERSION,
  64. K_DIR_IDENTITY_KEY,
  65. K_DIR_KEY_PUBLISHED,
  66. K_DIR_KEY_EXPIRES,
  67. K_DIR_KEY_CERTIFICATION,
  68. K_DIR_ADDRESS,
  69. K_VOTE_STATUS,
  70. K_VALID_AFTER,
  71. K_FRESH_UNTIL,
  72. K_VALID_UNTIL,
  73. K_VOTING_DELAY,
  74. K_KNOWN_FLAGS,
  75. K_VOTE_DIGEST,
  76. K_CONSENSUS_DIGEST,
  77. K_CONSENSUS_METHODS,
  78. K_CONSENSUS_METHOD,
  79. K_LEGACY_DIR_KEY,
  80. A_PURPOSE,
  81. _A_UNKNOWN,
  82. R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  83. R_VERSION,
  84. R_PERMANENT_KEY,
  85. R_SECRET_ID_PART,
  86. R_PUBLICATION_TIME,
  87. R_PROTOCOL_VERSIONS,
  88. R_INTRODUCTION_POINTS,
  89. R_SIGNATURE,
  90. R_IPO_IDENTIFIER,
  91. R_IPO_IP_ADDRESS,
  92. R_IPO_ONION_PORT,
  93. R_IPO_ONION_KEY,
  94. R_IPO_SERVICE_KEY,
  95. C_CLIENT_NAME,
  96. C_DESCRIPTOR_COOKIE,
  97. C_CLIENT_KEY,
  98. _UNRECOGNIZED,
  99. _ERR,
  100. _EOF,
  101. _NIL
  102. } directory_keyword;
  103. #define MIN_ANNOTATION A_PURPOSE
  104. #define MAX_ANNOTATION _A_UNKNOWN
  105. /** Structure to hold a single directory token.
  106. *
  107. * We parse a directory by breaking it into "tokens", each consisting
  108. * of a keyword, a line full of arguments, and a binary object. The
  109. * arguments and object are both optional, depending on the keyword
  110. * type.
  111. *
  112. * This structure is only allocated in memareas; do not allocate it on
  113. * the heap, or token_free() won't work.
  114. */
  115. typedef struct directory_token_t {
  116. directory_keyword tp; /**< Type of the token. */
  117. int n_args:30; /**< Number of elements in args */
  118. char **args; /**< Array of arguments from keyword line. */
  119. char *object_type; /**< -----BEGIN [object_type]-----*/
  120. size_t object_size; /**< Bytes in object_body */
  121. char *object_body; /**< Contents of object, base64-decoded. */
  122. crypto_pk_env_t *key; /**< For public keys only. Heap-allocated. */
  123. char *error; /**< For _ERR tokens only. */
  124. } directory_token_t;
  125. /* ********************************************************************** */
  126. /** We use a table of rules to decide how to parse each token type. */
  127. /** Rules for whether the keyword needs an object. */
  128. typedef enum {
  129. NO_OBJ, /**< No object, ever. */
  130. NEED_OBJ, /**< Object is required. */
  131. NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
  132. NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  133. NEED_KEY, /**< Object is required, and must be a public key. */
  134. OBJ_OK, /**< Object is optional. */
  135. } obj_syntax;
  136. #define AT_START 1
  137. #define AT_END 2
  138. /** Determines the parsing rules for a single token type. */
  139. typedef struct token_rule_t {
  140. /** The string value of the keyword identifying the type of item. */
  141. const char *t;
  142. /** The corresponding directory_keyword enum. */
  143. directory_keyword v;
  144. /** Minimum number of arguments for this item */
  145. int min_args;
  146. /** Maximum number of arguments for this item */
  147. int max_args;
  148. /** If true, we concatenate all arguments for this item into a single
  149. * string. */
  150. int concat_args;
  151. /** Requirments on object syntax for this item. */
  152. obj_syntax os;
  153. /** Lowest number of times this item may appear in a document. */
  154. int min_cnt;
  155. /** Highest number of times this item may appear in a document. */
  156. int max_cnt;
  157. /** One or more of AT_START/AT_END to limit where the item may appear in a
  158. * document. */
  159. int pos;
  160. /** True iff this token is an annotation. */
  161. int is_annotation;
  162. } token_rule_t;
  163. /*
  164. * Helper macros to define token tables. 's' is a string, 't' is a
  165. * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
  166. * object syntax.
  167. *
  168. */
  169. /** Appears to indicate the end of a table. */
  170. #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
  171. /** An item with no restrictions: used for obsolete document types */
  172. #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  173. /** An item with no restrictions on multiplicity or location. */
  174. #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  175. /** An item that must appear exactly once */
  176. #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0, 0 }
  177. /** An item that must appear exactly once, at the start of the document */
  178. #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START, 0 }
  179. /** An item that must appear exactly once, at the end of the document */
  180. #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END, 0 }
  181. /** An item that must appear one or more times */
  182. #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0, 0 }
  183. /** An item that must appear no more than once */
  184. #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
  185. /** An annotation that must appear no more than once */
  186. #define A01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
  187. /* Argument multiplicity: any number of arguments. */
  188. #define ARGS 0,INT_MAX,0
  189. /* Argument multiplicity: no arguments. */
  190. #define NO_ARGS 0,0,0
  191. /* Argument multiplicity: concatenate all arguments. */
  192. #define CONCAT_ARGS 1,1,1
  193. /* Argument multiplicity: at least <b>n</b> arguments. */
  194. #define GE(n) n,INT_MAX,0
  195. /* Argument multiplicity: exactly <b>n</b> arguments. */
  196. #define EQ(n) n,n,0
  197. /** List of tokens allowable in router derscriptors */
  198. static token_rule_t routerdesc_token_table[] = {
  199. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  200. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  201. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  202. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  203. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  204. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  205. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  206. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  207. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  208. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  209. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  210. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  211. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  212. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  213. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  214. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  215. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  216. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  217. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  218. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  219. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  220. T01("eventdns", K_EVENTDNS, ARGS, NO_OBJ ),
  221. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  222. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  223. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  224. END_OF_TABLE
  225. };
  226. /** List of tokens allowable in extra-info documents. */
  227. static token_rule_t extrainfo_token_table[] = {
  228. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  229. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  230. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  231. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  232. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  233. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  234. END_OF_TABLE
  235. };
  236. /** List of tokens allowable in the body part of v2 and v3 networkstatus
  237. * documents. */
  238. static token_rule_t rtrstatus_token_table[] = {
  239. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  240. T1( "r", K_R, GE(8), NO_OBJ ),
  241. T1( "s", K_S, ARGS, NO_OBJ ),
  242. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  243. T01("w", K_W, ARGS, NO_OBJ ),
  244. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  245. END_OF_TABLE
  246. };
  247. /** List of tokens allowable in the header part of v2 networkstatus documents.
  248. */
  249. static token_rule_t netstatus_token_table[] = {
  250. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  251. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  252. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  253. T1( "dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  254. T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  255. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  256. GE(1), NO_OBJ ),
  257. T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  258. T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  259. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  260. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  261. END_OF_TABLE
  262. };
  263. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  264. * footers. */
  265. static token_rule_t dir_footer_token_table[] = {
  266. T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
  267. END_OF_TABLE
  268. };
  269. /** List of tokens allowable in v1 directory headers/footers. */
  270. static token_rule_t dir_token_table[] = {
  271. /* don't enforce counts; this is obsolete. */
  272. T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
  273. T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
  274. T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
  275. T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
  276. T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
  277. T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
  278. T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  279. T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  280. T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  281. T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
  282. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  283. END_OF_TABLE
  284. };
  285. #define CERTIFICATE_MEMBERS \
  286. T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
  287. GE(1), NO_OBJ ), \
  288. T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
  289. T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
  290. T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
  291. T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
  292. T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
  293. NO_ARGS, NEED_OBJ), \
  294. T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
  295. static token_rule_t dir_key_certificate_table[] = {
  296. CERTIFICATE_MEMBERS
  297. T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  298. END_OF_TABLE
  299. };
  300. /** List of tokens allowable in rendezvous service descriptors */
  301. static token_rule_t desc_token_table[] = {
  302. T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  303. EQ(1), NO_OBJ),
  304. T1("version", R_VERSION, EQ(1), NO_OBJ),
  305. T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
  306. T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
  307. T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
  308. T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
  309. T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
  310. T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
  311. END_OF_TABLE
  312. };
  313. /** List of tokens allowed in the (encrypted) list of introduction points of
  314. * rendezvous service descriptors */
  315. static token_rule_t ipo_token_table[] = {
  316. T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
  317. T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
  318. T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
  319. T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  320. T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
  321. END_OF_TABLE
  322. };
  323. /** List of tokens allowed in the (possibly encrypted) list of introduction
  324. * points of rendezvous service descriptors */
  325. static token_rule_t client_keys_token_table[] = {
  326. T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
  327. T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
  328. T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
  329. END_OF_TABLE
  330. };
  331. static token_rule_t networkstatus_token_table[] = {
  332. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  333. GE(1), NO_OBJ ),
  334. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  335. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  336. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  337. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  338. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  339. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  340. T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
  341. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  342. CERTIFICATE_MEMBERS
  343. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  344. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  345. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  346. T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
  347. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  348. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  349. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  350. T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
  351. END_OF_TABLE
  352. };
  353. static token_rule_t networkstatus_consensus_token_table[] = {
  354. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  355. GE(1), NO_OBJ ),
  356. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  357. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  358. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  359. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  360. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  361. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  362. T1N("dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  363. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  364. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  365. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  366. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  367. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  368. T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
  369. END_OF_TABLE
  370. };
  371. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  372. * footers. */
  373. static token_rule_t networkstatus_vote_footer_token_table[] = {
  374. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  375. END_OF_TABLE
  376. };
  377. static token_rule_t networkstatus_detached_signature_token_table[] = {
  378. T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
  379. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  380. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  381. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  382. T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  383. END_OF_TABLE
  384. };
  385. #undef T
  386. /* static function prototypes */
  387. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  388. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  389. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  390. static int router_get_hash_impl(const char *s, char *digest,
  391. const char *start_str, const char *end_str,
  392. char end_char);
  393. static void token_free(directory_token_t *tok);
  394. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  395. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  396. directory_keyword keyword);
  397. #define TS_ANNOTATIONS_OK 1
  398. #define TS_NOCHECK 2
  399. #define TS_NO_NEW_ANNOTATIONS 4
  400. static int tokenize_string(memarea_t *area,
  401. const char *start, const char *end,
  402. smartlist_t *out,
  403. token_rule_t *table,
  404. int flags);
  405. static directory_token_t *get_next_token(memarea_t *area,
  406. const char **s,
  407. const char *eos,
  408. token_rule_t *table);
  409. static int check_signature_token(const char *digest,
  410. directory_token_t *tok,
  411. crypto_pk_env_t *pkey,
  412. int check_authority,
  413. const char *doctype);
  414. static crypto_pk_env_t *find_dir_signing_key(const char *str, const char *eos);
  415. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  416. #undef DEBUG_AREA_ALLOC
  417. #ifdef DEBUG_AREA_ALLOC
  418. #define DUMP_AREA(a,name) STMT_BEGIN \
  419. size_t alloc=0, used=0; \
  420. memarea_get_stats((a),&alloc,&used); \
  421. log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
  422. name, (unsigned long)alloc, (unsigned long)used); \
  423. STMT_END
  424. #else
  425. #define DUMP_AREA(a,name) STMT_NIL
  426. #endif
  427. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  428. * <b>s</b>. Return 0 on success, -1 on failure.
  429. */
  430. int
  431. router_get_dir_hash(const char *s, char *digest)
  432. {
  433. return router_get_hash_impl(s,digest,
  434. "signed-directory","\ndirectory-signature",'\n');
  435. }
  436. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  437. * <b>s</b>. Return 0 on success, -1 on failure.
  438. */
  439. int
  440. router_get_router_hash(const char *s, char *digest)
  441. {
  442. return router_get_hash_impl(s,digest,
  443. "router ","\nrouter-signature", '\n');
  444. }
  445. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  446. * string in <b>s</b>. Return 0 on success, -1 on failure.
  447. */
  448. int
  449. router_get_runningrouters_hash(const char *s, char *digest)
  450. {
  451. return router_get_hash_impl(s,digest,
  452. "network-status","\ndirectory-signature", '\n');
  453. }
  454. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  455. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  456. int
  457. router_get_networkstatus_v2_hash(const char *s, char *digest)
  458. {
  459. return router_get_hash_impl(s,digest,
  460. "network-status-version","\ndirectory-signature",
  461. '\n');
  462. }
  463. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  464. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  465. int
  466. router_get_networkstatus_v3_hash(const char *s, char *digest)
  467. {
  468. return router_get_hash_impl(s,digest,
  469. "network-status-version","\ndirectory-signature",
  470. ' ');
  471. }
  472. /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
  473. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  474. int
  475. router_get_extrainfo_hash(const char *s, char *digest)
  476. {
  477. return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature",'\n');
  478. }
  479. /** Helper: used to generate signatures for routers, directories and
  480. * network-status objects. Given a digest in <b>digest</b> and a secret
  481. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  482. * surround it with -----BEGIN/END----- pairs, and write it to the
  483. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  484. * failure.
  485. */
  486. int
  487. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  488. crypto_pk_env_t *private_key)
  489. {
  490. char *signature;
  491. size_t i;
  492. signature = tor_malloc(crypto_pk_keysize(private_key));
  493. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  494. log_warn(LD_BUG,"Couldn't sign digest.");
  495. goto err;
  496. }
  497. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  498. goto truncated;
  499. i = strlen(buf);
  500. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  501. log_warn(LD_BUG,"couldn't base64-encode signature");
  502. goto err;
  503. }
  504. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  505. goto truncated;
  506. tor_free(signature);
  507. return 0;
  508. truncated:
  509. log_warn(LD_BUG,"tried to exceed string length.");
  510. err:
  511. tor_free(signature);
  512. return -1;
  513. }
  514. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  515. * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
  516. * entries. Else, return VS_OLD if every member of
  517. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  518. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  519. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  520. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  521. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  522. * VS_UNRECOMMENDED.
  523. *
  524. * (versionlist is a comma-separated list of version strings,
  525. * optionally prefixed with "Tor". Versions that can't be parsed are
  526. * ignored.)
  527. */
  528. version_status_t
  529. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  530. {
  531. tor_version_t mine, other;
  532. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  533. found_any_in_series = 0, r, same;
  534. version_status_t ret = VS_UNRECOMMENDED;
  535. smartlist_t *version_sl;
  536. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  537. myversion, versionlist);
  538. if (tor_version_parse(myversion, &mine)) {
  539. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  540. tor_assert(0);
  541. }
  542. version_sl = smartlist_create();
  543. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  544. if (!strlen(versionlist)) { /* no authorities cared or agreed */
  545. ret = VS_EMPTY;
  546. goto done;
  547. }
  548. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  549. if (!strcmpstart(cp, "Tor "))
  550. cp += 4;
  551. if (tor_version_parse(cp, &other)) {
  552. /* Couldn't parse other; it can't be a match. */
  553. } else {
  554. same = tor_version_same_series(&mine, &other);
  555. if (same)
  556. found_any_in_series = 1;
  557. r = tor_version_compare(&mine, &other);
  558. if (r==0) {
  559. ret = VS_RECOMMENDED;
  560. goto done;
  561. } else if (r<0) {
  562. found_newer = 1;
  563. if (same)
  564. found_newer_in_series = 1;
  565. } else if (r>0) {
  566. found_older = 1;
  567. }
  568. }
  569. });
  570. /* We didn't find the listed version. Is it new or old? */
  571. if (found_any_in_series && !found_newer_in_series && found_newer) {
  572. ret = VS_NEW_IN_SERIES;
  573. } else if (found_newer && !found_older) {
  574. ret = VS_OLD;
  575. } else if (found_older && !found_newer) {
  576. ret = VS_NEW;
  577. } else {
  578. ret = VS_UNRECOMMENDED;
  579. }
  580. done:
  581. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  582. smartlist_free(version_sl);
  583. return ret;
  584. }
  585. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  586. * Otherwise, return -1. If we're a directory cache, cache it.
  587. */
  588. int
  589. router_parse_directory(const char *str)
  590. {
  591. directory_token_t *tok;
  592. char digest[DIGEST_LEN];
  593. time_t published_on;
  594. int r;
  595. const char *end, *cp;
  596. smartlist_t *tokens = NULL;
  597. crypto_pk_env_t *declared_key = NULL;
  598. memarea_t *area = memarea_new();
  599. /* XXXX This could be simplified a lot, but it will all go away
  600. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  601. * touch it. */
  602. if (router_get_dir_hash(str, digest)) {
  603. log_warn(LD_DIR, "Unable to compute digest of directory");
  604. goto err;
  605. }
  606. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  607. /* Check signature first, before we try to tokenize. */
  608. cp = str;
  609. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  610. cp = end;
  611. if (cp == str || !cp) {
  612. log_warn(LD_DIR, "No signature found on directory."); goto err;
  613. }
  614. ++cp;
  615. tokens = smartlist_create();
  616. if (tokenize_string(area,cp,strchr(cp,'\0'),tokens,dir_token_table,0)) {
  617. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  618. }
  619. if (smartlist_len(tokens) != 1) {
  620. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  621. }
  622. tok=smartlist_get(tokens,0);
  623. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  624. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  625. }
  626. declared_key = find_dir_signing_key(str, str+strlen(str));
  627. note_crypto_pk_op(VERIFY_DIR);
  628. if (check_signature_token(digest, tok, declared_key, 1, "directory")<0)
  629. goto err;
  630. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  631. smartlist_clear(tokens);
  632. memarea_clear(area);
  633. /* Now try to parse the first part of the directory. */
  634. if ((end = strstr(str,"\nrouter "))) {
  635. ++end;
  636. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  637. ++end;
  638. } else {
  639. end = str + strlen(str);
  640. }
  641. if (tokenize_string(area,str,end,tokens,dir_token_table,0)) {
  642. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  643. }
  644. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  645. tor_assert(tok);
  646. tor_assert(tok->n_args == 1);
  647. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  648. goto err;
  649. }
  650. /* Now that we know the signature is okay, and we have a
  651. * publication time, cache the directory. */
  652. if (directory_caches_v1_dir_info(get_options()) &&
  653. !authdir_mode_v1(get_options()))
  654. dirserv_set_cached_directory(str, published_on, 0);
  655. r = 0;
  656. goto done;
  657. err:
  658. r = -1;
  659. done:
  660. if (declared_key) crypto_free_pk_env(declared_key);
  661. if (tokens) {
  662. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  663. smartlist_free(tokens);
  664. }
  665. if (area) {
  666. DUMP_AREA(area, "v1 directory");
  667. memarea_drop_all(area);
  668. }
  669. return r;
  670. }
  671. /** Read a signed router status statement from <b>str</b>. If it's
  672. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  673. * cache it.*/
  674. int
  675. router_parse_runningrouters(const char *str)
  676. {
  677. char digest[DIGEST_LEN];
  678. directory_token_t *tok;
  679. time_t published_on;
  680. int r = -1;
  681. crypto_pk_env_t *declared_key = NULL;
  682. smartlist_t *tokens = NULL;
  683. const char *eos = str + strlen(str);
  684. memarea_t *area = NULL;
  685. if (router_get_runningrouters_hash(str, digest)) {
  686. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  687. goto err;
  688. }
  689. area = memarea_new();
  690. tokens = smartlist_create();
  691. if (tokenize_string(area,str,eos,tokens,dir_token_table,0)) {
  692. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  693. }
  694. tok = smartlist_get(tokens,0);
  695. if (tok->tp != K_NETWORK_STATUS) {
  696. log_warn(LD_DIR, "Network-status starts with wrong token");
  697. goto err;
  698. }
  699. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  700. tor_assert(tok);
  701. tor_assert(tok->n_args == 1);
  702. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  703. goto err;
  704. }
  705. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  706. log_warn(LD_DIR, "Missing signature on running-routers");
  707. goto err;
  708. }
  709. declared_key = find_dir_signing_key(str, eos);
  710. note_crypto_pk_op(VERIFY_DIR);
  711. if (check_signature_token(digest, tok, declared_key, 1, "running-routers")
  712. < 0)
  713. goto err;
  714. /* Now that we know the signature is okay, and we have a
  715. * publication time, cache the list. */
  716. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  717. dirserv_set_cached_directory(str, published_on, 1);
  718. r = 0;
  719. err:
  720. if (declared_key) crypto_free_pk_env(declared_key);
  721. if (tokens) {
  722. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  723. smartlist_free(tokens);
  724. }
  725. if (area) {
  726. DUMP_AREA(area, "v1 running-routers");
  727. memarea_drop_all(area);
  728. }
  729. return r;
  730. }
  731. /** Given a directory or running-routers string in <b>str</b>, try to
  732. * find the its dir-signing-key token (if any). If this token is
  733. * present, extract and return the key. Return NULL on failure. */
  734. static crypto_pk_env_t *
  735. find_dir_signing_key(const char *str, const char *eos)
  736. {
  737. const char *cp;
  738. directory_token_t *tok;
  739. crypto_pk_env_t *key = NULL;
  740. memarea_t *area = NULL;
  741. tor_assert(str);
  742. tor_assert(eos);
  743. /* Is there a dir-signing-key in the directory? */
  744. cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
  745. if (!cp)
  746. cp = tor_memstr(str, eos-str, "\ndir-signing-key");
  747. if (!cp)
  748. return NULL;
  749. ++cp; /* Now cp points to the start of the token. */
  750. area = memarea_new();
  751. tok = get_next_token(area, &cp, eos, dir_token_table);
  752. if (!tok) {
  753. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  754. goto done;
  755. }
  756. if (tok->tp != K_DIR_SIGNING_KEY) {
  757. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  758. goto done;
  759. }
  760. if (tok->key) {
  761. key = tok->key;
  762. tok->key = NULL; /* steal reference. */
  763. } else {
  764. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  765. }
  766. done:
  767. if (tok) token_free(tok);
  768. if (area) {
  769. DUMP_AREA(area, "dir-signing-key token");
  770. memarea_drop_all(area);
  771. }
  772. return key;
  773. }
  774. /** Return true iff <b>key</b> is allowed to sign directories.
  775. */
  776. static int
  777. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  778. {
  779. char digest[DIGEST_LEN];
  780. if (!key) return 0;
  781. if (crypto_pk_get_digest(key, digest) < 0) {
  782. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  783. return 0;
  784. }
  785. if (!router_digest_is_trusted_dir(digest)) {
  786. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  787. return 0;
  788. }
  789. return 1;
  790. }
  791. /** Check whether the object body of the token in <b>tok</b> has a good
  792. * signature for <b>digest</b> using key <b>pkey</b>. If
  793. * <b>check_authority</b> is set, make sure that <b>pkey</b> is the key of a
  794. * directory authority. Use <b>doctype</b> as the type of the document when
  795. * generating log messages. Return 0 on success, negative on failure.
  796. */
  797. static int
  798. check_signature_token(const char *digest,
  799. directory_token_t *tok,
  800. crypto_pk_env_t *pkey,
  801. int check_authority,
  802. const char *doctype)
  803. {
  804. char *signed_digest;
  805. tor_assert(pkey);
  806. tor_assert(tok);
  807. tor_assert(digest);
  808. tor_assert(doctype);
  809. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  810. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  811. doctype);
  812. return -1;
  813. }
  814. if (strcmp(tok->object_type, "SIGNATURE")) {
  815. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  816. return -1;
  817. }
  818. signed_digest = tor_malloc(tok->object_size);
  819. if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
  820. tok->object_size)
  821. != DIGEST_LEN) {
  822. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  823. tor_free(signed_digest);
  824. return -1;
  825. }
  826. // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  827. // hex_str(signed_digest,4));
  828. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  829. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  830. tor_free(signed_digest);
  831. return -1;
  832. }
  833. tor_free(signed_digest);
  834. return 0;
  835. }
  836. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  837. * or to the first of the annotations proceeding the next router or
  838. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  839. * we found an extrainfo, or false if found a router. Do not scan beyond
  840. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  841. static int
  842. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  843. const char *eos,
  844. int *is_extrainfo_out)
  845. {
  846. const char *annotations = NULL;
  847. const char *s = *s_ptr;
  848. s = eat_whitespace_eos(s, eos);
  849. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  850. /* We're at the start of a line. */
  851. tor_assert(*s != '\n');
  852. if (*s == '@' && !annotations) {
  853. annotations = s;
  854. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  855. *s_ptr = annotations ? annotations : s;
  856. *is_extrainfo_out = 0;
  857. return 0;
  858. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  859. *s_ptr = annotations ? annotations : s;
  860. *is_extrainfo_out = 1;
  861. return 0;
  862. }
  863. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  864. break;
  865. s = eat_whitespace_eos(s, eos);
  866. }
  867. return -1;
  868. }
  869. /** Given a string *<b>s</b> containing a concatenated sequence of router
  870. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  871. * them and stores the result in <b>dest</b>. All routers are marked running
  872. * and valid. Advances *s to a point immediately following the last router
  873. * entry. Ignore any trailing router entries that are not complete.
  874. *
  875. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  876. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  877. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  878. *
  879. * Returns 0 on success and -1 on failure.
  880. */
  881. int
  882. router_parse_list_from_string(const char **s, const char *eos,
  883. smartlist_t *dest,
  884. saved_location_t saved_location,
  885. int want_extrainfo,
  886. int allow_annotations,
  887. const char *prepend_annotations)
  888. {
  889. routerinfo_t *router;
  890. extrainfo_t *extrainfo;
  891. signed_descriptor_t *signed_desc;
  892. void *elt;
  893. const char *end, *start;
  894. int have_extrainfo;
  895. tor_assert(s);
  896. tor_assert(*s);
  897. tor_assert(dest);
  898. start = *s;
  899. if (!eos)
  900. eos = *s + strlen(*s);
  901. tor_assert(eos >= *s);
  902. while (1) {
  903. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  904. break;
  905. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  906. if (end)
  907. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  908. if (end)
  909. end += strlen("\n-----END SIGNATURE-----\n");
  910. if (!end)
  911. break;
  912. elt = NULL;
  913. if (have_extrainfo && want_extrainfo) {
  914. routerlist_t *rl = router_get_routerlist();
  915. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  916. saved_location != SAVED_IN_CACHE,
  917. rl->identity_map);
  918. if (extrainfo) {
  919. signed_desc = &extrainfo->cache_info;
  920. elt = extrainfo;
  921. }
  922. } else if (!have_extrainfo && !want_extrainfo) {
  923. router = router_parse_entry_from_string(*s, end,
  924. saved_location != SAVED_IN_CACHE,
  925. allow_annotations,
  926. prepend_annotations);
  927. if (router) {
  928. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  929. router->nickname, router_purpose_to_string(router->purpose));
  930. signed_desc = &router->cache_info;
  931. elt = router;
  932. }
  933. }
  934. if (!elt) {
  935. *s = end;
  936. continue;
  937. }
  938. if (saved_location != SAVED_NOWHERE) {
  939. signed_desc->saved_location = saved_location;
  940. signed_desc->saved_offset = *s - start;
  941. }
  942. *s = end;
  943. smartlist_add(dest, elt);
  944. }
  945. return 0;
  946. }
  947. /* For debugging: define to count every descriptor digest we've seen so we
  948. * know if we need to try harder to avoid duplicate verifies. */
  949. #undef COUNT_DISTINCT_DIGESTS
  950. #ifdef COUNT_DISTINCT_DIGESTS
  951. static digestmap_t *verified_digests = NULL;
  952. #endif
  953. /** Log the total count of the number of distinct router digests we've ever
  954. * verified. When compared to the number of times we've verified routerdesc
  955. * signatures <i>in toto</i>, this will tell us if we're doing too much
  956. * multiple-verification. */
  957. void
  958. dump_distinct_digest_count(int severity)
  959. {
  960. #ifdef COUNT_DISTINCT_DIGESTS
  961. if (!verified_digests)
  962. verified_digests = digestmap_new();
  963. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  964. digestmap_size(verified_digests));
  965. #else
  966. (void)severity; /* suppress "unused parameter" warning */
  967. #endif
  968. }
  969. /** Helper function: reads a single router entry from *<b>s</b> ...
  970. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  971. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  972. * s through end into the signed_descriptor_body of the resulting
  973. * routerinfo_t.
  974. *
  975. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  976. * before the router; if it's false, reject the router if it's annotated. If
  977. * <b>prepend_annotations</b> is set, it should contain some annotations:
  978. * append them to the front of the router before parsing it, and keep them
  979. * around when caching the router.
  980. *
  981. * Only one of allow_annotations and prepend_annotations may be set.
  982. */
  983. routerinfo_t *
  984. router_parse_entry_from_string(const char *s, const char *end,
  985. int cache_copy, int allow_annotations,
  986. const char *prepend_annotations)
  987. {
  988. routerinfo_t *router = NULL;
  989. char digest[128];
  990. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  991. directory_token_t *tok;
  992. struct in_addr in;
  993. const char *start_of_annotations, *cp;
  994. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  995. int ok = 1;
  996. memarea_t *area = NULL;
  997. tor_assert(!allow_annotations || !prepend_annotations);
  998. if (!end) {
  999. end = s + strlen(s);
  1000. }
  1001. /* point 'end' to a point immediately after the final newline. */
  1002. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1003. --end;
  1004. area = memarea_new();
  1005. tokens = smartlist_create();
  1006. if (prepend_annotations) {
  1007. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  1008. routerdesc_token_table,TS_NOCHECK)) {
  1009. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1010. goto err;
  1011. }
  1012. }
  1013. start_of_annotations = s;
  1014. cp = tor_memstr(s, end-s, "\nrouter ");
  1015. if (!cp) {
  1016. if (end-s < 7 || strcmpstart(s, "router ")) {
  1017. log_warn(LD_DIR, "No router keyword found.");
  1018. goto err;
  1019. }
  1020. } else {
  1021. s = cp+1;
  1022. }
  1023. if (allow_annotations && start_of_annotations != s) {
  1024. if (tokenize_string(area,start_of_annotations,s,tokens,
  1025. routerdesc_token_table,TS_NOCHECK)) {
  1026. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1027. goto err;
  1028. }
  1029. }
  1030. if (router_get_router_hash(s, digest) < 0) {
  1031. log_warn(LD_DIR, "Couldn't compute router hash.");
  1032. goto err;
  1033. }
  1034. {
  1035. int flags = 0;
  1036. if (allow_annotations)
  1037. flags |= TS_ANNOTATIONS_OK;
  1038. if (prepend_annotations)
  1039. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  1040. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  1041. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1042. goto err;
  1043. }
  1044. }
  1045. if (smartlist_len(tokens) < 2) {
  1046. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1047. goto err;
  1048. }
  1049. tok = find_first_by_keyword(tokens, K_ROUTER);
  1050. tor_assert(tok->n_args >= 5);
  1051. router = tor_malloc_zero(sizeof(routerinfo_t));
  1052. router->country = -1;
  1053. router->cache_info.routerlist_index = -1;
  1054. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  1055. router->cache_info.signed_descriptor_len = end-s;
  1056. if (cache_copy) {
  1057. size_t len = router->cache_info.signed_descriptor_len +
  1058. router->cache_info.annotations_len;
  1059. char *cp =
  1060. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1061. if (prepend_annotations) {
  1062. memcpy(cp, prepend_annotations, prepend_len);
  1063. cp += prepend_len;
  1064. }
  1065. /* This assertion will always succeed.
  1066. * len == signed_desc_len + annotations_len
  1067. * == end-s + s-start_of_annotations + prepend_len
  1068. * == end-start_of_annotations + prepend_len
  1069. * We already wrote prepend_len bytes into the buffer; now we're
  1070. * writing end-start_of_annotations -NM. */
  1071. tor_assert(cp+(end-start_of_annotations) ==
  1072. router->cache_info.signed_descriptor_body+len);
  1073. memcpy(cp, start_of_annotations, end-start_of_annotations);
  1074. router->cache_info.signed_descriptor_body[len] = '\0';
  1075. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1076. }
  1077. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1078. router->nickname = tor_strdup(tok->args[0]);
  1079. if (!is_legal_nickname(router->nickname)) {
  1080. log_warn(LD_DIR,"Router nickname is invalid");
  1081. goto err;
  1082. }
  1083. router->address = tor_strdup(tok->args[1]);
  1084. if (!tor_inet_aton(router->address, &in)) {
  1085. log_warn(LD_DIR,"Router address is not an IP address.");
  1086. goto err;
  1087. }
  1088. router->addr = ntohl(in.s_addr);
  1089. router->or_port =
  1090. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1091. if (!ok) {
  1092. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1093. goto err;
  1094. }
  1095. router->dir_port =
  1096. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1097. if (!ok) {
  1098. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1099. goto err;
  1100. }
  1101. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  1102. tor_assert(tok && tok->n_args >= 3);
  1103. router->bandwidthrate = (int)
  1104. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1105. if (!ok) {
  1106. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1107. escaped(tok->args[0]));
  1108. goto err;
  1109. }
  1110. router->bandwidthburst =
  1111. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1112. if (!ok) {
  1113. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1114. goto err;
  1115. }
  1116. router->bandwidthcapacity = (int)
  1117. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1118. if (!ok) {
  1119. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1120. goto err;
  1121. }
  1122. if ((tok = find_first_by_keyword(tokens, A_PURPOSE))) {
  1123. tor_assert(tok->n_args != 0);
  1124. router->purpose = router_purpose_from_string(tok->args[0]);
  1125. } else {
  1126. router->purpose = ROUTER_PURPOSE_GENERAL;
  1127. }
  1128. router->cache_info.send_unencrypted =
  1129. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1130. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  1131. tor_assert(tok->n_args >= 1);
  1132. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1133. if (!ok) {
  1134. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1135. goto err;
  1136. }
  1137. }
  1138. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  1139. tor_assert(tok->n_args >= 1);
  1140. router->is_hibernating
  1141. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1142. }
  1143. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1144. tor_assert(tok);
  1145. tor_assert(tok->n_args == 1);
  1146. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1147. goto err;
  1148. tok = find_first_by_keyword(tokens, K_ONION_KEY);
  1149. tor_assert(tok);
  1150. router->onion_pkey = tok->key;
  1151. tok->key = NULL; /* Prevent free */
  1152. tok = find_first_by_keyword(tokens, K_SIGNING_KEY);
  1153. tor_assert(tok);
  1154. router->identity_pkey = tok->key;
  1155. tok->key = NULL; /* Prevent free */
  1156. if (crypto_pk_get_digest(router->identity_pkey,
  1157. router->cache_info.identity_digest)) {
  1158. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1159. }
  1160. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  1161. /* If there's a fingerprint line, it must match the identity digest. */
  1162. char d[DIGEST_LEN];
  1163. tor_assert(tok->n_args == 1);
  1164. tor_strstrip(tok->args[0], " ");
  1165. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1166. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1167. escaped(tok->args[0]));
  1168. goto err;
  1169. }
  1170. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  1171. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1172. tok->args[0]);
  1173. goto err;
  1174. }
  1175. }
  1176. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  1177. router->platform = tor_strdup(tok->args[0]);
  1178. }
  1179. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1180. router->contact_info = tor_strdup(tok->args[0]);
  1181. }
  1182. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  1183. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  1184. } else if (router->platform) {
  1185. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  1186. router->has_old_dnsworkers = 1;
  1187. }
  1188. exit_policy_tokens = find_all_exitpolicy(tokens);
  1189. if (!smartlist_len(exit_policy_tokens)) {
  1190. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1191. goto err;
  1192. }
  1193. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1194. if (router_add_exit_policy(router,t)<0) {
  1195. log_warn(LD_DIR,"Error in exit policy");
  1196. goto err;
  1197. });
  1198. policy_expand_private(&router->exit_policy);
  1199. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1200. int i;
  1201. router->declared_family = smartlist_create();
  1202. for (i=0;i<tok->n_args;++i) {
  1203. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1204. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1205. escaped(tok->args[i]));
  1206. goto err;
  1207. }
  1208. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1209. }
  1210. }
  1211. if ((tok = find_first_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1212. router->caches_extra_info = 1;
  1213. if ((tok = find_first_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS)))
  1214. router->allow_single_hop_exits = 1;
  1215. if ((tok = find_first_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1216. tor_assert(tok->n_args >= 1);
  1217. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1218. base16_decode(router->cache_info.extra_info_digest,
  1219. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1220. } else {
  1221. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1222. }
  1223. }
  1224. if ((tok = find_first_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
  1225. router->wants_to_be_hs_dir = 1;
  1226. }
  1227. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1228. tor_assert(tok);
  1229. note_crypto_pk_op(VERIFY_RTR);
  1230. #ifdef COUNT_DISTINCT_DIGESTS
  1231. if (!verified_digests)
  1232. verified_digests = digestmap_new();
  1233. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1234. #endif
  1235. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1236. "router descriptor") < 0)
  1237. goto err;
  1238. routerinfo_set_country(router);
  1239. if (!router->or_port) {
  1240. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1241. goto err;
  1242. }
  1243. if (!router->platform) {
  1244. router->platform = tor_strdup("<unknown>");
  1245. }
  1246. goto done;
  1247. err:
  1248. routerinfo_free(router);
  1249. router = NULL;
  1250. done:
  1251. if (tokens) {
  1252. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1253. smartlist_free(tokens);
  1254. }
  1255. if (exit_policy_tokens) {
  1256. smartlist_free(exit_policy_tokens);
  1257. }
  1258. if (area) {
  1259. DUMP_AREA(area, "routerinfo");
  1260. memarea_drop_all(area);
  1261. }
  1262. return router;
  1263. }
  1264. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1265. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1266. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1267. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1268. * as a map from router identity to routerinfo_t when looking up signing keys.
  1269. */
  1270. extrainfo_t *
  1271. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1272. int cache_copy, struct digest_ri_map_t *routermap)
  1273. {
  1274. extrainfo_t *extrainfo = NULL;
  1275. char digest[128];
  1276. smartlist_t *tokens = NULL;
  1277. directory_token_t *tok;
  1278. crypto_pk_env_t *key = NULL;
  1279. routerinfo_t *router = NULL;
  1280. memarea_t *area = NULL;
  1281. if (!end) {
  1282. end = s + strlen(s);
  1283. }
  1284. /* point 'end' to a point immediately after the final newline. */
  1285. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1286. --end;
  1287. if (router_get_extrainfo_hash(s, digest) < 0) {
  1288. log_warn(LD_DIR, "Couldn't compute router hash.");
  1289. return NULL;
  1290. }
  1291. tokens = smartlist_create();
  1292. area = memarea_new();
  1293. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1294. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1295. goto err;
  1296. }
  1297. if (smartlist_len(tokens) < 2) {
  1298. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1299. goto err;
  1300. }
  1301. tok = smartlist_get(tokens,0);
  1302. if (tok->tp != K_EXTRA_INFO) {
  1303. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1304. goto err;
  1305. }
  1306. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1307. extrainfo->cache_info.is_extrainfo = 1;
  1308. if (cache_copy)
  1309. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1310. extrainfo->cache_info.signed_descriptor_len = end-s;
  1311. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1312. tor_assert(tok->n_args >= 2);
  1313. if (!is_legal_nickname(tok->args[0])) {
  1314. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1315. goto err;
  1316. }
  1317. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1318. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1319. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1320. tok->args[1], HEX_DIGEST_LEN)) {
  1321. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1322. escaped(tok->args[1]));
  1323. goto err;
  1324. }
  1325. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1326. tor_assert(tok);
  1327. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1328. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1329. escaped(tok->args[0]));
  1330. goto err;
  1331. }
  1332. if (routermap &&
  1333. (router = digestmap_get((digestmap_t*)routermap,
  1334. extrainfo->cache_info.identity_digest))) {
  1335. key = router->identity_pkey;
  1336. }
  1337. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1338. tor_assert(tok);
  1339. if (strcmp(tok->object_type, "SIGNATURE") ||
  1340. tok->object_size < 128 || tok->object_size > 512) {
  1341. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1342. goto err;
  1343. }
  1344. if (key) {
  1345. note_crypto_pk_op(VERIFY_RTR);
  1346. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1347. goto err;
  1348. if (router)
  1349. extrainfo->cache_info.send_unencrypted =
  1350. router->cache_info.send_unencrypted;
  1351. } else {
  1352. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1353. tok->object_size);
  1354. extrainfo->pending_sig_len = tok->object_size;
  1355. }
  1356. goto done;
  1357. err:
  1358. if (extrainfo)
  1359. extrainfo_free(extrainfo);
  1360. extrainfo = NULL;
  1361. done:
  1362. if (tokens) {
  1363. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1364. smartlist_free(tokens);
  1365. }
  1366. if (area) {
  1367. DUMP_AREA(area, "extrainfo");
  1368. memarea_drop_all(area);
  1369. }
  1370. return extrainfo;
  1371. }
  1372. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1373. * the first character after the certificate. */
  1374. authority_cert_t *
  1375. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1376. {
  1377. authority_cert_t *cert = NULL, *old_cert;
  1378. smartlist_t *tokens = NULL;
  1379. char digest[DIGEST_LEN];
  1380. directory_token_t *tok;
  1381. char fp_declared[DIGEST_LEN];
  1382. char *eos;
  1383. size_t len;
  1384. int found;
  1385. memarea_t *area = NULL;
  1386. s = eat_whitespace(s);
  1387. eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1388. if (! eos) {
  1389. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1390. return NULL;
  1391. }
  1392. eos = strchr(eos+2, '\n');
  1393. tor_assert(eos);
  1394. ++eos;
  1395. len = eos - s;
  1396. tokens = smartlist_create();
  1397. area = memarea_new();
  1398. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1399. log_warn(LD_DIR, "Error tokenizing key certificate");
  1400. goto err;
  1401. }
  1402. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1403. "\ndir-key-certification", '\n') < 0)
  1404. goto err;
  1405. tok = smartlist_get(tokens, 0);
  1406. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1407. log_warn(LD_DIR,
  1408. "Key certificate does not begin with a recognized version (3).");
  1409. goto err;
  1410. }
  1411. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1412. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1413. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1414. tor_assert(tok && tok->key);
  1415. cert->signing_key = tok->key;
  1416. tok->key = NULL;
  1417. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1418. goto err;
  1419. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1420. tor_assert(tok && tok->key);
  1421. cert->identity_key = tok->key;
  1422. tok->key = NULL;
  1423. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1424. tor_assert(tok && tok->n_args);
  1425. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1426. strlen(tok->args[0]))) {
  1427. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1428. escaped(tok->args[0]));
  1429. goto err;
  1430. }
  1431. if (crypto_pk_get_digest(cert->identity_key,
  1432. cert->cache_info.identity_digest))
  1433. goto err;
  1434. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1435. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1436. "fingerprint");
  1437. goto err;
  1438. }
  1439. tok = find_first_by_keyword(tokens, K_DIR_ADDRESS);
  1440. if (tok) {
  1441. tor_assert(tok->n_args != 0);
  1442. if (parse_addr_port(LOG_WARN, tok->args[0], NULL, &cert->addr,
  1443. &cert->dir_port)<0) {
  1444. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1445. goto err;
  1446. }
  1447. }
  1448. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1449. tor_assert(tok);
  1450. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1451. goto err;
  1452. }
  1453. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1454. tor_assert(tok);
  1455. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1456. goto err;
  1457. }
  1458. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1459. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1460. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1461. goto err;
  1462. }
  1463. /* If we already have this cert, don't bother checking the signature. */
  1464. old_cert = authority_cert_get_by_digests(
  1465. cert->cache_info.identity_digest,
  1466. cert->signing_key_digest);
  1467. found = 0;
  1468. if (old_cert) {
  1469. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1470. * buy us much. */
  1471. if (old_cert->cache_info.signed_descriptor_len == len &&
  1472. old_cert->cache_info.signed_descriptor_body &&
  1473. !memcmp(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1474. log_debug(LD_DIR, "We already checked the signature on this "
  1475. "certificate; no need to do so again.");
  1476. found = 1;
  1477. }
  1478. }
  1479. if (!found) {
  1480. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1481. "key certificate")) {
  1482. goto err;
  1483. }
  1484. }
  1485. cert->cache_info.signed_descriptor_len = len;
  1486. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1487. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1488. cert->cache_info.signed_descriptor_body[len] = 0;
  1489. cert->cache_info.saved_location = SAVED_NOWHERE;
  1490. if (end_of_string) {
  1491. *end_of_string = eat_whitespace(eos);
  1492. }
  1493. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1494. smartlist_free(tokens);
  1495. if (area) {
  1496. DUMP_AREA(area, "authority cert");
  1497. memarea_drop_all(area);
  1498. }
  1499. return cert;
  1500. err:
  1501. authority_cert_free(cert);
  1502. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1503. smartlist_free(tokens);
  1504. if (area) {
  1505. DUMP_AREA(area, "authority cert");
  1506. memarea_drop_all(area);
  1507. }
  1508. return NULL;
  1509. }
  1510. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1511. * object (starting with "r " at the start of a line). If none is found,
  1512. * return the start of the next directory signature. If none is found, return
  1513. * the end of the string. */
  1514. static INLINE const char *
  1515. find_start_of_next_routerstatus(const char *s)
  1516. {
  1517. const char *eos = strstr(s, "\nr ");
  1518. if (eos) {
  1519. const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
  1520. if (eos2 && eos2 < eos)
  1521. return eos2;
  1522. else
  1523. return eos+1;
  1524. } else {
  1525. if ((eos = strstr(s, "\ndirectory-signature")))
  1526. return eos+1;
  1527. return s + strlen(s);
  1528. }
  1529. }
  1530. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1531. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1532. * object in the string, and advance *<b>s</b> to just after the end of the
  1533. * router status. Return NULL and advance *<b>s</b> on error.
  1534. *
  1535. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1536. * routerstatus but use <b>vote_rs</b> instead.
  1537. *
  1538. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1539. * consensus, and we should parse it according to the method used to
  1540. * make that consensus.
  1541. **/
  1542. static routerstatus_t *
  1543. routerstatus_parse_entry_from_string(memarea_t *area,
  1544. const char **s, smartlist_t *tokens,
  1545. networkstatus_t *vote,
  1546. vote_routerstatus_t *vote_rs,
  1547. int consensus_method)
  1548. {
  1549. const char *eos;
  1550. routerstatus_t *rs = NULL;
  1551. directory_token_t *tok;
  1552. char timebuf[ISO_TIME_LEN+1];
  1553. struct in_addr in;
  1554. tor_assert(tokens);
  1555. tor_assert(bool_eq(vote, vote_rs));
  1556. eos = find_start_of_next_routerstatus(*s);
  1557. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1558. log_warn(LD_DIR, "Error tokenizing router status");
  1559. goto err;
  1560. }
  1561. if (smartlist_len(tokens) < 1) {
  1562. log_warn(LD_DIR, "Impossibly short router status");
  1563. goto err;
  1564. }
  1565. tok = find_first_by_keyword(tokens, K_R);
  1566. tor_assert(tok);
  1567. tor_assert(tok->n_args >= 8);
  1568. if (vote_rs) {
  1569. rs = &vote_rs->status;
  1570. } else {
  1571. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1572. }
  1573. if (!is_legal_nickname(tok->args[0])) {
  1574. log_warn(LD_DIR,
  1575. "Invalid nickname %s in router status; skipping.",
  1576. escaped(tok->args[0]));
  1577. goto err;
  1578. }
  1579. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1580. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1581. log_warn(LD_DIR, "Error decoding identity digest %s",
  1582. escaped(tok->args[1]));
  1583. goto err;
  1584. }
  1585. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1586. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1587. escaped(tok->args[2]));
  1588. goto err;
  1589. }
  1590. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1591. tok->args[3], tok->args[4]) < 0 ||
  1592. parse_iso_time(timebuf, &rs->published_on)<0) {
  1593. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1594. tok->args[3], tok->args[4]);
  1595. goto err;
  1596. }
  1597. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1598. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1599. escaped(tok->args[5]));
  1600. goto err;
  1601. }
  1602. rs->addr = ntohl(in.s_addr);
  1603. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1604. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1605. tok = find_first_by_keyword(tokens, K_S);
  1606. if (tok && vote) {
  1607. int i;
  1608. vote_rs->flags = 0;
  1609. for (i=0; i < tok->n_args; ++i) {
  1610. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1611. if (p >= 0) {
  1612. vote_rs->flags |= (1<<p);
  1613. } else {
  1614. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1615. escaped(tok->args[i]));
  1616. goto err;
  1617. }
  1618. }
  1619. } else if (tok) {
  1620. int i;
  1621. for (i=0; i < tok->n_args; ++i) {
  1622. if (!strcmp(tok->args[i], "Exit"))
  1623. rs->is_exit = 1;
  1624. else if (!strcmp(tok->args[i], "Stable"))
  1625. rs->is_stable = 1;
  1626. else if (!strcmp(tok->args[i], "Fast"))
  1627. rs->is_fast = 1;
  1628. else if (!strcmp(tok->args[i], "Running"))
  1629. rs->is_running = 1;
  1630. else if (!strcmp(tok->args[i], "Named"))
  1631. rs->is_named = 1;
  1632. else if (!strcmp(tok->args[i], "Valid"))
  1633. rs->is_valid = 1;
  1634. else if (!strcmp(tok->args[i], "V2Dir"))
  1635. rs->is_v2_dir = 1;
  1636. else if (!strcmp(tok->args[i], "Guard"))
  1637. rs->is_possible_guard = 1;
  1638. else if (!strcmp(tok->args[i], "BadExit"))
  1639. rs->is_bad_exit = 1;
  1640. else if (!strcmp(tok->args[i], "BadDirectory"))
  1641. rs->is_bad_directory = 1;
  1642. else if (!strcmp(tok->args[i], "Authority"))
  1643. rs->is_authority = 1;
  1644. else if (!strcmp(tok->args[i], "Unnamed") &&
  1645. consensus_method >= 2) {
  1646. /* Unnamed is computed right by consensus method 2 and later. */
  1647. rs->is_unnamed = 1;
  1648. } else if (!strcmp(tok->args[i], "HSDir")) {
  1649. rs->is_hs_dir = 1;
  1650. }
  1651. }
  1652. }
  1653. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1654. tor_assert(tok->n_args == 1);
  1655. rs->version_known = 1;
  1656. if (strcmpstart(tok->args[0], "Tor ")) {
  1657. rs->version_supports_begindir = 1;
  1658. rs->version_supports_extrainfo_upload = 1;
  1659. rs->version_supports_conditional_consensus = 1;
  1660. } else {
  1661. rs->version_supports_begindir =
  1662. tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
  1663. rs->version_supports_extrainfo_upload =
  1664. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1665. rs->version_supports_v3_dir =
  1666. tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
  1667. rs->version_supports_conditional_consensus =
  1668. tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
  1669. }
  1670. if (vote_rs) {
  1671. vote_rs->version = tor_strdup(tok->args[0]);
  1672. }
  1673. }
  1674. /* handle weighting/bandwidth info */
  1675. if ((tok = find_first_by_keyword(tokens, K_W))) {
  1676. int i;
  1677. for (i=0; i < tok->n_args; ++i) {
  1678. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1679. int ok;
  1680. rs->bandwidth = tor_parse_ulong(strchr(tok->args[i], '=')+1, 10,
  1681. 0, UINT32_MAX, &ok, NULL);
  1682. if (!ok) {
  1683. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1684. goto err;
  1685. }
  1686. rs->has_bandwidth = 1;
  1687. }
  1688. }
  1689. }
  1690. /* parse exit policy summaries */
  1691. if ((tok = find_first_by_keyword(tokens, K_P))) {
  1692. tor_assert(tok->n_args == 1);
  1693. if (strcmpstart(tok->args[0], "accept ") &&
  1694. strcmpstart(tok->args[0], "reject ")) {
  1695. log_err(LD_DIR, "Unknown exit policy summary type %s.",
  1696. escaped(tok->args[0]));
  1697. goto err;
  1698. }
  1699. /* XXX weasel: parse this into ports and represent them somehow smart,
  1700. * maybe not here but somewhere on if we need it for the client.
  1701. * we should still parse it here to check it's valid tho.
  1702. */
  1703. rs->exitsummary = tor_strdup(tok->args[0]);
  1704. rs->has_exitsummary = 1;
  1705. }
  1706. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1707. rs->is_named = 0;
  1708. goto done;
  1709. err:
  1710. if (rs && !vote_rs)
  1711. routerstatus_free(rs);
  1712. rs = NULL;
  1713. done:
  1714. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1715. smartlist_clear(tokens);
  1716. if (area) {
  1717. DUMP_AREA(area, "routerstatus entry");
  1718. memarea_clear(area);
  1719. }
  1720. *s = eos;
  1721. return rs;
  1722. }
  1723. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1724. static int
  1725. _compare_routerstatus_entries(const void **_a, const void **_b)
  1726. {
  1727. const routerstatus_t *a = *_a, *b = *_b;
  1728. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1729. }
  1730. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1731. static void
  1732. _free_duplicate_routerstatus_entry(void *e)
  1733. {
  1734. log_warn(LD_DIR,
  1735. "Network-status has two entries for the same router. "
  1736. "Dropping one.");
  1737. routerstatus_free(e);
  1738. }
  1739. /** Given a v2 network-status object in <b>s</b>, try to
  1740. * parse it and return the result. Return NULL on failure. Check the
  1741. * signature of the network status, but do not (yet) check the signing key for
  1742. * authority.
  1743. */
  1744. networkstatus_v2_t *
  1745. networkstatus_v2_parse_from_string(const char *s)
  1746. {
  1747. const char *eos;
  1748. smartlist_t *tokens = smartlist_create();
  1749. smartlist_t *footer_tokens = smartlist_create();
  1750. networkstatus_v2_t *ns = NULL;
  1751. char ns_digest[DIGEST_LEN];
  1752. char tmp_digest[DIGEST_LEN];
  1753. struct in_addr in;
  1754. directory_token_t *tok;
  1755. int i;
  1756. memarea_t *area = NULL;
  1757. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1758. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1759. goto err;
  1760. }
  1761. area = memarea_new();
  1762. eos = find_start_of_next_routerstatus(s);
  1763. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  1764. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1765. goto err;
  1766. }
  1767. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1768. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1769. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1770. tor_assert(tok && tok->n_args >= 1);
  1771. if (strcmp(tok->args[0], "2")) {
  1772. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1773. "%s", escaped(tok->args[0]));
  1774. goto err;
  1775. }
  1776. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1777. tor_assert(tok);
  1778. tor_assert(tok->n_args >= 3);
  1779. ns->source_address = tor_strdup(tok->args[0]);
  1780. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1781. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1782. escaped(tok->args[1]));
  1783. goto err;
  1784. }
  1785. ns->source_addr = ntohl(in.s_addr);
  1786. ns->source_dirport =
  1787. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1788. if (ns->source_dirport == 0) {
  1789. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1790. goto err;
  1791. }
  1792. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1793. tor_assert(tok);
  1794. tor_assert(tok->n_args != 0);
  1795. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1796. strlen(tok->args[0]))) {
  1797. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1798. escaped(tok->args[0]));
  1799. goto err;
  1800. }
  1801. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1802. tor_assert(tok->n_args != 0);
  1803. ns->contact = tor_strdup(tok->args[0]);
  1804. }
  1805. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1806. tor_assert(tok && tok->key);
  1807. ns->signing_key = tok->key;
  1808. tok->key = NULL;
  1809. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1810. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1811. goto err;
  1812. }
  1813. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1814. log_warn(LD_DIR,
  1815. "network-status fingerprint did not match dir-signing-key");
  1816. goto err;
  1817. }
  1818. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1819. for (i=0; i < tok->n_args; ++i) {
  1820. if (!strcmp(tok->args[i], "Names"))
  1821. ns->binds_names = 1;
  1822. if (!strcmp(tok->args[i], "Versions"))
  1823. ns->recommends_versions = 1;
  1824. if (!strcmp(tok->args[i], "BadExits"))
  1825. ns->lists_bad_exits = 1;
  1826. if (!strcmp(tok->args[i], "BadDirectories"))
  1827. ns->lists_bad_directories = 1;
  1828. }
  1829. }
  1830. if (ns->recommends_versions) {
  1831. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1832. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1833. goto err;
  1834. }
  1835. ns->client_versions = tor_strdup(tok->args[0]);
  1836. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1837. tok->n_args<1) {
  1838. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1839. goto err;
  1840. }
  1841. ns->server_versions = tor_strdup(tok->args[0]);
  1842. }
  1843. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1844. tor_assert(tok);
  1845. tor_assert(tok->n_args == 1);
  1846. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1847. goto err;
  1848. }
  1849. ns->entries = smartlist_create();
  1850. s = eos;
  1851. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1852. smartlist_clear(tokens);
  1853. memarea_clear(area);
  1854. while (!strcmpstart(s, "r ")) {
  1855. routerstatus_t *rs;
  1856. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  1857. NULL, NULL, 0)))
  1858. smartlist_add(ns->entries, rs);
  1859. }
  1860. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1861. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1862. _free_duplicate_routerstatus_entry);
  1863. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1864. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1865. goto err;
  1866. }
  1867. if (smartlist_len(footer_tokens) < 1) {
  1868. log_warn(LD_DIR, "Too few items in network-status footer.");
  1869. goto err;
  1870. }
  1871. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1872. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1873. log_warn(LD_DIR,
  1874. "Expected network-status footer to end with a signature.");
  1875. goto err;
  1876. }
  1877. note_crypto_pk_op(VERIFY_DIR);
  1878. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1879. "network-status") < 0)
  1880. goto err;
  1881. goto done;
  1882. err:
  1883. if (ns)
  1884. networkstatus_v2_free(ns);
  1885. ns = NULL;
  1886. done:
  1887. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1888. smartlist_free(tokens);
  1889. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1890. smartlist_free(footer_tokens);
  1891. if (area) {
  1892. DUMP_AREA(area, "v2 networkstatus");
  1893. memarea_drop_all(area);
  1894. }
  1895. return ns;
  1896. }
  1897. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  1898. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  1899. networkstatus_t *
  1900. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  1901. networkstatus_type_t ns_type)
  1902. {
  1903. smartlist_t *tokens = smartlist_create();
  1904. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1905. networkstatus_voter_info_t *voter = NULL;
  1906. networkstatus_t *ns = NULL;
  1907. char ns_digest[DIGEST_LEN];
  1908. const char *cert, *end_of_header, *end_of_footer;
  1909. directory_token_t *tok;
  1910. int ok;
  1911. struct in_addr in;
  1912. int i, inorder, n_signatures = 0;
  1913. memarea_t *area = NULL, *rs_area = NULL;
  1914. tor_assert(s);
  1915. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1916. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1917. goto err;
  1918. }
  1919. area = memarea_new();
  1920. end_of_header = find_start_of_next_routerstatus(s);
  1921. if (tokenize_string(area, s, end_of_header, tokens,
  1922. (ns_type == NS_TYPE_CONSENSUS) ?
  1923. networkstatus_consensus_token_table :
  1924. networkstatus_token_table, 0)) {
  1925. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  1926. goto err;
  1927. }
  1928. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1929. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1930. if (ns_type != NS_TYPE_CONSENSUS) {
  1931. const char *end_of_cert = NULL;
  1932. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1933. goto err;
  1934. ++cert;
  1935. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  1936. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  1937. goto err;
  1938. }
  1939. tok = find_first_by_keyword(tokens, K_VOTE_STATUS);
  1940. tor_assert(tok);
  1941. tor_assert(tok->n_args != 0);
  1942. if (!strcmp(tok->args[0], "vote")) {
  1943. ns->type = NS_TYPE_VOTE;
  1944. } else if (!strcmp(tok->args[0], "consensus")) {
  1945. ns->type = NS_TYPE_CONSENSUS;
  1946. } else if (!strcmp(tok->args[0], "opinion")) {
  1947. ns->type = NS_TYPE_OPINION;
  1948. } else {
  1949. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  1950. escaped(tok->args[0]));
  1951. goto err;
  1952. }
  1953. if (ns_type != ns->type) {
  1954. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  1955. goto err;
  1956. }
  1957. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  1958. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1959. if (parse_iso_time(tok->args[0], &ns->published))
  1960. goto err;
  1961. ns->supported_methods = smartlist_create();
  1962. tok = find_first_by_keyword(tokens, K_CONSENSUS_METHODS);
  1963. if (tok) {
  1964. for (i=0; i < tok->n_args; ++i)
  1965. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  1966. } else {
  1967. smartlist_add(ns->supported_methods, tor_strdup("1"));
  1968. }
  1969. } else {
  1970. tok = find_first_by_keyword(tokens, K_CONSENSUS_METHOD);
  1971. if (tok) {
  1972. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  1973. &ok, NULL);
  1974. if (!ok)
  1975. goto err;
  1976. } else {
  1977. ns->consensus_method = 1;
  1978. }
  1979. }
  1980. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  1981. if (parse_iso_time(tok->args[0], &ns->valid_after))
  1982. goto err;
  1983. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  1984. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  1985. goto err;
  1986. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  1987. if (parse_iso_time(tok->args[0], &ns->valid_until))
  1988. goto err;
  1989. tok = find_first_by_keyword(tokens, K_VOTING_DELAY);
  1990. tor_assert(tok->n_args >= 2);
  1991. ns->vote_seconds =
  1992. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  1993. if (!ok)
  1994. goto err;
  1995. ns->dist_seconds =
  1996. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  1997. if (!ok)
  1998. goto err;
  1999. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2000. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2001. goto err;
  2002. }
  2003. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2004. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2005. goto err;
  2006. }
  2007. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2008. log_warn(LD_DIR, "Vote seconds is too short");
  2009. goto err;
  2010. }
  2011. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2012. log_warn(LD_DIR, "Dist seconds is too short");
  2013. goto err;
  2014. }
  2015. if ((tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2016. ns->client_versions = tor_strdup(tok->args[0]);
  2017. }
  2018. if ((tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2019. ns->server_versions = tor_strdup(tok->args[0]);
  2020. }
  2021. tok = find_first_by_keyword(tokens, K_KNOWN_FLAGS);
  2022. ns->known_flags = smartlist_create();
  2023. inorder = 1;
  2024. for (i = 0; i < tok->n_args; ++i) {
  2025. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2026. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2027. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2028. inorder = 0;
  2029. }
  2030. }
  2031. if (!inorder) {
  2032. log_warn(LD_DIR, "known-flags not in order");
  2033. goto err;
  2034. }
  2035. ns->voters = smartlist_create();
  2036. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2037. {
  2038. tok = _tok;
  2039. if (tok->tp == K_DIR_SOURCE) {
  2040. tor_assert(tok->n_args >= 6);
  2041. if (voter)
  2042. smartlist_add(ns->voters, voter);
  2043. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2044. if (ns->type != NS_TYPE_CONSENSUS)
  2045. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  2046. voter->nickname = tor_strdup(tok->args[0]);
  2047. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2048. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2049. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2050. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2051. "network-status vote.", escaped(tok->args[1]));
  2052. goto err;
  2053. }
  2054. if (ns->type != NS_TYPE_CONSENSUS &&
  2055. memcmp(ns->cert->cache_info.identity_digest,
  2056. voter->identity_digest, DIGEST_LEN)) {
  2057. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2058. goto err;
  2059. }
  2060. voter->address = tor_strdup(tok->args[2]);
  2061. if (!tor_inet_aton(tok->args[3], &in)) {
  2062. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2063. escaped(tok->args[3]));
  2064. goto err;
  2065. }
  2066. voter->addr = ntohl(in.s_addr);
  2067. voter->dir_port = (uint16_t)
  2068. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2069. if (!ok)
  2070. goto err;
  2071. voter->or_port = (uint16_t)
  2072. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2073. if (!ok)
  2074. goto err;
  2075. } else if (tok->tp == K_CONTACT) {
  2076. if (!voter || voter->contact) {
  2077. log_warn(LD_DIR, "contact element is out of place.");
  2078. goto err;
  2079. }
  2080. voter->contact = tor_strdup(tok->args[0]);
  2081. } else if (tok->tp == K_VOTE_DIGEST) {
  2082. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2083. tor_assert(tok->n_args >= 1);
  2084. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2085. log_warn(LD_DIR, "vote-digest element is out of place.");
  2086. goto err;
  2087. }
  2088. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2089. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2090. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2091. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2092. "network-status consensus.", escaped(tok->args[1]));
  2093. goto err;
  2094. }
  2095. }
  2096. });
  2097. if (voter) {
  2098. smartlist_add(ns->voters, voter);
  2099. voter = NULL;
  2100. }
  2101. if (smartlist_len(ns->voters) == 0) {
  2102. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2103. goto err;
  2104. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2105. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2106. goto err;
  2107. }
  2108. if (ns->type != NS_TYPE_CONSENSUS &&
  2109. (tok = find_first_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2110. int bad = 1;
  2111. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2112. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2113. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2114. tok->args[0], HEX_DIGEST_LEN)<0)
  2115. bad = 1;
  2116. else
  2117. bad = 0;
  2118. }
  2119. if (bad) {
  2120. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2121. escaped(tok->args[0]));
  2122. }
  2123. }
  2124. /* Parse routerstatus lines. */
  2125. rs_tokens = smartlist_create();
  2126. rs_area = memarea_new();
  2127. s = end_of_header;
  2128. ns->routerstatus_list = smartlist_create();
  2129. while (!strcmpstart(s, "r ")) {
  2130. if (ns->type != NS_TYPE_CONSENSUS) {
  2131. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2132. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2133. rs, 0))
  2134. smartlist_add(ns->routerstatus_list, rs);
  2135. else {
  2136. tor_free(rs->version);
  2137. tor_free(rs);
  2138. }
  2139. } else {
  2140. routerstatus_t *rs;
  2141. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2142. NULL, NULL,
  2143. ns->consensus_method)))
  2144. smartlist_add(ns->routerstatus_list, rs);
  2145. }
  2146. }
  2147. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2148. routerstatus_t *rs1, *rs2;
  2149. if (ns->type != NS_TYPE_CONSENSUS) {
  2150. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2151. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2152. rs1 = &a->status; rs2 = &b->status;
  2153. } else {
  2154. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2155. rs2 = smartlist_get(ns->routerstatus_list, i);
  2156. }
  2157. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  2158. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2159. "digest");
  2160. goto err;
  2161. }
  2162. }
  2163. /* Parse footer; check signature. */
  2164. footer_tokens = smartlist_create();
  2165. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2166. ++end_of_footer;
  2167. else
  2168. end_of_footer = s + strlen(s);
  2169. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2170. networkstatus_vote_footer_token_table, 0)) {
  2171. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2172. goto err;
  2173. }
  2174. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  2175. {
  2176. char declared_identity[DIGEST_LEN];
  2177. networkstatus_voter_info_t *v;
  2178. tok = _tok;
  2179. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2180. continue;
  2181. tor_assert(tok->n_args >= 2);
  2182. if (!tok->object_type ||
  2183. strcmp(tok->object_type, "SIGNATURE") ||
  2184. tok->object_size < 128 || tok->object_size > 512) {
  2185. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2186. goto err;
  2187. }
  2188. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2189. base16_decode(declared_identity, sizeof(declared_identity),
  2190. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2191. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2192. "network-status vote.", escaped(tok->args[0]));
  2193. goto err;
  2194. }
  2195. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2196. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2197. "any declared directory source.");
  2198. goto err;
  2199. }
  2200. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2201. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  2202. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2203. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2204. "network-status vote.", escaped(tok->args[1]));
  2205. goto err;
  2206. }
  2207. if (ns->type != NS_TYPE_CONSENSUS) {
  2208. if (memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  2209. DIGEST_LEN)) {
  2210. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2211. "network-status vote.");
  2212. goto err;
  2213. }
  2214. }
  2215. if (ns->type != NS_TYPE_CONSENSUS) {
  2216. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  2217. "network-status vote"))
  2218. goto err;
  2219. v->good_signature = 1;
  2220. } else {
  2221. if (tok->object_size >= INT_MAX)
  2222. goto err;
  2223. v->signature = tor_memdup(tok->object_body, tok->object_size);
  2224. v->signature_len = (int) tok->object_size;
  2225. }
  2226. ++n_signatures;
  2227. });
  2228. if (! n_signatures) {
  2229. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2230. goto err;
  2231. }
  2232. if (eos_out)
  2233. *eos_out = end_of_footer;
  2234. goto done;
  2235. err:
  2236. if (ns)
  2237. networkstatus_vote_free(ns);
  2238. ns = NULL;
  2239. done:
  2240. if (tokens) {
  2241. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2242. smartlist_free(tokens);
  2243. }
  2244. if (voter) {
  2245. tor_free(voter->nickname);
  2246. tor_free(voter->address);
  2247. tor_free(voter->contact);
  2248. tor_free(voter->signature);
  2249. tor_free(voter);
  2250. }
  2251. if (rs_tokens) {
  2252. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  2253. smartlist_free(rs_tokens);
  2254. }
  2255. if (footer_tokens) {
  2256. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  2257. smartlist_free(footer_tokens);
  2258. }
  2259. if (area) {
  2260. DUMP_AREA(area, "v3 networkstatus");
  2261. memarea_drop_all(area);
  2262. }
  2263. if (rs_area)
  2264. memarea_drop_all(rs_area);
  2265. return ns;
  2266. }
  2267. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2268. * <b>eos</b> and return the result. Return -1 on failure. */
  2269. ns_detached_signatures_t *
  2270. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2271. {
  2272. /* XXXX021 there is too much duplicate code here. */
  2273. directory_token_t *tok;
  2274. memarea_t *area = NULL;
  2275. smartlist_t *tokens = smartlist_create();
  2276. ns_detached_signatures_t *sigs =
  2277. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2278. if (!eos)
  2279. eos = s + strlen(s);
  2280. area = memarea_new();
  2281. if (tokenize_string(area,s, eos, tokens,
  2282. networkstatus_detached_signature_token_table, 0)) {
  2283. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2284. goto err;
  2285. }
  2286. tok = find_first_by_keyword(tokens, K_CONSENSUS_DIGEST);
  2287. if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
  2288. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2289. "networkstatus signatures");
  2290. goto err;
  2291. }
  2292. if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
  2293. tok->args[0], strlen(tok->args[0])) < 0) {
  2294. log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
  2295. "networkstatus signatures");
  2296. goto err;
  2297. }
  2298. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  2299. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2300. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2301. goto err;
  2302. }
  2303. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  2304. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2305. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2306. goto err;
  2307. }
  2308. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  2309. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2310. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2311. goto err;
  2312. }
  2313. sigs->signatures = smartlist_create();
  2314. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2315. {
  2316. char id_digest[DIGEST_LEN];
  2317. char sk_digest[DIGEST_LEN];
  2318. networkstatus_voter_info_t *voter;
  2319. tok = _tok;
  2320. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2321. continue;
  2322. tor_assert(tok->n_args >= 2);
  2323. if (!tok->object_type ||
  2324. strcmp(tok->object_type, "SIGNATURE") ||
  2325. tok->object_size < 128 || tok->object_size > 512) {
  2326. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2327. goto err;
  2328. }
  2329. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2330. base16_decode(id_digest, sizeof(id_digest),
  2331. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2332. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2333. "network-status vote.", escaped(tok->args[0]));
  2334. goto err;
  2335. }
  2336. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2337. base16_decode(sk_digest, sizeof(sk_digest),
  2338. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2339. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2340. "network-status vote.", escaped(tok->args[1]));
  2341. goto err;
  2342. }
  2343. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2344. memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
  2345. memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
  2346. if (tok->object_size >= INT_MAX)
  2347. goto err;
  2348. voter->signature = tor_memdup(tok->object_body, tok->object_size);
  2349. voter->signature_len = (int) tok->object_size;
  2350. smartlist_add(sigs->signatures, voter);
  2351. });
  2352. goto done;
  2353. err:
  2354. ns_detached_signatures_free(sigs);
  2355. sigs = NULL;
  2356. done:
  2357. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2358. smartlist_free(tokens);
  2359. if (area) {
  2360. DUMP_AREA(area, "detached signatures");
  2361. memarea_drop_all(area);
  2362. }
  2363. return sigs;
  2364. }
  2365. /** Parse the addr policy in the string <b>s</b> and return it. If
  2366. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2367. * ADDR_POLICY_REJECT) for items that specify no action.
  2368. */
  2369. addr_policy_t *
  2370. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  2371. {
  2372. directory_token_t *tok = NULL;
  2373. const char *cp, *eos;
  2374. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  2375. * But note that there can be an arbitrary amount of space between the
  2376. * accept and the address:mask/port element. */
  2377. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2378. addr_policy_t *r;
  2379. memarea_t *area = NULL;
  2380. s = eat_whitespace(s);
  2381. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2382. if (tor_snprintf(line, sizeof(line), "%s %s",
  2383. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2384. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2385. return NULL;
  2386. }
  2387. cp = line;
  2388. tor_strlower(line);
  2389. } else { /* assume an already well-formed address policy line */
  2390. cp = s;
  2391. }
  2392. eos = cp + strlen(cp);
  2393. area = memarea_new();
  2394. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  2395. if (tok->tp == _ERR) {
  2396. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2397. goto err;
  2398. }
  2399. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  2400. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  2401. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2402. goto err;
  2403. }
  2404. r = router_parse_addr_policy(tok);
  2405. goto done;
  2406. err:
  2407. r = NULL;
  2408. done:
  2409. token_free(tok);
  2410. if (area) {
  2411. DUMP_AREA(area, "policy item");
  2412. memarea_drop_all(area);
  2413. }
  2414. return r;
  2415. }
  2416. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2417. * <b>router</b>. Return 0 on success, -1 on failure. */
  2418. static int
  2419. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2420. {
  2421. addr_policy_t *newe;
  2422. newe = router_parse_addr_policy(tok);
  2423. if (!newe)
  2424. return -1;
  2425. if (! router->exit_policy)
  2426. router->exit_policy = smartlist_create();
  2427. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2428. tor_addr_family(&newe->addr) == AF_INET)
  2429. ||
  2430. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  2431. tor_addr_family(&newe->addr) == AF_INET6)) {
  2432. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  2433. "policy");
  2434. addr_policy_free(newe);
  2435. return -1;
  2436. }
  2437. smartlist_add(router->exit_policy, newe);
  2438. return 0;
  2439. }
  2440. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  2441. * a new exit_policy_t corresponding to the token. */
  2442. static addr_policy_t *
  2443. router_parse_addr_policy(directory_token_t *tok)
  2444. {
  2445. addr_policy_t newe;
  2446. char *arg;
  2447. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  2448. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  2449. if (tok->n_args != 1)
  2450. return NULL;
  2451. arg = tok->args[0];
  2452. if (!strcmpstart(arg,"private"))
  2453. return router_parse_addr_policy_private(tok);
  2454. memset(&newe, 0, sizeof(newe));
  2455. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2456. newe.policy_type = ADDR_POLICY_REJECT;
  2457. else
  2458. newe.policy_type = ADDR_POLICY_ACCEPT;
  2459. if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
  2460. &newe.prt_min, &newe.prt_max) < 0) {
  2461. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  2462. return NULL;
  2463. }
  2464. return addr_policy_get_canonical_entry(&newe);
  2465. }
  2466. /** Parse an exit policy line of the format "accept/reject private:...".
  2467. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  2468. * router descriptors until earlier versions are obsolete.
  2469. */
  2470. static addr_policy_t *
  2471. router_parse_addr_policy_private(directory_token_t *tok)
  2472. {
  2473. const char *arg;
  2474. uint16_t port_min, port_max;
  2475. addr_policy_t result;
  2476. arg = tok->args[0];
  2477. if (strcmpstart(arg, "private"))
  2478. return NULL;
  2479. arg += strlen("private");
  2480. arg = (char*) eat_whitespace(arg);
  2481. if (!arg || *arg != ':')
  2482. return NULL;
  2483. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  2484. return NULL;
  2485. memset(&result, 0, sizeof(result));
  2486. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2487. result.policy_type = ADDR_POLICY_REJECT;
  2488. else
  2489. result.policy_type = ADDR_POLICY_ACCEPT;
  2490. result.is_private = 1;
  2491. result.prt_min = port_min;
  2492. result.prt_max = port_max;
  2493. return addr_policy_get_canonical_entry(&result);
  2494. }
  2495. /** Log and exit if <b>t</b> is malformed */
  2496. void
  2497. assert_addr_policy_ok(smartlist_t *lst)
  2498. {
  2499. if (!lst) return;
  2500. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  2501. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2502. t->policy_type == ADDR_POLICY_ACCEPT);
  2503. tor_assert(t->prt_min <= t->prt_max);
  2504. });
  2505. }
  2506. /*
  2507. * Low-level tokenizer for router descriptors and directories.
  2508. */
  2509. /** Free all resources allocated for <b>tok</b> */
  2510. static void
  2511. token_free(directory_token_t *tok)
  2512. {
  2513. tor_assert(tok);
  2514. if (tok->key)
  2515. crypto_free_pk_env(tok->key);
  2516. }
  2517. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  2518. #define ALLOC(sz) memarea_alloc(area,sz)
  2519. #define STRDUP(str) memarea_strdup(area,str)
  2520. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  2521. #define RET_ERR(msg) \
  2522. STMT_BEGIN \
  2523. if (tok) token_free(tok); \
  2524. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  2525. tok->tp = _ERR; \
  2526. tok->error = STRDUP(msg); \
  2527. goto done_tokenizing; \
  2528. STMT_END
  2529. static INLINE directory_token_t *
  2530. token_check_object(memarea_t *area, const char *kwd,
  2531. directory_token_t *tok, obj_syntax o_syn)
  2532. {
  2533. char ebuf[128];
  2534. switch (o_syn) {
  2535. case NO_OBJ:
  2536. if (tok->object_body) {
  2537. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2538. RET_ERR(ebuf);
  2539. }
  2540. if (tok->key) {
  2541. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2542. RET_ERR(ebuf);
  2543. }
  2544. break;
  2545. case NEED_OBJ:
  2546. if (!tok->object_body) {
  2547. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2548. RET_ERR(ebuf);
  2549. }
  2550. break;
  2551. case NEED_KEY_1024:
  2552. case NEED_SKEY_1024:
  2553. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2554. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2555. kwd, (int)crypto_pk_keysize(tok->key));
  2556. RET_ERR(ebuf);
  2557. }
  2558. /* fall through */
  2559. case NEED_KEY:
  2560. if (!tok->key) {
  2561. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2562. }
  2563. if (o_syn != NEED_SKEY_1024) {
  2564. if (crypto_pk_key_is_private(tok->key)) {
  2565. tor_snprintf(ebuf, sizeof(ebuf),
  2566. "Private key given for %s, which wants a public key", kwd);
  2567. RET_ERR(ebuf);
  2568. }
  2569. } else { /* o_syn == NEED_SKEY_1024 */
  2570. if (!crypto_pk_key_is_private(tok->key)) {
  2571. tor_snprintf(ebuf, sizeof(ebuf),
  2572. "Public key given for %s, which wants a private key", kwd);
  2573. RET_ERR(ebuf);
  2574. }
  2575. }
  2576. break;
  2577. case OBJ_OK:
  2578. break;
  2579. }
  2580. done_tokenizing:
  2581. return tok;
  2582. }
  2583. /** Helper function: read the next token from *s, advance *s to the end of the
  2584. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2585. * of tokens in <b>table</b>.
  2586. */
  2587. static directory_token_t *
  2588. get_next_token(memarea_t *area,
  2589. const char **s, const char *eos, token_rule_t *table)
  2590. {
  2591. const char *next, *eol, *obstart;
  2592. size_t obname_len;
  2593. int i;
  2594. directory_token_t *tok;
  2595. obj_syntax o_syn = NO_OBJ;
  2596. char ebuf[128];
  2597. const char *kwd = "";
  2598. tor_assert(area);
  2599. tok = ALLOC_ZERO(sizeof(directory_token_t));
  2600. tok->tp = _ERR;
  2601. /* Set *s to first token, eol to end-of-line, next to after first token */
  2602. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2603. tor_assert(eos >= *s);
  2604. eol = memchr(*s, '\n', eos-*s);
  2605. if (!eol)
  2606. eol = eos;
  2607. next = find_whitespace_eos(*s, eol);
  2608. if (!strcmp_len(*s, "opt", next-*s)) {
  2609. /* Skip past an "opt" at the start of the line. */
  2610. *s = eat_whitespace_eos_no_nl(next, eol);
  2611. next = find_whitespace_eos(*s, eol);
  2612. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2613. RET_ERR("Unexpected EOF");
  2614. }
  2615. /* Search the table for the appropriate entry. (I tried a binary search
  2616. * instead, but it wasn't any faster.) */
  2617. for (i = 0; table[i].t ; ++i) {
  2618. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2619. /* We've found the keyword. */
  2620. kwd = table[i].t;
  2621. tok->tp = table[i].v;
  2622. o_syn = table[i].os;
  2623. *s = eat_whitespace_eos_no_nl(next, eol);
  2624. next = find_whitespace_eos(*s, eol); /* XXXX021 lower this. */
  2625. /* We go ahead whether there are arguments or not, so that tok->args is
  2626. * always set if we want arguments. */
  2627. if (table[i].concat_args) {
  2628. /* The keyword takes the line as a single argument */
  2629. tok->args = ALLOC(sizeof(char*));
  2630. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  2631. tok->n_args = 1;
  2632. } else {
  2633. /* This keyword takes multiple arguments. */
  2634. /* XXXX021 this code is still too complicated. */
  2635. char *mem = memarea_strndup(area, *s, eol-*s);
  2636. char *cp = mem;
  2637. int j = 0;
  2638. while (*cp) {
  2639. j++;
  2640. cp = (char*)find_whitespace(cp);
  2641. if (!cp || !*cp)
  2642. break;
  2643. cp = (char*)eat_whitespace(cp);
  2644. }
  2645. tok->n_args = j;
  2646. if (tok->n_args) {
  2647. tok->args = memarea_alloc(area, sizeof(char*)*tok->n_args);
  2648. cp = mem;
  2649. j = 0;
  2650. while (*cp) {
  2651. tok->args[j++] = cp;
  2652. cp = (char*)find_whitespace(cp);
  2653. if (!cp || !*cp)
  2654. break;
  2655. *cp++ = '\0';
  2656. cp = (char*)eat_whitespace(cp);
  2657. }
  2658. }
  2659. *s = eol;
  2660. }
  2661. if (tok->n_args < table[i].min_args) {
  2662. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2663. RET_ERR(ebuf);
  2664. } else if (tok->n_args > table[i].max_args) {
  2665. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2666. RET_ERR(ebuf);
  2667. }
  2668. break;
  2669. }
  2670. }
  2671. if (tok->tp == _ERR) {
  2672. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  2673. if (**s == '@')
  2674. tok->tp = _A_UNKNOWN;
  2675. else
  2676. tok->tp = K_OPT;
  2677. tok->args = ALLOC(sizeof(char*));
  2678. tok->args[0] = STRNDUP(*s, eol-*s);
  2679. tok->n_args = 1;
  2680. o_syn = OBJ_OK;
  2681. }
  2682. /* Check whether there's an object present */
  2683. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2684. tor_assert(eos >= *s);
  2685. eol = memchr(*s, '\n', eos-*s);
  2686. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2687. goto check_object;
  2688. obstart = *s; /* Set obstart to start of object spec */
  2689. tor_assert(eol >= (*s+16));
  2690. if (*s+11 >= eol-5 || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2691. strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */
  2692. RET_ERR("Malformed object: bad begin line");
  2693. }
  2694. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  2695. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2696. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2697. /* Go to the end of the object */
  2698. next = tor_memstr(*s, eos-*s, "-----END ");
  2699. if (!next) {
  2700. RET_ERR("Malformed object: missing object end line");
  2701. }
  2702. tor_assert(eos >= next);
  2703. eol = memchr(next, '\n', eos-next);
  2704. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2705. eol = eos;
  2706. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2707. if ((size_t)(eol-next) != 9+obname_len+5 ||
  2708. strcmp_len(next+9, tok->object_type, obname_len) ||
  2709. strcmp_len(eol-5, "-----", 5)) {
  2710. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2711. tok->object_type);
  2712. ebuf[sizeof(ebuf)-1] = '\0';
  2713. RET_ERR(ebuf);
  2714. }
  2715. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  2716. tok->key = crypto_new_pk_env();
  2717. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2718. RET_ERR("Couldn't parse public key.");
  2719. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  2720. tok->key = crypto_new_pk_env();
  2721. if (crypto_pk_read_private_key_from_string(tok->key, obstart))
  2722. RET_ERR("Couldn't parse private key.");
  2723. } else { /* If it's something else, try to base64-decode it */
  2724. int r;
  2725. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  2726. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2727. if (r<0)
  2728. RET_ERR("Malformed object: bad base64-encoded data");
  2729. tok->object_size = r;
  2730. }
  2731. *s = eol;
  2732. check_object:
  2733. tok = token_check_object(area, kwd, tok, o_syn);
  2734. done_tokenizing:
  2735. return tok;
  2736. #undef RET_ERR
  2737. #undef ALLOC
  2738. #undef ALLOC_ZERO
  2739. #undef STRDUP
  2740. #undef STRNDUP
  2741. }
  2742. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2743. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2744. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  2745. * entire string.
  2746. */
  2747. static int
  2748. tokenize_string(memarea_t *area,
  2749. const char *start, const char *end, smartlist_t *out,
  2750. token_rule_t *table, int flags)
  2751. {
  2752. const char **s;
  2753. directory_token_t *tok = NULL;
  2754. int counts[_NIL];
  2755. int i;
  2756. int first_nonannotation;
  2757. int prev_len = smartlist_len(out);
  2758. tor_assert(area);
  2759. s = &start;
  2760. if (!end)
  2761. end = start+strlen(start);
  2762. for (i = 0; i < _NIL; ++i)
  2763. counts[i] = 0;
  2764. while (*s < end && (!tok || tok->tp != _EOF)) {
  2765. tok = get_next_token(area, s, end, table);
  2766. if (tok->tp == _ERR) {
  2767. log_warn(LD_DIR, "parse error: %s", tok->error);
  2768. token_free(tok);
  2769. return -1;
  2770. }
  2771. ++counts[tok->tp];
  2772. smartlist_add(out, tok);
  2773. *s = eat_whitespace_eos(*s, end);
  2774. }
  2775. if (flags & TS_NOCHECK)
  2776. return 0;
  2777. if ((flags & TS_ANNOTATIONS_OK)) {
  2778. first_nonannotation = -1;
  2779. for (i = 0; i < smartlist_len(out); ++i) {
  2780. tok = smartlist_get(out, i);
  2781. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  2782. first_nonannotation = i;
  2783. break;
  2784. }
  2785. }
  2786. if (first_nonannotation < 0) {
  2787. log_warn(LD_DIR, "parse error: item contains only annotations");
  2788. return -1;
  2789. }
  2790. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  2791. tok = smartlist_get(out, i);
  2792. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2793. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  2794. return -1;
  2795. }
  2796. }
  2797. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  2798. if (first_nonannotation != prev_len) {
  2799. log_warn(LD_DIR, "parse error: Unexpectd annotations.");
  2800. return -1;
  2801. }
  2802. }
  2803. } else {
  2804. for (i=0; i < smartlist_len(out); ++i) {
  2805. tok = smartlist_get(out, i);
  2806. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2807. log_warn(LD_DIR, "parse error: no annotations allowed.");
  2808. return -1;
  2809. }
  2810. }
  2811. first_nonannotation = 0;
  2812. }
  2813. for (i = 0; table[i].t; ++i) {
  2814. if (counts[table[i].v] < table[i].min_cnt) {
  2815. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2816. return -1;
  2817. }
  2818. if (counts[table[i].v] > table[i].max_cnt) {
  2819. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2820. return -1;
  2821. }
  2822. if (table[i].pos & AT_START) {
  2823. if (smartlist_len(out) < 1 ||
  2824. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  2825. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2826. return -1;
  2827. }
  2828. }
  2829. if (table[i].pos & AT_END) {
  2830. if (smartlist_len(out) < 1 ||
  2831. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2832. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2833. return -1;
  2834. }
  2835. }
  2836. }
  2837. return 0;
  2838. }
  2839. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2840. * NULL if no such keyword is found.
  2841. */
  2842. static directory_token_t *
  2843. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  2844. {
  2845. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2846. return NULL;
  2847. }
  2848. /** Return a newly allocated smartlist of all accept or reject tokens in
  2849. * <b>s</b>.
  2850. */
  2851. static smartlist_t *
  2852. find_all_exitpolicy(smartlist_t *s)
  2853. {
  2854. smartlist_t *out = smartlist_create();
  2855. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2856. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  2857. t->tp == K_REJECT || t->tp == K_REJECT6)
  2858. smartlist_add(out,t));
  2859. return out;
  2860. }
  2861. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  2862. * occurrence of <b>start_str</b> through the first instance of c after the
  2863. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  2864. * <b>digest</b>; return 0 on success.
  2865. *
  2866. * If no such substring exists, return -1.
  2867. */
  2868. static int
  2869. router_get_hash_impl(const char *s, char *digest,
  2870. const char *start_str,
  2871. const char *end_str, char end_c)
  2872. {
  2873. char *start, *end;
  2874. start = strstr(s, start_str);
  2875. if (!start) {
  2876. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  2877. return -1;
  2878. }
  2879. if (start != s && *(start-1) != '\n') {
  2880. log_warn(LD_DIR,
  2881. "first occurrence of \"%s\" is not at the start of a line",
  2882. start_str);
  2883. return -1;
  2884. }
  2885. end = strstr(start+strlen(start_str), end_str);
  2886. if (!end) {
  2887. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  2888. return -1;
  2889. }
  2890. end = strchr(end+strlen(end_str), end_c);
  2891. if (!end) {
  2892. log_warn(LD_DIR,"couldn't find EOL");
  2893. return -1;
  2894. }
  2895. ++end;
  2896. if (crypto_digest(digest, start, end-start)) {
  2897. log_warn(LD_BUG,"couldn't compute digest");
  2898. return -1;
  2899. }
  2900. return 0;
  2901. }
  2902. /** Parse the Tor version of the platform string <b>platform</b>,
  2903. * and compare it to the version in <b>cutoff</b>. Return 1 if
  2904. * the router is at least as new as the cutoff, else return 0.
  2905. */
  2906. int
  2907. tor_version_as_new_as(const char *platform, const char *cutoff)
  2908. {
  2909. tor_version_t cutoff_version, router_version;
  2910. char *s, *s2, *start;
  2911. char tmp[128];
  2912. tor_assert(platform);
  2913. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  2914. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  2915. return 0;
  2916. }
  2917. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  2918. return 1;
  2919. start = (char *)eat_whitespace(platform+3);
  2920. if (!*start) return 0;
  2921. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2922. s2 = (char*)eat_whitespace(s);
  2923. if (!strcmpstart(s2, "(r"))
  2924. s = (char*)find_whitespace(s2);
  2925. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2926. return 0;
  2927. strlcpy(tmp, start, s-start+1);
  2928. if (tor_version_parse(tmp, &router_version)<0) {
  2929. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2930. return 1; /* be safe and say yes */
  2931. }
  2932. /* Here's why we don't need to do any special handling for svn revisions:
  2933. * - If neither has an svn revision, we're fine.
  2934. * - If the router doesn't have an svn revision, we can't assume that it
  2935. * is "at least" any svn revision, so we need to return 0.
  2936. * - If the target version doesn't have an svn revision, any svn revision
  2937. * (or none at all) is good enough, so return 1.
  2938. * - If both target and router have an svn revision, we compare them.
  2939. */
  2940. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  2941. }
  2942. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  2943. * Return 0 on success, -1 on failure. */
  2944. int
  2945. tor_version_parse(const char *s, tor_version_t *out)
  2946. {
  2947. char *eos=NULL;
  2948. const char *cp=NULL;
  2949. /* Format is:
  2950. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  2951. */
  2952. tor_assert(s);
  2953. tor_assert(out);
  2954. memset(out, 0, sizeof(tor_version_t));
  2955. if (!strcasecmpstart(s, "Tor "))
  2956. s += 4;
  2957. /* Get major. */
  2958. out->major = (int)strtol(s,&eos,10);
  2959. if (!eos || eos==s || *eos != '.') return -1;
  2960. cp = eos+1;
  2961. /* Get minor */
  2962. out->minor = (int) strtol(cp,&eos,10);
  2963. if (!eos || eos==cp || *eos != '.') return -1;
  2964. cp = eos+1;
  2965. /* Get micro */
  2966. out->micro = (int) strtol(cp,&eos,10);
  2967. if (!eos || eos==cp) return -1;
  2968. if (!*eos) {
  2969. out->status = VER_RELEASE;
  2970. out->patchlevel = 0;
  2971. return 0;
  2972. }
  2973. cp = eos;
  2974. /* Get status */
  2975. if (*cp == '.') {
  2976. out->status = VER_RELEASE;
  2977. ++cp;
  2978. } else if (0==strncmp(cp, "pre", 3)) {
  2979. out->status = VER_PRE;
  2980. cp += 3;
  2981. } else if (0==strncmp(cp, "rc", 2)) {
  2982. out->status = VER_RC;
  2983. cp += 2;
  2984. } else {
  2985. return -1;
  2986. }
  2987. /* Get patchlevel */
  2988. out->patchlevel = (int) strtol(cp,&eos,10);
  2989. if (!eos || eos==cp) return -1;
  2990. cp = eos;
  2991. /* Get status tag. */
  2992. if (*cp == '-' || *cp == '.')
  2993. ++cp;
  2994. eos = (char*) find_whitespace(cp);
  2995. if (eos-cp >= (int)sizeof(out->status_tag))
  2996. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  2997. else {
  2998. memcpy(out->status_tag, cp, eos-cp);
  2999. out->status_tag[eos-cp] = 0;
  3000. }
  3001. cp = eat_whitespace(eos);
  3002. if (!strcmpstart(cp, "(r")) {
  3003. cp += 2;
  3004. out->svn_revision = (int) strtol(cp,&eos,10);
  3005. }
  3006. return 0;
  3007. }
  3008. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  3009. * b. */
  3010. int
  3011. tor_version_compare(tor_version_t *a, tor_version_t *b)
  3012. {
  3013. int i;
  3014. tor_assert(a);
  3015. tor_assert(b);
  3016. if ((i = a->major - b->major))
  3017. return i;
  3018. else if ((i = a->minor - b->minor))
  3019. return i;
  3020. else if ((i = a->micro - b->micro))
  3021. return i;
  3022. else if ((i = a->status - b->status))
  3023. return i;
  3024. else if ((i = a->patchlevel - b->patchlevel))
  3025. return i;
  3026. else if ((i = strcmp(a->status_tag, b->status_tag)))
  3027. return i;
  3028. else
  3029. return a->svn_revision - b->svn_revision;
  3030. }
  3031. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  3032. */
  3033. static int
  3034. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  3035. {
  3036. tor_assert(a);
  3037. tor_assert(b);
  3038. return ((a->major == b->major) &&
  3039. (a->minor == b->minor) &&
  3040. (a->micro == b->micro));
  3041. }
  3042. /** Helper: Given pointers to two strings describing tor versions, return -1
  3043. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  3044. * Used to sort a list of versions. */
  3045. static int
  3046. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  3047. {
  3048. const char *a = *_a, *b = *_b;
  3049. int ca, cb;
  3050. tor_version_t va, vb;
  3051. ca = tor_version_parse(a, &va);
  3052. cb = tor_version_parse(b, &vb);
  3053. /* If they both parse, compare them. */
  3054. if (!ca && !cb)
  3055. return tor_version_compare(&va,&vb);
  3056. /* If one parses, it comes first. */
  3057. if (!ca && cb)
  3058. return -1;
  3059. if (ca && !cb)
  3060. return 1;
  3061. /* If neither parses, compare strings. Also, the directory server admin
  3062. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  3063. return strcmp(a,b);
  3064. }
  3065. /** Sort a list of string-representations of versions in ascending order. */
  3066. void
  3067. sort_version_list(smartlist_t *versions, int remove_duplicates)
  3068. {
  3069. smartlist_sort(versions, _compare_tor_version_str_ptr);
  3070. if (remove_duplicates)
  3071. smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
  3072. }
  3073. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  3074. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  3075. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  3076. * encrypted introduction points to the newly allocated
  3077. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  3078. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  3079. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  3080. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  3081. * and -1 for failure.
  3082. */
  3083. int
  3084. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  3085. char *desc_id_out,
  3086. char **intro_points_encrypted_out,
  3087. size_t *intro_points_encrypted_size_out,
  3088. size_t *encoded_size_out,
  3089. const char **next_out, const char *desc)
  3090. {
  3091. rend_service_descriptor_t *result =
  3092. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3093. char desc_hash[DIGEST_LEN];
  3094. const char *eos;
  3095. smartlist_t *tokens = smartlist_create();
  3096. directory_token_t *tok;
  3097. char secret_id_part[DIGEST_LEN];
  3098. int i, version, num_ok=1;
  3099. smartlist_t *versions;
  3100. char public_key_hash[DIGEST_LEN];
  3101. char test_desc_id[DIGEST_LEN];
  3102. memarea_t *area = NULL;
  3103. tor_assert(desc);
  3104. /* Check if desc starts correctly. */
  3105. if (strncmp(desc, "rendezvous-service-descriptor ",
  3106. strlen("rendezvous-service-descriptor "))) {
  3107. log_info(LD_REND, "Descriptor does not start correctly.");
  3108. goto err;
  3109. }
  3110. /* Compute descriptor hash for later validation. */
  3111. if (router_get_hash_impl(desc, desc_hash,
  3112. "rendezvous-service-descriptor ",
  3113. "\nsignature", '\n') < 0) {
  3114. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  3115. goto err;
  3116. }
  3117. /* Determine end of string. */
  3118. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  3119. if (!eos)
  3120. eos = desc + strlen(desc);
  3121. else
  3122. eos = eos + 1;
  3123. /* Check length. */
  3124. if (strlen(desc) > REND_DESC_MAX_SIZE) {
  3125. log_warn(LD_REND, "Descriptor length is %i which exceeds "
  3126. "maximum rendezvous descriptor size of %i kilobytes.",
  3127. (int)strlen(desc), REND_DESC_MAX_SIZE);
  3128. goto err;
  3129. }
  3130. /* Tokenize descriptor. */
  3131. area = memarea_new();
  3132. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  3133. log_warn(LD_REND, "Error tokenizing descriptor.");
  3134. goto err;
  3135. }
  3136. /* Set next to next descriptor, if available. */
  3137. *next_out = eos;
  3138. /* Set length of encoded descriptor. */
  3139. *encoded_size_out = eos - desc;
  3140. /* Check min allowed length of token list. */
  3141. if (smartlist_len(tokens) < 7) {
  3142. log_warn(LD_REND, "Impossibly short descriptor.");
  3143. goto err;
  3144. }
  3145. /* Parse base32-encoded descriptor ID. */
  3146. tok = find_first_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  3147. tor_assert(tok);
  3148. tor_assert(tok == smartlist_get(tokens, 0));
  3149. tor_assert(tok->n_args == 1);
  3150. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  3151. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  3152. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  3153. goto err;
  3154. }
  3155. if (base32_decode(desc_id_out, DIGEST_LEN,
  3156. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  3157. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  3158. tok->args[0]);
  3159. goto err;
  3160. }
  3161. /* Parse descriptor version. */
  3162. tok = find_first_by_keyword(tokens, R_VERSION);
  3163. tor_assert(tok);
  3164. tor_assert(tok->n_args == 1);
  3165. result->version =
  3166. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  3167. if (result->version != 2 || !num_ok) {
  3168. /* If it's <2, it shouldn't be under this format. If the number
  3169. * is greater than 2, we bumped it because we broke backward
  3170. * compatibility. See how version numbers in our other formats
  3171. * work. */
  3172. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  3173. escaped(tok->args[0]));
  3174. goto err;
  3175. }
  3176. /* Parse public key. */
  3177. tok = find_first_by_keyword(tokens, R_PERMANENT_KEY);
  3178. tor_assert(tok);
  3179. result->pk = tok->key;
  3180. tok->key = NULL; /* Prevent free */
  3181. /* Parse secret ID part. */
  3182. tok = find_first_by_keyword(tokens, R_SECRET_ID_PART);
  3183. tor_assert(tok);
  3184. tor_assert(tok->n_args == 1);
  3185. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  3186. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  3187. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  3188. goto err;
  3189. }
  3190. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  3191. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  3192. tok->args[0]);
  3193. goto err;
  3194. }
  3195. /* Parse publication time -- up-to-date check is done when storing the
  3196. * descriptor. */
  3197. tok = find_first_by_keyword(tokens, R_PUBLICATION_TIME);
  3198. tor_assert(tok);
  3199. tor_assert(tok->n_args == 1);
  3200. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  3201. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  3202. goto err;
  3203. }
  3204. /* Parse protocol versions. */
  3205. tok = find_first_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  3206. tor_assert(tok);
  3207. tor_assert(tok->n_args == 1);
  3208. versions = smartlist_create();
  3209. smartlist_split_string(versions, tok->args[0], ",",
  3210. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3211. for (i = 0; i < smartlist_len(versions); i++) {
  3212. version = (int) tor_parse_long(smartlist_get(versions, i),
  3213. 10, 0, INT_MAX, &num_ok, NULL);
  3214. if (!num_ok) /* It's a string; let's ignore it. */
  3215. continue;
  3216. result->protocols |= 1 << version;
  3217. }
  3218. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  3219. smartlist_free(versions);
  3220. /* Parse encrypted introduction points. Don't verify. */
  3221. tok = find_first_by_keyword(tokens, R_INTRODUCTION_POINTS);
  3222. if (tok) {
  3223. if (strcmp(tok->object_type, "MESSAGE")) {
  3224. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  3225. "type MESSAGE");
  3226. goto err;
  3227. }
  3228. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  3229. tok->object_size);
  3230. *intro_points_encrypted_size_out = tok->object_size;
  3231. } else {
  3232. *intro_points_encrypted_out = NULL;
  3233. *intro_points_encrypted_size_out = 0;
  3234. }
  3235. /* Parse and verify signature. */
  3236. tok = find_first_by_keyword(tokens, R_SIGNATURE);
  3237. tor_assert(tok);
  3238. note_crypto_pk_op(VERIFY_RTR);
  3239. if (check_signature_token(desc_hash, tok, result->pk, 0,
  3240. "v2 rendezvous service descriptor") < 0)
  3241. goto err;
  3242. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3243. crypto_pk_get_digest(result->pk, public_key_hash);
  3244. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3245. secret_id_part);
  3246. if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3247. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3248. "computed descriptor ID.");
  3249. goto err;
  3250. }
  3251. goto done;
  3252. err:
  3253. if (result)
  3254. rend_service_descriptor_free(result);
  3255. result = NULL;
  3256. done:
  3257. if (tokens) {
  3258. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3259. smartlist_free(tokens);
  3260. }
  3261. if (area)
  3262. memarea_drop_all(area);
  3263. *parsed_out = result;
  3264. if (result)
  3265. return 0;
  3266. return -1;
  3267. }
  3268. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  3269. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  3270. * write the result to a newly allocated string that is pointed to by
  3271. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  3272. * Return 0 if decryption was successful and -1 otherwise. */
  3273. int
  3274. rend_decrypt_introduction_points(char **ipos_decrypted,
  3275. size_t *ipos_decrypted_size,
  3276. const char *descriptor_cookie,
  3277. const char *ipos_encrypted,
  3278. size_t ipos_encrypted_size)
  3279. {
  3280. tor_assert(ipos_encrypted);
  3281. tor_assert(descriptor_cookie);
  3282. if (ipos_encrypted_size < 2) {
  3283. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3284. "small.");
  3285. return -1;
  3286. }
  3287. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  3288. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  3289. session_key[CIPHER_KEY_LEN], *dec;
  3290. int declen, client_blocks;
  3291. size_t pos = 0, len, client_entries_len;
  3292. crypto_digest_env_t *digest;
  3293. crypto_cipher_env_t *cipher;
  3294. client_blocks = (int) ipos_encrypted[1];
  3295. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  3296. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  3297. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  3298. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3299. "small.");
  3300. return -1;
  3301. }
  3302. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  3303. digest = crypto_new_digest_env();
  3304. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  3305. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  3306. crypto_digest_get_digest(digest, client_id,
  3307. REND_BASIC_AUTH_CLIENT_ID_LEN);
  3308. crypto_free_digest_env(digest);
  3309. for (pos = 2; pos < 2 + client_entries_len;
  3310. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  3311. if (!memcmp(ipos_encrypted + pos, client_id,
  3312. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  3313. /* Attempt to decrypt introduction points. */
  3314. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3315. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  3316. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  3317. CIPHER_KEY_LEN) < 0) {
  3318. log_warn(LD_REND, "Could not decrypt session key for client.");
  3319. crypto_free_cipher_env(cipher);
  3320. return -1;
  3321. }
  3322. crypto_free_cipher_env(cipher);
  3323. cipher = crypto_create_init_cipher(session_key, 0);
  3324. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  3325. dec = tor_malloc(len);
  3326. declen = crypto_cipher_decrypt_with_iv(cipher, dec, len,
  3327. ipos_encrypted + 2 + client_entries_len,
  3328. ipos_encrypted_size - 2 - client_entries_len);
  3329. crypto_free_cipher_env(cipher);
  3330. if (declen < 0) {
  3331. log_warn(LD_REND, "Could not decrypt introduction point string.");
  3332. tor_free(dec);
  3333. return -1;
  3334. }
  3335. if (memcmpstart(dec, declen, "introduction-point ")) {
  3336. log_warn(LD_REND, "Decrypted introduction points don't "
  3337. "look like we could parse them.");
  3338. tor_free(dec);
  3339. continue;
  3340. }
  3341. *ipos_decrypted = dec;
  3342. *ipos_decrypted_size = declen;
  3343. return 0;
  3344. }
  3345. }
  3346. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  3347. "check your authorization for this service!");
  3348. return -1;
  3349. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  3350. crypto_cipher_env_t *cipher;
  3351. char *dec;
  3352. int declen;
  3353. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  3354. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3355. declen = crypto_cipher_decrypt_with_iv(cipher, dec,
  3356. ipos_encrypted_size -
  3357. CIPHER_IV_LEN - 1,
  3358. ipos_encrypted + 1,
  3359. ipos_encrypted_size - 1);
  3360. crypto_free_cipher_env(cipher);
  3361. if (declen < 0) {
  3362. log_warn(LD_REND, "Decrypting introduction points failed!");
  3363. tor_free(dec);
  3364. return -1;
  3365. }
  3366. *ipos_decrypted = dec;
  3367. *ipos_decrypted_size = declen;
  3368. return 0;
  3369. } else {
  3370. log_warn(LD_REND, "Unknown authorization type number: %d",
  3371. ipos_encrypted[0]);
  3372. return -1;
  3373. }
  3374. }
  3375. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  3376. * length <b>intro_points_encoded_size</b> and write the result to the
  3377. * descriptor in <b>parsed</b>; return the number of successfully parsed
  3378. * introduction points or -1 in case of a failure. */
  3379. int
  3380. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  3381. const char *intro_points_encoded,
  3382. size_t intro_points_encoded_size)
  3383. {
  3384. const char *current_ipo, *end_of_intro_points;
  3385. smartlist_t *tokens;
  3386. directory_token_t *tok;
  3387. rend_intro_point_t *intro;
  3388. extend_info_t *info;
  3389. int result, num_ok=1;
  3390. memarea_t *area = NULL;
  3391. tor_assert(parsed);
  3392. /** Function may only be invoked once. */
  3393. tor_assert(!parsed->intro_nodes);
  3394. tor_assert(intro_points_encoded);
  3395. tor_assert(intro_points_encoded_size > 0);
  3396. /* Consider one intro point after the other. */
  3397. current_ipo = intro_points_encoded;
  3398. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  3399. tokens = smartlist_create();
  3400. parsed->intro_nodes = smartlist_create();
  3401. area = memarea_new();
  3402. while (!memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  3403. "introduction-point ")) {
  3404. /* Determine end of string. */
  3405. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  3406. "\nintroduction-point ");
  3407. if (!eos)
  3408. eos = end_of_intro_points;
  3409. else
  3410. eos = eos+1;
  3411. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  3412. /* Free tokens and clear token list. */
  3413. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3414. smartlist_clear(tokens);
  3415. memarea_clear(area);
  3416. /* Tokenize string. */
  3417. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  3418. log_warn(LD_REND, "Error tokenizing introduction point");
  3419. goto err;
  3420. }
  3421. /* Advance to next introduction point, if available. */
  3422. current_ipo = eos;
  3423. /* Check minimum allowed length of introduction point. */
  3424. if (smartlist_len(tokens) < 5) {
  3425. log_warn(LD_REND, "Impossibly short introduction point.");
  3426. goto err;
  3427. }
  3428. /* Allocate new intro point and extend info. */
  3429. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3430. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3431. /* Parse identifier. */
  3432. tok = find_first_by_keyword(tokens, R_IPO_IDENTIFIER);
  3433. tor_assert(tok);
  3434. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3435. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3436. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3437. tok->args[0]);
  3438. rend_intro_point_free(intro);
  3439. goto err;
  3440. }
  3441. /* Write identifier to nickname. */
  3442. info->nickname[0] = '$';
  3443. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3444. info->identity_digest, DIGEST_LEN);
  3445. /* Parse IP address. */
  3446. tok = find_first_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3447. if (tor_addr_from_str(&info->addr, tok->args[0])<0) {
  3448. log_warn(LD_REND, "Could not parse introduction point address.");
  3449. rend_intro_point_free(intro);
  3450. goto err;
  3451. }
  3452. if (tor_addr_family(&info->addr) != AF_INET) {
  3453. log_warn(LD_REND, "Introduction point address was not ipv4.");
  3454. rend_intro_point_free(intro);
  3455. goto err;
  3456. }
  3457. /* Parse onion port. */
  3458. tok = find_first_by_keyword(tokens, R_IPO_ONION_PORT);
  3459. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3460. &num_ok,NULL);
  3461. if (!info->port || !num_ok) {
  3462. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3463. escaped(tok->args[0]));
  3464. rend_intro_point_free(intro);
  3465. goto err;
  3466. }
  3467. /* Parse onion key. */
  3468. tok = find_first_by_keyword(tokens, R_IPO_ONION_KEY);
  3469. info->onion_key = tok->key;
  3470. tok->key = NULL; /* Prevent free */
  3471. /* Parse service key. */
  3472. tok = find_first_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3473. intro->intro_key = tok->key;
  3474. tok->key = NULL; /* Prevent free */
  3475. /* Add extend info to list of introduction points. */
  3476. smartlist_add(parsed->intro_nodes, intro);
  3477. }
  3478. result = smartlist_len(parsed->intro_nodes);
  3479. goto done;
  3480. err:
  3481. result = -1;
  3482. done:
  3483. /* Free tokens and clear token list. */
  3484. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3485. smartlist_free(tokens);
  3486. if (area)
  3487. memarea_drop_all(area);
  3488. return result;
  3489. }
  3490. /** Parse the content of a client_key file in <b>ckstr</b> and add
  3491. * rend_authorized_client_t's for each parsed client to
  3492. * <b>parsed_clients</b>. Return the number of parsed clients as result
  3493. * or -1 for failure. */
  3494. int
  3495. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  3496. {
  3497. int result = -1;
  3498. smartlist_t *tokens;
  3499. directory_token_t *tok;
  3500. const char *current_entry = NULL;
  3501. memarea_t *area = NULL;
  3502. if (!ckstr || strlen(ckstr) == 0)
  3503. return -1;
  3504. tokens = smartlist_create();
  3505. /* Begin parsing with first entry, skipping comments or whitespace at the
  3506. * beginning. */
  3507. area = memarea_new();
  3508. current_entry = eat_whitespace(ckstr);
  3509. while (!strcmpstart(current_entry, "client-name ")) {
  3510. rend_authorized_client_t *parsed_entry;
  3511. size_t len;
  3512. char descriptor_cookie_base64[REND_DESC_COOKIE_LEN_BASE64+2+1];
  3513. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  3514. /* Determine end of string. */
  3515. const char *eos = strstr(current_entry, "\nclient-name ");
  3516. if (!eos)
  3517. eos = current_entry + strlen(current_entry);
  3518. else
  3519. eos = eos + 1;
  3520. /* Free tokens and clear token list. */
  3521. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3522. smartlist_clear(tokens);
  3523. memarea_clear(area);
  3524. /* Tokenize string. */
  3525. if (tokenize_string(area, current_entry, eos, tokens,
  3526. client_keys_token_table, 0)) {
  3527. log_warn(LD_REND, "Error tokenizing client keys file.");
  3528. goto err;
  3529. }
  3530. /* Advance to next entry, if available. */
  3531. current_entry = eos;
  3532. /* Check minimum allowed length of token list. */
  3533. if (smartlist_len(tokens) < 2) {
  3534. log_warn(LD_REND, "Impossibly short client key entry.");
  3535. goto err;
  3536. }
  3537. /* Parse client name. */
  3538. tok = find_first_by_keyword(tokens, C_CLIENT_NAME);
  3539. tor_assert(tok);
  3540. tor_assert(tok == smartlist_get(tokens, 0));
  3541. tor_assert(tok->n_args == 1);
  3542. len = strlen(tok->args[0]);
  3543. if (len < 1 || len > 19 ||
  3544. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  3545. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  3546. "between 1 and 19, and valid characters are "
  3547. "[A-Za-z0-9+-_].)", tok->args[0]);
  3548. goto err;
  3549. }
  3550. /* Check if client name is duplicate. */
  3551. if (strmap_get(parsed_clients, tok->args[0])) {
  3552. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  3553. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  3554. goto err;
  3555. }
  3556. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  3557. parsed_entry->client_name = tor_strdup(tok->args[0]);
  3558. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  3559. /* Parse client key. */
  3560. tok = find_first_by_keyword(tokens, C_CLIENT_KEY);
  3561. if (tok) {
  3562. parsed_entry->client_key = tok->key;
  3563. tok->key = NULL; /* Prevent free */
  3564. }
  3565. /* Parse descriptor cookie. */
  3566. tok = find_first_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  3567. tor_assert(tok);
  3568. tor_assert(tok->n_args == 1);
  3569. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  3570. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  3571. escaped(tok->args[0]));
  3572. goto err;
  3573. }
  3574. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  3575. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  3576. * cases. */
  3577. if ((base64_decode(descriptor_cookie_tmp, REND_DESC_COOKIE_LEN+2,
  3578. tok->args[0], REND_DESC_COOKIE_LEN_BASE64+2+1)
  3579. != REND_DESC_COOKIE_LEN)) {
  3580. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  3581. "%s", descriptor_cookie_base64);
  3582. goto err;
  3583. }
  3584. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  3585. REND_DESC_COOKIE_LEN);
  3586. }
  3587. result = strmap_size(parsed_clients);
  3588. goto done;
  3589. err:
  3590. result = -1;
  3591. done:
  3592. /* Free tokens and clear token list. */
  3593. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3594. smartlist_free(tokens);
  3595. if (area)
  3596. memarea_drop_all(area);
  3597. return result;
  3598. }