routerparse.c 135 KB

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