routerparse.c 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062
  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-2010, 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 (allow_annotations && start_of_annotations != s) {
  1046. if (tokenize_string(area,start_of_annotations,s,tokens,
  1047. routerdesc_token_table,TS_NOCHECK)) {
  1048. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1049. goto err;
  1050. }
  1051. }
  1052. if (router_get_router_hash(s, end - s, digest) < 0) {
  1053. log_warn(LD_DIR, "Couldn't compute router hash.");
  1054. goto err;
  1055. }
  1056. {
  1057. int flags = 0;
  1058. if (allow_annotations)
  1059. flags |= TS_ANNOTATIONS_OK;
  1060. if (prepend_annotations)
  1061. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  1062. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  1063. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1064. goto err;
  1065. }
  1066. }
  1067. if (smartlist_len(tokens) < 2) {
  1068. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1069. goto err;
  1070. }
  1071. tok = find_by_keyword(tokens, K_ROUTER);
  1072. tor_assert(tok->n_args >= 5);
  1073. router = tor_malloc_zero(sizeof(routerinfo_t));
  1074. router->country = -1;
  1075. router->cache_info.routerlist_index = -1;
  1076. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  1077. router->cache_info.signed_descriptor_len = end-s;
  1078. if (cache_copy) {
  1079. size_t len = router->cache_info.signed_descriptor_len +
  1080. router->cache_info.annotations_len;
  1081. char *cp =
  1082. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1083. if (prepend_annotations) {
  1084. memcpy(cp, prepend_annotations, prepend_len);
  1085. cp += prepend_len;
  1086. }
  1087. /* This assertion will always succeed.
  1088. * len == signed_desc_len + annotations_len
  1089. * == end-s + s-start_of_annotations + prepend_len
  1090. * == end-start_of_annotations + prepend_len
  1091. * We already wrote prepend_len bytes into the buffer; now we're
  1092. * writing end-start_of_annotations -NM. */
  1093. tor_assert(cp+(end-start_of_annotations) ==
  1094. router->cache_info.signed_descriptor_body+len);
  1095. memcpy(cp, start_of_annotations, end-start_of_annotations);
  1096. router->cache_info.signed_descriptor_body[len] = '\0';
  1097. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1098. }
  1099. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1100. router->nickname = tor_strdup(tok->args[0]);
  1101. if (!is_legal_nickname(router->nickname)) {
  1102. log_warn(LD_DIR,"Router nickname is invalid");
  1103. goto err;
  1104. }
  1105. router->address = tor_strdup(tok->args[1]);
  1106. if (!tor_inet_aton(router->address, &in)) {
  1107. log_warn(LD_DIR,"Router address is not an IP address.");
  1108. goto err;
  1109. }
  1110. router->addr = ntohl(in.s_addr);
  1111. router->or_port =
  1112. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1113. if (!ok) {
  1114. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1115. goto err;
  1116. }
  1117. router->dir_port =
  1118. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1119. if (!ok) {
  1120. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1121. goto err;
  1122. }
  1123. tok = find_by_keyword(tokens, K_BANDWIDTH);
  1124. tor_assert(tok->n_args >= 3);
  1125. router->bandwidthrate = (int)
  1126. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1127. if (!ok) {
  1128. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1129. escaped(tok->args[0]));
  1130. goto err;
  1131. }
  1132. router->bandwidthburst =
  1133. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1134. if (!ok) {
  1135. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1136. goto err;
  1137. }
  1138. router->bandwidthcapacity = (int)
  1139. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1140. if (!ok) {
  1141. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1142. goto err;
  1143. }
  1144. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  1145. tor_assert(tok->n_args);
  1146. router->purpose = router_purpose_from_string(tok->args[0]);
  1147. } else {
  1148. router->purpose = ROUTER_PURPOSE_GENERAL;
  1149. }
  1150. router->cache_info.send_unencrypted =
  1151. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1152. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  1153. tor_assert(tok->n_args >= 1);
  1154. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1155. if (!ok) {
  1156. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1157. goto err;
  1158. }
  1159. }
  1160. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  1161. tor_assert(tok->n_args >= 1);
  1162. router->is_hibernating
  1163. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1164. }
  1165. tok = find_by_keyword(tokens, K_PUBLISHED);
  1166. tor_assert(tok->n_args == 1);
  1167. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1168. goto err;
  1169. tok = find_by_keyword(tokens, K_ONION_KEY);
  1170. router->onion_pkey = tok->key;
  1171. tok->key = NULL; /* Prevent free */
  1172. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1173. router->identity_pkey = tok->key;
  1174. tok->key = NULL; /* Prevent free */
  1175. if (crypto_pk_get_digest(router->identity_pkey,
  1176. router->cache_info.identity_digest)) {
  1177. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1178. }
  1179. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1180. /* If there's a fingerprint line, it must match the identity digest. */
  1181. char d[DIGEST_LEN];
  1182. tor_assert(tok->n_args == 1);
  1183. tor_strstrip(tok->args[0], " ");
  1184. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1185. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1186. escaped(tok->args[0]));
  1187. goto err;
  1188. }
  1189. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  1190. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1191. tok->args[0]);
  1192. goto err;
  1193. }
  1194. }
  1195. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1196. router->platform = tor_strdup(tok->args[0]);
  1197. }
  1198. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1199. router->contact_info = tor_strdup(tok->args[0]);
  1200. }
  1201. if ((tok = find_opt_by_keyword(tokens, K_EVENTDNS))) {
  1202. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  1203. } else if (router->platform) {
  1204. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  1205. router->has_old_dnsworkers = 1;
  1206. }
  1207. exit_policy_tokens = find_all_exitpolicy(tokens);
  1208. if (!smartlist_len(exit_policy_tokens)) {
  1209. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1210. goto err;
  1211. }
  1212. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1213. if (router_add_exit_policy(router,t)<0) {
  1214. log_warn(LD_DIR,"Error in exit policy");
  1215. goto err;
  1216. });
  1217. policy_expand_private(&router->exit_policy);
  1218. if (policy_is_reject_star(router->exit_policy))
  1219. router->policy_is_reject_star = 1;
  1220. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1221. int i;
  1222. router->declared_family = smartlist_create();
  1223. for (i=0;i<tok->n_args;++i) {
  1224. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1225. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1226. escaped(tok->args[i]));
  1227. goto err;
  1228. }
  1229. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1230. }
  1231. }
  1232. if ((tok = find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1233. router->caches_extra_info = 1;
  1234. if ((tok = find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS)))
  1235. router->allow_single_hop_exits = 1;
  1236. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1237. tor_assert(tok->n_args >= 1);
  1238. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1239. base16_decode(router->cache_info.extra_info_digest,
  1240. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1241. } else {
  1242. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1243. }
  1244. }
  1245. if ((tok = find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
  1246. router->wants_to_be_hs_dir = 1;
  1247. }
  1248. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1249. note_crypto_pk_op(VERIFY_RTR);
  1250. #ifdef COUNT_DISTINCT_DIGESTS
  1251. if (!verified_digests)
  1252. verified_digests = digestmap_new();
  1253. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1254. #endif
  1255. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1256. "router descriptor") < 0)
  1257. goto err;
  1258. routerinfo_set_country(router);
  1259. if (!router->or_port) {
  1260. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1261. goto err;
  1262. }
  1263. if (!router->platform) {
  1264. router->platform = tor_strdup("<unknown>");
  1265. }
  1266. goto done;
  1267. err:
  1268. routerinfo_free(router);
  1269. router = NULL;
  1270. done:
  1271. if (tokens) {
  1272. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1273. smartlist_free(tokens);
  1274. }
  1275. if (exit_policy_tokens) {
  1276. smartlist_free(exit_policy_tokens);
  1277. }
  1278. if (area) {
  1279. DUMP_AREA(area, "routerinfo");
  1280. memarea_drop_all(area);
  1281. }
  1282. return router;
  1283. }
  1284. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1285. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1286. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1287. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1288. * as a map from router identity to routerinfo_t when looking up signing keys.
  1289. */
  1290. extrainfo_t *
  1291. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1292. int cache_copy, struct digest_ri_map_t *routermap)
  1293. {
  1294. extrainfo_t *extrainfo = NULL;
  1295. char digest[128];
  1296. smartlist_t *tokens = NULL;
  1297. directory_token_t *tok;
  1298. crypto_pk_env_t *key = NULL;
  1299. routerinfo_t *router = NULL;
  1300. memarea_t *area = NULL;
  1301. if (!end) {
  1302. end = s + strlen(s);
  1303. }
  1304. /* point 'end' to a point immediately after the final newline. */
  1305. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1306. --end;
  1307. if (router_get_extrainfo_hash(s, digest) < 0) {
  1308. log_warn(LD_DIR, "Couldn't compute router hash.");
  1309. goto err;
  1310. }
  1311. tokens = smartlist_create();
  1312. area = memarea_new();
  1313. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1314. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1315. goto err;
  1316. }
  1317. if (smartlist_len(tokens) < 2) {
  1318. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1319. goto err;
  1320. }
  1321. tok = smartlist_get(tokens,0);
  1322. if (tok->tp != K_EXTRA_INFO) {
  1323. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1324. goto err;
  1325. }
  1326. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1327. extrainfo->cache_info.is_extrainfo = 1;
  1328. if (cache_copy)
  1329. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1330. extrainfo->cache_info.signed_descriptor_len = end-s;
  1331. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1332. tor_assert(tok->n_args >= 2);
  1333. if (!is_legal_nickname(tok->args[0])) {
  1334. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1335. goto err;
  1336. }
  1337. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1338. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1339. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1340. tok->args[1], HEX_DIGEST_LEN)) {
  1341. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1342. escaped(tok->args[1]));
  1343. goto err;
  1344. }
  1345. tok = find_by_keyword(tokens, K_PUBLISHED);
  1346. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1347. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1348. escaped(tok->args[0]));
  1349. goto err;
  1350. }
  1351. if (routermap &&
  1352. (router = digestmap_get((digestmap_t*)routermap,
  1353. extrainfo->cache_info.identity_digest))) {
  1354. key = router->identity_pkey;
  1355. }
  1356. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1357. if (strcmp(tok->object_type, "SIGNATURE") ||
  1358. tok->object_size < 128 || tok->object_size > 512) {
  1359. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1360. goto err;
  1361. }
  1362. if (key) {
  1363. note_crypto_pk_op(VERIFY_RTR);
  1364. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1365. goto err;
  1366. if (router)
  1367. extrainfo->cache_info.send_unencrypted =
  1368. router->cache_info.send_unencrypted;
  1369. } else {
  1370. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1371. tok->object_size);
  1372. extrainfo->pending_sig_len = tok->object_size;
  1373. }
  1374. goto done;
  1375. err:
  1376. if (extrainfo)
  1377. extrainfo_free(extrainfo);
  1378. extrainfo = NULL;
  1379. done:
  1380. if (tokens) {
  1381. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1382. smartlist_free(tokens);
  1383. }
  1384. if (area) {
  1385. DUMP_AREA(area, "extrainfo");
  1386. memarea_drop_all(area);
  1387. }
  1388. return extrainfo;
  1389. }
  1390. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1391. * the first character after the certificate. */
  1392. authority_cert_t *
  1393. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1394. {
  1395. authority_cert_t *cert = NULL, *old_cert;
  1396. smartlist_t *tokens = NULL;
  1397. char digest[DIGEST_LEN];
  1398. directory_token_t *tok;
  1399. char fp_declared[DIGEST_LEN];
  1400. char *eos;
  1401. size_t len;
  1402. int found;
  1403. memarea_t *area = NULL;
  1404. s = eat_whitespace(s);
  1405. eos = strstr(s, "\ndir-key-certification");
  1406. if (! eos) {
  1407. log_warn(LD_DIR, "No signature found on key certificate");
  1408. return NULL;
  1409. }
  1410. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1411. if (! eos) {
  1412. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1413. return NULL;
  1414. }
  1415. eos = strchr(eos+2, '\n');
  1416. tor_assert(eos);
  1417. ++eos;
  1418. len = eos - s;
  1419. tokens = smartlist_create();
  1420. area = memarea_new();
  1421. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1422. log_warn(LD_DIR, "Error tokenizing key certificate");
  1423. goto err;
  1424. }
  1425. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  1426. "\ndir-key-certification", '\n') < 0)
  1427. goto err;
  1428. tok = smartlist_get(tokens, 0);
  1429. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1430. log_warn(LD_DIR,
  1431. "Key certificate does not begin with a recognized version (3).");
  1432. goto err;
  1433. }
  1434. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1435. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1436. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1437. tor_assert(tok->key);
  1438. cert->signing_key = tok->key;
  1439. tok->key = NULL;
  1440. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1441. goto err;
  1442. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1443. tor_assert(tok->key);
  1444. cert->identity_key = tok->key;
  1445. tok->key = NULL;
  1446. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1447. tor_assert(tok->n_args);
  1448. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1449. strlen(tok->args[0]))) {
  1450. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1451. escaped(tok->args[0]));
  1452. goto err;
  1453. }
  1454. if (crypto_pk_get_digest(cert->identity_key,
  1455. cert->cache_info.identity_digest))
  1456. goto err;
  1457. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1458. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1459. "fingerprint");
  1460. goto err;
  1461. }
  1462. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1463. if (tok) {
  1464. struct in_addr in;
  1465. char *address = NULL;
  1466. tor_assert(tok->n_args);
  1467. /* XXX021 use tor_addr_port_parse() below instead. -RD */
  1468. if (parse_addr_port(LOG_WARN, tok->args[0], &address, NULL,
  1469. &cert->dir_port)<0 ||
  1470. tor_inet_aton(address, &in) == 0) {
  1471. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1472. tor_free(address);
  1473. goto err;
  1474. }
  1475. cert->addr = ntohl(in.s_addr);
  1476. tor_free(address);
  1477. }
  1478. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1479. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1480. goto err;
  1481. }
  1482. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1483. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1484. goto err;
  1485. }
  1486. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1487. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1488. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1489. goto err;
  1490. }
  1491. /* If we already have this cert, don't bother checking the signature. */
  1492. old_cert = authority_cert_get_by_digests(
  1493. cert->cache_info.identity_digest,
  1494. cert->signing_key_digest);
  1495. found = 0;
  1496. if (old_cert) {
  1497. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1498. * buy us much. */
  1499. if (old_cert->cache_info.signed_descriptor_len == len &&
  1500. old_cert->cache_info.signed_descriptor_body &&
  1501. !memcmp(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1502. log_debug(LD_DIR, "We already checked the signature on this "
  1503. "certificate; no need to do so again.");
  1504. found = 1;
  1505. cert->is_cross_certified = old_cert->is_cross_certified;
  1506. }
  1507. }
  1508. if (!found) {
  1509. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1510. "key certificate")) {
  1511. goto err;
  1512. }
  1513. if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
  1514. /* XXXX Once all authorities generate cross-certified certificates,
  1515. * make this field mandatory. */
  1516. if (check_signature_token(cert->cache_info.identity_digest,
  1517. tok,
  1518. cert->signing_key,
  1519. CST_NO_CHECK_OBJTYPE,
  1520. "key cross-certification")) {
  1521. goto err;
  1522. }
  1523. cert->is_cross_certified = 1;
  1524. }
  1525. }
  1526. cert->cache_info.signed_descriptor_len = len;
  1527. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1528. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1529. cert->cache_info.signed_descriptor_body[len] = 0;
  1530. cert->cache_info.saved_location = SAVED_NOWHERE;
  1531. if (end_of_string) {
  1532. *end_of_string = eat_whitespace(eos);
  1533. }
  1534. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1535. smartlist_free(tokens);
  1536. if (area) {
  1537. DUMP_AREA(area, "authority cert");
  1538. memarea_drop_all(area);
  1539. }
  1540. return cert;
  1541. err:
  1542. authority_cert_free(cert);
  1543. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1544. smartlist_free(tokens);
  1545. if (area) {
  1546. DUMP_AREA(area, "authority cert");
  1547. memarea_drop_all(area);
  1548. }
  1549. return NULL;
  1550. }
  1551. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1552. * object (starting with "r " at the start of a line). If none is found,
  1553. * return the start of the next directory signature. If none is found, return
  1554. * the end of the string. */
  1555. static INLINE const char *
  1556. find_start_of_next_routerstatus(const char *s)
  1557. {
  1558. const char *eos = strstr(s, "\nr ");
  1559. if (eos) {
  1560. const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
  1561. if (eos2 && eos2 < eos)
  1562. return eos2;
  1563. else
  1564. return eos+1;
  1565. } else {
  1566. if ((eos = strstr(s, "\ndirectory-signature")))
  1567. return eos+1;
  1568. return s + strlen(s);
  1569. }
  1570. }
  1571. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1572. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1573. * object in the string, and advance *<b>s</b> to just after the end of the
  1574. * router status. Return NULL and advance *<b>s</b> on error.
  1575. *
  1576. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1577. * routerstatus but use <b>vote_rs</b> instead.
  1578. *
  1579. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1580. * consensus, and we should parse it according to the method used to
  1581. * make that consensus.
  1582. **/
  1583. static routerstatus_t *
  1584. routerstatus_parse_entry_from_string(memarea_t *area,
  1585. const char **s, smartlist_t *tokens,
  1586. networkstatus_t *vote,
  1587. vote_routerstatus_t *vote_rs,
  1588. int consensus_method)
  1589. {
  1590. const char *eos;
  1591. routerstatus_t *rs = NULL;
  1592. directory_token_t *tok;
  1593. char timebuf[ISO_TIME_LEN+1];
  1594. struct in_addr in;
  1595. tor_assert(tokens);
  1596. tor_assert(bool_eq(vote, vote_rs));
  1597. eos = find_start_of_next_routerstatus(*s);
  1598. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1599. log_warn(LD_DIR, "Error tokenizing router status");
  1600. goto err;
  1601. }
  1602. if (smartlist_len(tokens) < 1) {
  1603. log_warn(LD_DIR, "Impossibly short router status");
  1604. goto err;
  1605. }
  1606. tok = find_by_keyword(tokens, K_R);
  1607. tor_assert(tok->n_args >= 8);
  1608. if (vote_rs) {
  1609. rs = &vote_rs->status;
  1610. } else {
  1611. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1612. }
  1613. if (!is_legal_nickname(tok->args[0])) {
  1614. log_warn(LD_DIR,
  1615. "Invalid nickname %s in router status; skipping.",
  1616. escaped(tok->args[0]));
  1617. goto err;
  1618. }
  1619. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1620. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1621. log_warn(LD_DIR, "Error decoding identity digest %s",
  1622. escaped(tok->args[1]));
  1623. goto err;
  1624. }
  1625. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1626. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1627. escaped(tok->args[2]));
  1628. goto err;
  1629. }
  1630. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1631. tok->args[3], tok->args[4]) < 0 ||
  1632. parse_iso_time(timebuf, &rs->published_on)<0) {
  1633. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1634. tok->args[3], tok->args[4]);
  1635. goto err;
  1636. }
  1637. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1638. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1639. escaped(tok->args[5]));
  1640. goto err;
  1641. }
  1642. rs->addr = ntohl(in.s_addr);
  1643. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1644. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1645. tok = find_opt_by_keyword(tokens, K_S);
  1646. if (tok && vote) {
  1647. int i;
  1648. vote_rs->flags = 0;
  1649. for (i=0; i < tok->n_args; ++i) {
  1650. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1651. if (p >= 0) {
  1652. vote_rs->flags |= (1<<p);
  1653. } else {
  1654. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1655. escaped(tok->args[i]));
  1656. goto err;
  1657. }
  1658. }
  1659. } else if (tok) {
  1660. int i;
  1661. for (i=0; i < tok->n_args; ++i) {
  1662. if (!strcmp(tok->args[i], "Exit"))
  1663. rs->is_exit = 1;
  1664. else if (!strcmp(tok->args[i], "Stable"))
  1665. rs->is_stable = 1;
  1666. else if (!strcmp(tok->args[i], "Fast"))
  1667. rs->is_fast = 1;
  1668. else if (!strcmp(tok->args[i], "Running"))
  1669. rs->is_running = 1;
  1670. else if (!strcmp(tok->args[i], "Named"))
  1671. rs->is_named = 1;
  1672. else if (!strcmp(tok->args[i], "Valid"))
  1673. rs->is_valid = 1;
  1674. else if (!strcmp(tok->args[i], "V2Dir"))
  1675. rs->is_v2_dir = 1;
  1676. else if (!strcmp(tok->args[i], "Guard"))
  1677. rs->is_possible_guard = 1;
  1678. else if (!strcmp(tok->args[i], "BadExit"))
  1679. rs->is_bad_exit = 1;
  1680. else if (!strcmp(tok->args[i], "BadDirectory"))
  1681. rs->is_bad_directory = 1;
  1682. else if (!strcmp(tok->args[i], "Authority"))
  1683. rs->is_authority = 1;
  1684. else if (!strcmp(tok->args[i], "Unnamed") &&
  1685. consensus_method >= 2) {
  1686. /* Unnamed is computed right by consensus method 2 and later. */
  1687. rs->is_unnamed = 1;
  1688. } else if (!strcmp(tok->args[i], "HSDir")) {
  1689. rs->is_hs_dir = 1;
  1690. }
  1691. }
  1692. }
  1693. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1694. tor_assert(tok->n_args == 1);
  1695. rs->version_known = 1;
  1696. if (strcmpstart(tok->args[0], "Tor ")) {
  1697. rs->version_supports_begindir = 1;
  1698. rs->version_supports_extrainfo_upload = 1;
  1699. rs->version_supports_conditional_consensus = 1;
  1700. } else {
  1701. rs->version_supports_begindir =
  1702. tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
  1703. rs->version_supports_extrainfo_upload =
  1704. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1705. rs->version_supports_v3_dir =
  1706. tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
  1707. rs->version_supports_conditional_consensus =
  1708. tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
  1709. }
  1710. if (vote_rs) {
  1711. vote_rs->version = tor_strdup(tok->args[0]);
  1712. }
  1713. }
  1714. /* handle weighting/bandwidth info */
  1715. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1716. int i;
  1717. for (i=0; i < tok->n_args; ++i) {
  1718. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1719. int ok;
  1720. rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1721. 10, 0, UINT32_MAX,
  1722. &ok, NULL);
  1723. if (!ok) {
  1724. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1725. goto err;
  1726. }
  1727. rs->has_bandwidth = 1;
  1728. }
  1729. }
  1730. }
  1731. /* parse exit policy summaries */
  1732. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1733. tor_assert(tok->n_args == 1);
  1734. if (strcmpstart(tok->args[0], "accept ") &&
  1735. strcmpstart(tok->args[0], "reject ")) {
  1736. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1737. escaped(tok->args[0]));
  1738. goto err;
  1739. }
  1740. /* XXX weasel: parse this into ports and represent them somehow smart,
  1741. * maybe not here but somewhere on if we need it for the client.
  1742. * we should still parse it here to check it's valid tho.
  1743. */
  1744. rs->exitsummary = tor_strdup(tok->args[0]);
  1745. rs->has_exitsummary = 1;
  1746. }
  1747. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1748. rs->is_named = 0;
  1749. goto done;
  1750. err:
  1751. if (rs && !vote_rs)
  1752. routerstatus_free(rs);
  1753. rs = NULL;
  1754. done:
  1755. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1756. smartlist_clear(tokens);
  1757. if (area) {
  1758. DUMP_AREA(area, "routerstatus entry");
  1759. memarea_clear(area);
  1760. }
  1761. *s = eos;
  1762. return rs;
  1763. }
  1764. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1765. static int
  1766. _compare_routerstatus_entries(const void **_a, const void **_b)
  1767. {
  1768. const routerstatus_t *a = *_a, *b = *_b;
  1769. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1770. }
  1771. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1772. static void
  1773. _free_duplicate_routerstatus_entry(void *e)
  1774. {
  1775. log_warn(LD_DIR,
  1776. "Network-status has two entries for the same router. "
  1777. "Dropping one.");
  1778. routerstatus_free(e);
  1779. }
  1780. /** Given a v2 network-status object in <b>s</b>, try to
  1781. * parse it and return the result. Return NULL on failure. Check the
  1782. * signature of the network status, but do not (yet) check the signing key for
  1783. * authority.
  1784. */
  1785. networkstatus_v2_t *
  1786. networkstatus_v2_parse_from_string(const char *s)
  1787. {
  1788. const char *eos;
  1789. smartlist_t *tokens = smartlist_create();
  1790. smartlist_t *footer_tokens = smartlist_create();
  1791. networkstatus_v2_t *ns = NULL;
  1792. char ns_digest[DIGEST_LEN];
  1793. char tmp_digest[DIGEST_LEN];
  1794. struct in_addr in;
  1795. directory_token_t *tok;
  1796. int i;
  1797. memarea_t *area = NULL;
  1798. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1799. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1800. goto err;
  1801. }
  1802. area = memarea_new();
  1803. eos = find_start_of_next_routerstatus(s);
  1804. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  1805. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1806. goto err;
  1807. }
  1808. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1809. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1810. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1811. tor_assert(tok->n_args >= 1);
  1812. if (strcmp(tok->args[0], "2")) {
  1813. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1814. "%s", escaped(tok->args[0]));
  1815. goto err;
  1816. }
  1817. tok = find_by_keyword(tokens, K_DIR_SOURCE);
  1818. tor_assert(tok->n_args >= 3);
  1819. ns->source_address = tor_strdup(tok->args[0]);
  1820. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1821. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1822. escaped(tok->args[1]));
  1823. goto err;
  1824. }
  1825. ns->source_addr = ntohl(in.s_addr);
  1826. ns->source_dirport =
  1827. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1828. if (ns->source_dirport == 0) {
  1829. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1830. goto err;
  1831. }
  1832. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1833. tor_assert(tok->n_args);
  1834. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1835. strlen(tok->args[0]))) {
  1836. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1837. escaped(tok->args[0]));
  1838. goto err;
  1839. }
  1840. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1841. tor_assert(tok->n_args);
  1842. ns->contact = tor_strdup(tok->args[0]);
  1843. }
  1844. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1845. tor_assert(tok->key);
  1846. ns->signing_key = tok->key;
  1847. tok->key = NULL;
  1848. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1849. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1850. goto err;
  1851. }
  1852. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1853. log_warn(LD_DIR,
  1854. "network-status fingerprint did not match dir-signing-key");
  1855. goto err;
  1856. }
  1857. if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
  1858. for (i=0; i < tok->n_args; ++i) {
  1859. if (!strcmp(tok->args[i], "Names"))
  1860. ns->binds_names = 1;
  1861. if (!strcmp(tok->args[i], "Versions"))
  1862. ns->recommends_versions = 1;
  1863. if (!strcmp(tok->args[i], "BadExits"))
  1864. ns->lists_bad_exits = 1;
  1865. if (!strcmp(tok->args[i], "BadDirectories"))
  1866. ns->lists_bad_directories = 1;
  1867. }
  1868. }
  1869. if (ns->recommends_versions) {
  1870. if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1871. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1872. goto err;
  1873. }
  1874. ns->client_versions = tor_strdup(tok->args[0]);
  1875. if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1876. tok->n_args<1) {
  1877. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1878. goto err;
  1879. }
  1880. ns->server_versions = tor_strdup(tok->args[0]);
  1881. }
  1882. tok = find_by_keyword(tokens, K_PUBLISHED);
  1883. tor_assert(tok->n_args == 1);
  1884. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1885. goto err;
  1886. }
  1887. ns->entries = smartlist_create();
  1888. s = eos;
  1889. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1890. smartlist_clear(tokens);
  1891. memarea_clear(area);
  1892. while (!strcmpstart(s, "r ")) {
  1893. routerstatus_t *rs;
  1894. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  1895. NULL, NULL, 0)))
  1896. smartlist_add(ns->entries, rs);
  1897. }
  1898. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1899. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1900. _free_duplicate_routerstatus_entry);
  1901. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1902. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1903. goto err;
  1904. }
  1905. if (smartlist_len(footer_tokens) < 1) {
  1906. log_warn(LD_DIR, "Too few items in network-status footer.");
  1907. goto err;
  1908. }
  1909. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1910. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1911. log_warn(LD_DIR,
  1912. "Expected network-status footer to end with a signature.");
  1913. goto err;
  1914. }
  1915. note_crypto_pk_op(VERIFY_DIR);
  1916. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1917. "network-status") < 0)
  1918. goto err;
  1919. goto done;
  1920. err:
  1921. if (ns)
  1922. networkstatus_v2_free(ns);
  1923. ns = NULL;
  1924. done:
  1925. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1926. smartlist_free(tokens);
  1927. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1928. smartlist_free(footer_tokens);
  1929. if (area) {
  1930. DUMP_AREA(area, "v2 networkstatus");
  1931. memarea_drop_all(area);
  1932. }
  1933. return ns;
  1934. }
  1935. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  1936. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  1937. networkstatus_t *
  1938. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  1939. networkstatus_type_t ns_type)
  1940. {
  1941. smartlist_t *tokens = smartlist_create();
  1942. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1943. networkstatus_voter_info_t *voter = NULL;
  1944. networkstatus_t *ns = NULL;
  1945. char ns_digest[DIGEST_LEN];
  1946. const char *cert, *end_of_header, *end_of_footer;
  1947. directory_token_t *tok;
  1948. int ok;
  1949. struct in_addr in;
  1950. int i, inorder, n_signatures = 0;
  1951. memarea_t *area = NULL, *rs_area = NULL;
  1952. tor_assert(s);
  1953. if (eos_out)
  1954. *eos_out = NULL;
  1955. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1956. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1957. goto err;
  1958. }
  1959. area = memarea_new();
  1960. end_of_header = find_start_of_next_routerstatus(s);
  1961. if (tokenize_string(area, s, end_of_header, tokens,
  1962. (ns_type == NS_TYPE_CONSENSUS) ?
  1963. networkstatus_consensus_token_table :
  1964. networkstatus_token_table, 0)) {
  1965. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  1966. goto err;
  1967. }
  1968. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1969. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1970. if (ns_type != NS_TYPE_CONSENSUS) {
  1971. const char *end_of_cert = NULL;
  1972. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1973. goto err;
  1974. ++cert;
  1975. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  1976. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  1977. goto err;
  1978. }
  1979. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  1980. tor_assert(tok->n_args);
  1981. if (!strcmp(tok->args[0], "vote")) {
  1982. ns->type = NS_TYPE_VOTE;
  1983. } else if (!strcmp(tok->args[0], "consensus")) {
  1984. ns->type = NS_TYPE_CONSENSUS;
  1985. } else if (!strcmp(tok->args[0], "opinion")) {
  1986. ns->type = NS_TYPE_OPINION;
  1987. } else {
  1988. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  1989. escaped(tok->args[0]));
  1990. goto err;
  1991. }
  1992. if (ns_type != ns->type) {
  1993. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  1994. goto err;
  1995. }
  1996. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  1997. tok = find_by_keyword(tokens, K_PUBLISHED);
  1998. if (parse_iso_time(tok->args[0], &ns->published))
  1999. goto err;
  2000. ns->supported_methods = smartlist_create();
  2001. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2002. if (tok) {
  2003. for (i=0; i < tok->n_args; ++i)
  2004. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2005. } else {
  2006. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2007. }
  2008. } else {
  2009. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2010. if (tok) {
  2011. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2012. &ok, NULL);
  2013. if (!ok)
  2014. goto err;
  2015. } else {
  2016. ns->consensus_method = 1;
  2017. }
  2018. }
  2019. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2020. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2021. goto err;
  2022. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2023. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2024. goto err;
  2025. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2026. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2027. goto err;
  2028. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2029. tor_assert(tok->n_args >= 2);
  2030. ns->vote_seconds =
  2031. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2032. if (!ok)
  2033. goto err;
  2034. ns->dist_seconds =
  2035. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2036. if (!ok)
  2037. goto err;
  2038. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2039. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2040. goto err;
  2041. }
  2042. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2043. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2044. goto err;
  2045. }
  2046. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2047. log_warn(LD_DIR, "Vote seconds is too short");
  2048. goto err;
  2049. }
  2050. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2051. log_warn(LD_DIR, "Dist seconds is too short");
  2052. goto err;
  2053. }
  2054. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2055. ns->client_versions = tor_strdup(tok->args[0]);
  2056. }
  2057. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2058. ns->server_versions = tor_strdup(tok->args[0]);
  2059. }
  2060. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2061. ns->known_flags = smartlist_create();
  2062. inorder = 1;
  2063. for (i = 0; i < tok->n_args; ++i) {
  2064. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2065. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2066. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2067. inorder = 0;
  2068. }
  2069. }
  2070. if (!inorder) {
  2071. log_warn(LD_DIR, "known-flags not in order");
  2072. goto err;
  2073. }
  2074. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2075. if (tok) {
  2076. inorder = 1;
  2077. ns->net_params = smartlist_create();
  2078. for (i = 0; i < tok->n_args; ++i) {
  2079. int ok=0;
  2080. char *eq = strchr(tok->args[i], '=');
  2081. if (!eq) {
  2082. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2083. goto err;
  2084. }
  2085. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2086. if (!ok) {
  2087. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2088. goto err;
  2089. }
  2090. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2091. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2092. inorder = 0;
  2093. }
  2094. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  2095. }
  2096. if (!inorder) {
  2097. log_warn(LD_DIR, "params not in order");
  2098. goto err;
  2099. }
  2100. }
  2101. ns->voters = smartlist_create();
  2102. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2103. tok = _tok;
  2104. if (tok->tp == K_DIR_SOURCE) {
  2105. tor_assert(tok->n_args >= 6);
  2106. if (voter)
  2107. smartlist_add(ns->voters, voter);
  2108. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2109. if (ns->type != NS_TYPE_CONSENSUS)
  2110. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  2111. voter->nickname = tor_strdup(tok->args[0]);
  2112. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2113. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2114. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2115. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2116. "network-status vote.", escaped(tok->args[1]));
  2117. goto err;
  2118. }
  2119. if (ns->type != NS_TYPE_CONSENSUS &&
  2120. memcmp(ns->cert->cache_info.identity_digest,
  2121. voter->identity_digest, DIGEST_LEN)) {
  2122. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2123. goto err;
  2124. }
  2125. voter->address = tor_strdup(tok->args[2]);
  2126. if (!tor_inet_aton(tok->args[3], &in)) {
  2127. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2128. escaped(tok->args[3]));
  2129. goto err;
  2130. }
  2131. voter->addr = ntohl(in.s_addr);
  2132. voter->dir_port = (uint16_t)
  2133. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2134. if (!ok)
  2135. goto err;
  2136. voter->or_port = (uint16_t)
  2137. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2138. if (!ok)
  2139. goto err;
  2140. } else if (tok->tp == K_CONTACT) {
  2141. if (!voter || voter->contact) {
  2142. log_warn(LD_DIR, "contact element is out of place.");
  2143. goto err;
  2144. }
  2145. voter->contact = tor_strdup(tok->args[0]);
  2146. } else if (tok->tp == K_VOTE_DIGEST) {
  2147. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2148. tor_assert(tok->n_args >= 1);
  2149. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2150. log_warn(LD_DIR, "vote-digest element is out of place.");
  2151. goto err;
  2152. }
  2153. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2154. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2155. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2156. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2157. "network-status consensus.", escaped(tok->args[0]));
  2158. goto err;
  2159. }
  2160. }
  2161. } SMARTLIST_FOREACH_END(_tok);
  2162. if (voter) {
  2163. smartlist_add(ns->voters, voter);
  2164. voter = NULL;
  2165. }
  2166. if (smartlist_len(ns->voters) == 0) {
  2167. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2168. goto err;
  2169. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2170. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2171. goto err;
  2172. }
  2173. if (ns->type != NS_TYPE_CONSENSUS &&
  2174. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2175. int bad = 1;
  2176. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2177. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2178. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2179. tok->args[0], HEX_DIGEST_LEN)<0)
  2180. bad = 1;
  2181. else
  2182. bad = 0;
  2183. }
  2184. if (bad) {
  2185. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2186. escaped(tok->args[0]));
  2187. }
  2188. }
  2189. /* Parse routerstatus lines. */
  2190. rs_tokens = smartlist_create();
  2191. rs_area = memarea_new();
  2192. s = end_of_header;
  2193. ns->routerstatus_list = smartlist_create();
  2194. while (!strcmpstart(s, "r ")) {
  2195. if (ns->type != NS_TYPE_CONSENSUS) {
  2196. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2197. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2198. rs, 0))
  2199. smartlist_add(ns->routerstatus_list, rs);
  2200. else {
  2201. tor_free(rs->version);
  2202. tor_free(rs);
  2203. }
  2204. } else {
  2205. routerstatus_t *rs;
  2206. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2207. NULL, NULL,
  2208. ns->consensus_method)))
  2209. smartlist_add(ns->routerstatus_list, rs);
  2210. }
  2211. }
  2212. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2213. routerstatus_t *rs1, *rs2;
  2214. if (ns->type != NS_TYPE_CONSENSUS) {
  2215. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2216. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2217. rs1 = &a->status; rs2 = &b->status;
  2218. } else {
  2219. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2220. rs2 = smartlist_get(ns->routerstatus_list, i);
  2221. }
  2222. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  2223. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2224. "digest");
  2225. goto err;
  2226. }
  2227. }
  2228. /* Parse footer; check signature. */
  2229. footer_tokens = smartlist_create();
  2230. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2231. ++end_of_footer;
  2232. else
  2233. end_of_footer = s + strlen(s);
  2234. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2235. networkstatus_vote_footer_token_table, 0)) {
  2236. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2237. goto err;
  2238. }
  2239. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  2240. {
  2241. char declared_identity[DIGEST_LEN];
  2242. networkstatus_voter_info_t *v;
  2243. tok = _tok;
  2244. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2245. continue;
  2246. tor_assert(tok->n_args >= 2);
  2247. if (!tok->object_type ||
  2248. strcmp(tok->object_type, "SIGNATURE") ||
  2249. tok->object_size < 128 || tok->object_size > 512) {
  2250. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2251. goto err;
  2252. }
  2253. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2254. base16_decode(declared_identity, sizeof(declared_identity),
  2255. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2256. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2257. "network-status vote.", escaped(tok->args[0]));
  2258. goto err;
  2259. }
  2260. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2261. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2262. "any declared directory source.");
  2263. goto err;
  2264. }
  2265. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2266. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  2267. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2268. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2269. "network-status vote.", escaped(tok->args[1]));
  2270. goto err;
  2271. }
  2272. if (ns->type != NS_TYPE_CONSENSUS) {
  2273. if (memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  2274. DIGEST_LEN)) {
  2275. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2276. "network-status vote.");
  2277. goto err;
  2278. }
  2279. }
  2280. if (ns->type != NS_TYPE_CONSENSUS) {
  2281. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  2282. "network-status vote"))
  2283. goto err;
  2284. v->good_signature = 1;
  2285. } else {
  2286. if (tok->object_size >= INT_MAX)
  2287. goto err;
  2288. /* We already parsed a vote from this voter. Use the first one. */
  2289. if (v->signature) {
  2290. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  2291. "that contains two votes from the same voter. Ignoring "
  2292. "the second vote.");
  2293. continue;
  2294. }
  2295. v->signature = tor_memdup(tok->object_body, tok->object_size);
  2296. v->signature_len = (int) tok->object_size;
  2297. }
  2298. ++n_signatures;
  2299. });
  2300. if (! n_signatures) {
  2301. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2302. goto err;
  2303. }
  2304. if (eos_out)
  2305. *eos_out = end_of_footer;
  2306. goto done;
  2307. err:
  2308. if (ns)
  2309. networkstatus_vote_free(ns);
  2310. ns = NULL;
  2311. done:
  2312. if (tokens) {
  2313. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2314. smartlist_free(tokens);
  2315. }
  2316. if (voter) {
  2317. tor_free(voter->nickname);
  2318. tor_free(voter->address);
  2319. tor_free(voter->contact);
  2320. tor_free(voter->signature);
  2321. tor_free(voter);
  2322. }
  2323. if (rs_tokens) {
  2324. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  2325. smartlist_free(rs_tokens);
  2326. }
  2327. if (footer_tokens) {
  2328. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  2329. smartlist_free(footer_tokens);
  2330. }
  2331. if (area) {
  2332. DUMP_AREA(area, "v3 networkstatus");
  2333. memarea_drop_all(area);
  2334. }
  2335. if (rs_area)
  2336. memarea_drop_all(rs_area);
  2337. return ns;
  2338. }
  2339. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2340. * <b>eos</b> and return the result. Return -1 on failure. */
  2341. ns_detached_signatures_t *
  2342. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2343. {
  2344. /* XXXX there is too much duplicate shared between this function and
  2345. * networkstatus_parse_vote_from_string(). */
  2346. directory_token_t *tok;
  2347. memarea_t *area = NULL;
  2348. smartlist_t *tokens = smartlist_create();
  2349. ns_detached_signatures_t *sigs =
  2350. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2351. if (!eos)
  2352. eos = s + strlen(s);
  2353. area = memarea_new();
  2354. if (tokenize_string(area,s, eos, tokens,
  2355. networkstatus_detached_signature_token_table, 0)) {
  2356. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2357. goto err;
  2358. }
  2359. tok = find_by_keyword(tokens, K_CONSENSUS_DIGEST);
  2360. if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
  2361. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2362. "networkstatus signatures");
  2363. goto err;
  2364. }
  2365. if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
  2366. tok->args[0], strlen(tok->args[0])) < 0) {
  2367. log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
  2368. "networkstatus signatures");
  2369. goto err;
  2370. }
  2371. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2372. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2373. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2374. goto err;
  2375. }
  2376. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2377. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2378. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2379. goto err;
  2380. }
  2381. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2382. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2383. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2384. goto err;
  2385. }
  2386. sigs->signatures = smartlist_create();
  2387. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2388. {
  2389. char id_digest[DIGEST_LEN];
  2390. char sk_digest[DIGEST_LEN];
  2391. networkstatus_voter_info_t *voter;
  2392. tok = _tok;
  2393. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2394. continue;
  2395. tor_assert(tok->n_args >= 2);
  2396. if (!tok->object_type ||
  2397. strcmp(tok->object_type, "SIGNATURE") ||
  2398. tok->object_size < 128 || tok->object_size > 512) {
  2399. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2400. goto err;
  2401. }
  2402. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2403. base16_decode(id_digest, sizeof(id_digest),
  2404. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2405. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2406. "network-status vote.", escaped(tok->args[0]));
  2407. goto err;
  2408. }
  2409. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2410. base16_decode(sk_digest, sizeof(sk_digest),
  2411. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2412. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2413. "network-status vote.", escaped(tok->args[1]));
  2414. goto err;
  2415. }
  2416. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2417. memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
  2418. memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
  2419. if (tok->object_size >= INT_MAX)
  2420. goto err;
  2421. voter->signature = tor_memdup(tok->object_body, tok->object_size);
  2422. voter->signature_len = (int) tok->object_size;
  2423. smartlist_add(sigs->signatures, voter);
  2424. });
  2425. goto done;
  2426. err:
  2427. ns_detached_signatures_free(sigs);
  2428. sigs = NULL;
  2429. done:
  2430. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2431. smartlist_free(tokens);
  2432. if (area) {
  2433. DUMP_AREA(area, "detached signatures");
  2434. memarea_drop_all(area);
  2435. }
  2436. return sigs;
  2437. }
  2438. /** Parse the addr policy in the string <b>s</b> and return it. If
  2439. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2440. * ADDR_POLICY_REJECT) for items that specify no action.
  2441. */
  2442. addr_policy_t *
  2443. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  2444. {
  2445. directory_token_t *tok = NULL;
  2446. const char *cp, *eos;
  2447. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  2448. * But note that there can be an arbitrary amount of space between the
  2449. * accept and the address:mask/port element. */
  2450. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2451. addr_policy_t *r;
  2452. memarea_t *area = NULL;
  2453. s = eat_whitespace(s);
  2454. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2455. if (tor_snprintf(line, sizeof(line), "%s %s",
  2456. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2457. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2458. return NULL;
  2459. }
  2460. cp = line;
  2461. tor_strlower(line);
  2462. } else { /* assume an already well-formed address policy line */
  2463. cp = s;
  2464. }
  2465. eos = cp + strlen(cp);
  2466. area = memarea_new();
  2467. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  2468. if (tok->tp == _ERR) {
  2469. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2470. goto err;
  2471. }
  2472. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  2473. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  2474. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2475. goto err;
  2476. }
  2477. r = router_parse_addr_policy(tok);
  2478. goto done;
  2479. err:
  2480. r = NULL;
  2481. done:
  2482. token_free(tok);
  2483. if (area) {
  2484. DUMP_AREA(area, "policy item");
  2485. memarea_drop_all(area);
  2486. }
  2487. return r;
  2488. }
  2489. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2490. * <b>router</b>. Return 0 on success, -1 on failure. */
  2491. static int
  2492. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2493. {
  2494. addr_policy_t *newe;
  2495. newe = router_parse_addr_policy(tok);
  2496. if (!newe)
  2497. return -1;
  2498. if (! router->exit_policy)
  2499. router->exit_policy = smartlist_create();
  2500. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2501. tor_addr_family(&newe->addr) == AF_INET)
  2502. ||
  2503. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  2504. tor_addr_family(&newe->addr) == AF_INET6)) {
  2505. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  2506. "policy");
  2507. addr_policy_free(newe);
  2508. return -1;
  2509. }
  2510. smartlist_add(router->exit_policy, newe);
  2511. return 0;
  2512. }
  2513. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  2514. * a new exit_policy_t corresponding to the token. */
  2515. static addr_policy_t *
  2516. router_parse_addr_policy(directory_token_t *tok)
  2517. {
  2518. addr_policy_t newe;
  2519. char *arg;
  2520. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  2521. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  2522. if (tok->n_args != 1)
  2523. return NULL;
  2524. arg = tok->args[0];
  2525. if (!strcmpstart(arg,"private"))
  2526. return router_parse_addr_policy_private(tok);
  2527. memset(&newe, 0, sizeof(newe));
  2528. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2529. newe.policy_type = ADDR_POLICY_REJECT;
  2530. else
  2531. newe.policy_type = ADDR_POLICY_ACCEPT;
  2532. if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
  2533. &newe.prt_min, &newe.prt_max) < 0) {
  2534. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  2535. return NULL;
  2536. }
  2537. return addr_policy_get_canonical_entry(&newe);
  2538. }
  2539. /** Parse an exit policy line of the format "accept/reject private:...".
  2540. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  2541. * router descriptors until earlier versions are obsolete.
  2542. */
  2543. static addr_policy_t *
  2544. router_parse_addr_policy_private(directory_token_t *tok)
  2545. {
  2546. const char *arg;
  2547. uint16_t port_min, port_max;
  2548. addr_policy_t result;
  2549. arg = tok->args[0];
  2550. if (strcmpstart(arg, "private"))
  2551. return NULL;
  2552. arg += strlen("private");
  2553. arg = (char*) eat_whitespace(arg);
  2554. if (!arg || *arg != ':')
  2555. return NULL;
  2556. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  2557. return NULL;
  2558. memset(&result, 0, sizeof(result));
  2559. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2560. result.policy_type = ADDR_POLICY_REJECT;
  2561. else
  2562. result.policy_type = ADDR_POLICY_ACCEPT;
  2563. result.is_private = 1;
  2564. result.prt_min = port_min;
  2565. result.prt_max = port_max;
  2566. return addr_policy_get_canonical_entry(&result);
  2567. }
  2568. /** Log and exit if <b>t</b> is malformed */
  2569. void
  2570. assert_addr_policy_ok(smartlist_t *lst)
  2571. {
  2572. if (!lst) return;
  2573. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  2574. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2575. t->policy_type == ADDR_POLICY_ACCEPT);
  2576. tor_assert(t->prt_min <= t->prt_max);
  2577. });
  2578. }
  2579. /*
  2580. * Low-level tokenizer for router descriptors and directories.
  2581. */
  2582. /** Free all resources allocated for <b>tok</b> */
  2583. static void
  2584. token_free(directory_token_t *tok)
  2585. {
  2586. tor_assert(tok);
  2587. if (tok->key)
  2588. crypto_free_pk_env(tok->key);
  2589. }
  2590. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  2591. #define ALLOC(sz) memarea_alloc(area,sz)
  2592. #define STRDUP(str) memarea_strdup(area,str)
  2593. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  2594. #define RET_ERR(msg) \
  2595. STMT_BEGIN \
  2596. if (tok) token_free(tok); \
  2597. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  2598. tok->tp = _ERR; \
  2599. tok->error = STRDUP(msg); \
  2600. goto done_tokenizing; \
  2601. STMT_END
  2602. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  2603. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  2604. * Return <b>tok</b> on success, or a new _ERR token if the token didn't
  2605. * conform to the syntax we wanted.
  2606. **/
  2607. static INLINE directory_token_t *
  2608. token_check_object(memarea_t *area, const char *kwd,
  2609. directory_token_t *tok, obj_syntax o_syn)
  2610. {
  2611. char ebuf[128];
  2612. switch (o_syn) {
  2613. case NO_OBJ:
  2614. /* No object is allowed for this token. */
  2615. if (tok->object_body) {
  2616. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2617. RET_ERR(ebuf);
  2618. }
  2619. if (tok->key) {
  2620. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2621. RET_ERR(ebuf);
  2622. }
  2623. break;
  2624. case NEED_OBJ:
  2625. /* There must be a (non-key) object. */
  2626. if (!tok->object_body) {
  2627. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2628. RET_ERR(ebuf);
  2629. }
  2630. break;
  2631. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  2632. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  2633. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2634. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2635. kwd, (int)crypto_pk_keysize(tok->key));
  2636. RET_ERR(ebuf);
  2637. }
  2638. /* fall through */
  2639. case NEED_KEY: /* There must be some kind of key. */
  2640. if (!tok->key) {
  2641. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2642. RET_ERR(ebuf);
  2643. }
  2644. if (o_syn != NEED_SKEY_1024) {
  2645. if (crypto_pk_key_is_private(tok->key)) {
  2646. tor_snprintf(ebuf, sizeof(ebuf),
  2647. "Private key given for %s, which wants a public key", kwd);
  2648. RET_ERR(ebuf);
  2649. }
  2650. } else { /* o_syn == NEED_SKEY_1024 */
  2651. if (!crypto_pk_key_is_private(tok->key)) {
  2652. tor_snprintf(ebuf, sizeof(ebuf),
  2653. "Public key given for %s, which wants a private key", kwd);
  2654. RET_ERR(ebuf);
  2655. }
  2656. }
  2657. break;
  2658. case OBJ_OK:
  2659. /* Anything goes with this token. */
  2660. break;
  2661. }
  2662. done_tokenizing:
  2663. return tok;
  2664. }
  2665. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  2666. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  2667. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  2668. * all storage in <b>area</b>. Return the number of arguments parsed, or
  2669. * return -1 if there was an insanely high number of arguments. */
  2670. static INLINE int
  2671. get_token_arguments(memarea_t *area, directory_token_t *tok,
  2672. const char *s, const char *eol)
  2673. {
  2674. /** Largest number of arguments we'll accept to any token, ever. */
  2675. #define MAX_ARGS 512
  2676. char *mem = memarea_strndup(area, s, eol-s);
  2677. char *cp = mem;
  2678. int j = 0;
  2679. char *args[MAX_ARGS];
  2680. while (*cp) {
  2681. if (j == MAX_ARGS)
  2682. return -1;
  2683. args[j++] = cp;
  2684. cp = (char*)find_whitespace(cp);
  2685. if (!cp || !*cp)
  2686. break; /* End of the line. */
  2687. *cp++ = '\0';
  2688. cp = (char*)eat_whitespace(cp);
  2689. }
  2690. tok->n_args = j;
  2691. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  2692. return j;
  2693. #undef MAX_ARGS
  2694. }
  2695. /** Helper function: read the next token from *s, advance *s to the end of the
  2696. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2697. * of tokens in <b>table</b>.
  2698. */
  2699. static directory_token_t *
  2700. get_next_token(memarea_t *area,
  2701. const char **s, const char *eos, token_rule_t *table)
  2702. {
  2703. const char *next, *eol, *obstart;
  2704. size_t obname_len;
  2705. int i;
  2706. directory_token_t *tok;
  2707. obj_syntax o_syn = NO_OBJ;
  2708. char ebuf[128];
  2709. const char *kwd = "";
  2710. tor_assert(area);
  2711. tok = ALLOC_ZERO(sizeof(directory_token_t));
  2712. tok->tp = _ERR;
  2713. /* Set *s to first token, eol to end-of-line, next to after first token */
  2714. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2715. tor_assert(eos >= *s);
  2716. eol = memchr(*s, '\n', eos-*s);
  2717. if (!eol)
  2718. eol = eos;
  2719. next = find_whitespace_eos(*s, eol);
  2720. if (!strcmp_len(*s, "opt", next-*s)) {
  2721. /* Skip past an "opt" at the start of the line. */
  2722. *s = eat_whitespace_eos_no_nl(next, eol);
  2723. next = find_whitespace_eos(*s, eol);
  2724. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2725. RET_ERR("Unexpected EOF");
  2726. }
  2727. /* Search the table for the appropriate entry. (I tried a binary search
  2728. * instead, but it wasn't any faster.) */
  2729. for (i = 0; table[i].t ; ++i) {
  2730. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2731. /* We've found the keyword. */
  2732. kwd = table[i].t;
  2733. tok->tp = table[i].v;
  2734. o_syn = table[i].os;
  2735. *s = eat_whitespace_eos_no_nl(next, eol);
  2736. /* We go ahead whether there are arguments or not, so that tok->args is
  2737. * always set if we want arguments. */
  2738. if (table[i].concat_args) {
  2739. /* The keyword takes the line as a single argument */
  2740. tok->args = ALLOC(sizeof(char*));
  2741. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  2742. tok->n_args = 1;
  2743. } else {
  2744. /* This keyword takes multiple arguments. */
  2745. if (get_token_arguments(area, tok, *s, eol)<0) {
  2746. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  2747. RET_ERR(ebuf);
  2748. }
  2749. *s = eol;
  2750. }
  2751. if (tok->n_args < table[i].min_args) {
  2752. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2753. RET_ERR(ebuf);
  2754. } else if (tok->n_args > table[i].max_args) {
  2755. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2756. RET_ERR(ebuf);
  2757. }
  2758. break;
  2759. }
  2760. }
  2761. if (tok->tp == _ERR) {
  2762. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  2763. if (**s == '@')
  2764. tok->tp = _A_UNKNOWN;
  2765. else
  2766. tok->tp = K_OPT;
  2767. tok->args = ALLOC(sizeof(char*));
  2768. tok->args[0] = STRNDUP(*s, eol-*s);
  2769. tok->n_args = 1;
  2770. o_syn = OBJ_OK;
  2771. }
  2772. /* Check whether there's an object present */
  2773. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2774. tor_assert(eos >= *s);
  2775. eol = memchr(*s, '\n', eos-*s);
  2776. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2777. goto check_object;
  2778. obstart = *s; /* Set obstart to start of object spec */
  2779. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2780. strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */
  2781. RET_ERR("Malformed object: bad begin line");
  2782. }
  2783. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  2784. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2785. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2786. /* Go to the end of the object */
  2787. next = tor_memstr(*s, eos-*s, "-----END ");
  2788. if (!next) {
  2789. RET_ERR("Malformed object: missing object end line");
  2790. }
  2791. tor_assert(eos >= next);
  2792. eol = memchr(next, '\n', eos-next);
  2793. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2794. eol = eos;
  2795. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2796. if ((size_t)(eol-next) != 9+obname_len+5 ||
  2797. strcmp_len(next+9, tok->object_type, obname_len) ||
  2798. strcmp_len(eol-5, "-----", 5)) {
  2799. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2800. tok->object_type);
  2801. ebuf[sizeof(ebuf)-1] = '\0';
  2802. RET_ERR(ebuf);
  2803. }
  2804. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  2805. tok->key = crypto_new_pk_env();
  2806. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2807. RET_ERR("Couldn't parse public key.");
  2808. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  2809. tok->key = crypto_new_pk_env();
  2810. if (crypto_pk_read_private_key_from_string(tok->key, obstart))
  2811. RET_ERR("Couldn't parse private key.");
  2812. } else { /* If it's something else, try to base64-decode it */
  2813. int r;
  2814. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  2815. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2816. if (r<0)
  2817. RET_ERR("Malformed object: bad base64-encoded data");
  2818. tok->object_size = r;
  2819. }
  2820. *s = eol;
  2821. check_object:
  2822. tok = token_check_object(area, kwd, tok, o_syn);
  2823. done_tokenizing:
  2824. return tok;
  2825. #undef RET_ERR
  2826. #undef ALLOC
  2827. #undef ALLOC_ZERO
  2828. #undef STRDUP
  2829. #undef STRNDUP
  2830. }
  2831. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2832. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2833. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  2834. * entire string.
  2835. */
  2836. static int
  2837. tokenize_string(memarea_t *area,
  2838. const char *start, const char *end, smartlist_t *out,
  2839. token_rule_t *table, int flags)
  2840. {
  2841. const char **s;
  2842. directory_token_t *tok = NULL;
  2843. int counts[_NIL];
  2844. int i;
  2845. int first_nonannotation;
  2846. int prev_len = smartlist_len(out);
  2847. tor_assert(area);
  2848. s = &start;
  2849. if (!end)
  2850. end = start+strlen(start);
  2851. for (i = 0; i < _NIL; ++i)
  2852. counts[i] = 0;
  2853. while (*s < end && (!tok || tok->tp != _EOF)) {
  2854. tok = get_next_token(area, s, end, table);
  2855. if (tok->tp == _ERR) {
  2856. log_warn(LD_DIR, "parse error: %s", tok->error);
  2857. token_free(tok);
  2858. return -1;
  2859. }
  2860. ++counts[tok->tp];
  2861. smartlist_add(out, tok);
  2862. *s = eat_whitespace_eos(*s, end);
  2863. }
  2864. if (flags & TS_NOCHECK)
  2865. return 0;
  2866. if ((flags & TS_ANNOTATIONS_OK)) {
  2867. first_nonannotation = -1;
  2868. for (i = 0; i < smartlist_len(out); ++i) {
  2869. tok = smartlist_get(out, i);
  2870. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  2871. first_nonannotation = i;
  2872. break;
  2873. }
  2874. }
  2875. if (first_nonannotation < 0) {
  2876. log_warn(LD_DIR, "parse error: item contains only annotations");
  2877. return -1;
  2878. }
  2879. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  2880. tok = smartlist_get(out, i);
  2881. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2882. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  2883. return -1;
  2884. }
  2885. }
  2886. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  2887. if (first_nonannotation != prev_len) {
  2888. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  2889. return -1;
  2890. }
  2891. }
  2892. } else {
  2893. for (i=0; i < smartlist_len(out); ++i) {
  2894. tok = smartlist_get(out, i);
  2895. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2896. log_warn(LD_DIR, "parse error: no annotations allowed.");
  2897. return -1;
  2898. }
  2899. }
  2900. first_nonannotation = 0;
  2901. }
  2902. for (i = 0; table[i].t; ++i) {
  2903. if (counts[table[i].v] < table[i].min_cnt) {
  2904. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2905. return -1;
  2906. }
  2907. if (counts[table[i].v] > table[i].max_cnt) {
  2908. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2909. return -1;
  2910. }
  2911. if (table[i].pos & AT_START) {
  2912. if (smartlist_len(out) < 1 ||
  2913. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  2914. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2915. return -1;
  2916. }
  2917. }
  2918. if (table[i].pos & AT_END) {
  2919. if (smartlist_len(out) < 1 ||
  2920. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2921. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2922. return -1;
  2923. }
  2924. }
  2925. }
  2926. return 0;
  2927. }
  2928. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2929. * NULL if no such keyword is found.
  2930. */
  2931. static directory_token_t *
  2932. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  2933. {
  2934. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2935. return NULL;
  2936. }
  2937. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  2938. * with an assert if no such keyword is found.
  2939. */
  2940. static directory_token_t *
  2941. _find_by_keyword(smartlist_t *s, directory_keyword keyword,
  2942. const char *keyword_as_string)
  2943. {
  2944. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  2945. if (PREDICT_UNLIKELY(!tok)) {
  2946. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  2947. "been validated. Internal error.", keyword_as_string, (int)keyword);
  2948. tor_assert(tok);
  2949. }
  2950. return tok;
  2951. }
  2952. /** Return a newly allocated smartlist of all accept or reject tokens in
  2953. * <b>s</b>.
  2954. */
  2955. static smartlist_t *
  2956. find_all_exitpolicy(smartlist_t *s)
  2957. {
  2958. smartlist_t *out = smartlist_create();
  2959. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2960. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  2961. t->tp == K_REJECT || t->tp == K_REJECT6)
  2962. smartlist_add(out,t));
  2963. return out;
  2964. }
  2965. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  2966. * occurrence of <b>start_str</b> through the first instance of c after the
  2967. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  2968. * <b>digest</b>; return 0 on success.
  2969. *
  2970. * If no such substring exists, return -1.
  2971. */
  2972. static int
  2973. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  2974. const char *start_str,
  2975. const char *end_str, char end_c)
  2976. {
  2977. const char *start, *end;
  2978. start = tor_memstr(s, s_len, start_str);
  2979. if (!start) {
  2980. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  2981. return -1;
  2982. }
  2983. if (start != s && *(start-1) != '\n') {
  2984. log_warn(LD_DIR,
  2985. "first occurrence of \"%s\" is not at the start of a line",
  2986. start_str);
  2987. return -1;
  2988. }
  2989. end = tor_memstr(start+strlen(start_str),
  2990. s_len - (start-s) - strlen(start_str), end_str);
  2991. if (!end) {
  2992. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  2993. return -1;
  2994. }
  2995. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  2996. if (!end) {
  2997. log_warn(LD_DIR,"couldn't find EOL");
  2998. return -1;
  2999. }
  3000. ++end;
  3001. if (crypto_digest(digest, start, end-start)) {
  3002. log_warn(LD_BUG,"couldn't compute digest");
  3003. return -1;
  3004. }
  3005. return 0;
  3006. }
  3007. /** Parse the Tor version of the platform string <b>platform</b>,
  3008. * and compare it to the version in <b>cutoff</b>. Return 1 if
  3009. * the router is at least as new as the cutoff, else return 0.
  3010. */
  3011. int
  3012. tor_version_as_new_as(const char *platform, const char *cutoff)
  3013. {
  3014. tor_version_t cutoff_version, router_version;
  3015. char *s, *s2, *start;
  3016. char tmp[128];
  3017. tor_assert(platform);
  3018. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  3019. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  3020. return 0;
  3021. }
  3022. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  3023. return 1;
  3024. start = (char *)eat_whitespace(platform+3);
  3025. if (!*start) return 0;
  3026. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  3027. s2 = (char*)eat_whitespace(s);
  3028. if (!strcmpstart(s2, "(r"))
  3029. s = (char*)find_whitespace(s2);
  3030. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  3031. return 0;
  3032. strlcpy(tmp, start, s-start+1);
  3033. if (tor_version_parse(tmp, &router_version)<0) {
  3034. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  3035. return 1; /* be safe and say yes */
  3036. }
  3037. /* Here's why we don't need to do any special handling for svn revisions:
  3038. * - If neither has an svn revision, we're fine.
  3039. * - If the router doesn't have an svn revision, we can't assume that it
  3040. * is "at least" any svn revision, so we need to return 0.
  3041. * - If the target version doesn't have an svn revision, any svn revision
  3042. * (or none at all) is good enough, so return 1.
  3043. * - If both target and router have an svn revision, we compare them.
  3044. */
  3045. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  3046. }
  3047. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  3048. * Return 0 on success, -1 on failure. */
  3049. int
  3050. tor_version_parse(const char *s, tor_version_t *out)
  3051. {
  3052. char *eos=NULL;
  3053. const char *cp=NULL;
  3054. /* Format is:
  3055. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  3056. */
  3057. tor_assert(s);
  3058. tor_assert(out);
  3059. memset(out, 0, sizeof(tor_version_t));
  3060. if (!strcasecmpstart(s, "Tor "))
  3061. s += 4;
  3062. /* Get major. */
  3063. out->major = (int)strtol(s,&eos,10);
  3064. if (!eos || eos==s || *eos != '.') return -1;
  3065. cp = eos+1;
  3066. /* Get minor */
  3067. out->minor = (int) strtol(cp,&eos,10);
  3068. if (!eos || eos==cp || *eos != '.') return -1;
  3069. cp = eos+1;
  3070. /* Get micro */
  3071. out->micro = (int) strtol(cp,&eos,10);
  3072. if (!eos || eos==cp) return -1;
  3073. if (!*eos) {
  3074. out->status = VER_RELEASE;
  3075. out->patchlevel = 0;
  3076. return 0;
  3077. }
  3078. cp = eos;
  3079. /* Get status */
  3080. if (*cp == '.') {
  3081. out->status = VER_RELEASE;
  3082. ++cp;
  3083. } else if (0==strncmp(cp, "pre", 3)) {
  3084. out->status = VER_PRE;
  3085. cp += 3;
  3086. } else if (0==strncmp(cp, "rc", 2)) {
  3087. out->status = VER_RC;
  3088. cp += 2;
  3089. } else {
  3090. return -1;
  3091. }
  3092. /* Get patchlevel */
  3093. out->patchlevel = (int) strtol(cp,&eos,10);
  3094. if (!eos || eos==cp) return -1;
  3095. cp = eos;
  3096. /* Get status tag. */
  3097. if (*cp == '-' || *cp == '.')
  3098. ++cp;
  3099. eos = (char*) find_whitespace(cp);
  3100. if (eos-cp >= (int)sizeof(out->status_tag))
  3101. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  3102. else {
  3103. memcpy(out->status_tag, cp, eos-cp);
  3104. out->status_tag[eos-cp] = 0;
  3105. }
  3106. cp = eat_whitespace(eos);
  3107. if (!strcmpstart(cp, "(r")) {
  3108. cp += 2;
  3109. out->svn_revision = (int) strtol(cp,&eos,10);
  3110. }
  3111. return 0;
  3112. }
  3113. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  3114. * b. */
  3115. int
  3116. tor_version_compare(tor_version_t *a, tor_version_t *b)
  3117. {
  3118. int i;
  3119. tor_assert(a);
  3120. tor_assert(b);
  3121. if ((i = a->major - b->major))
  3122. return i;
  3123. else if ((i = a->minor - b->minor))
  3124. return i;
  3125. else if ((i = a->micro - b->micro))
  3126. return i;
  3127. else if ((i = a->status - b->status))
  3128. return i;
  3129. else if ((i = a->patchlevel - b->patchlevel))
  3130. return i;
  3131. else if ((i = strcmp(a->status_tag, b->status_tag)))
  3132. return i;
  3133. else
  3134. return a->svn_revision - b->svn_revision;
  3135. }
  3136. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  3137. */
  3138. static int
  3139. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  3140. {
  3141. tor_assert(a);
  3142. tor_assert(b);
  3143. return ((a->major == b->major) &&
  3144. (a->minor == b->minor) &&
  3145. (a->micro == b->micro));
  3146. }
  3147. /** Helper: Given pointers to two strings describing tor versions, return -1
  3148. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  3149. * Used to sort a list of versions. */
  3150. static int
  3151. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  3152. {
  3153. const char *a = *_a, *b = *_b;
  3154. int ca, cb;
  3155. tor_version_t va, vb;
  3156. ca = tor_version_parse(a, &va);
  3157. cb = tor_version_parse(b, &vb);
  3158. /* If they both parse, compare them. */
  3159. if (!ca && !cb)
  3160. return tor_version_compare(&va,&vb);
  3161. /* If one parses, it comes first. */
  3162. if (!ca && cb)
  3163. return -1;
  3164. if (ca && !cb)
  3165. return 1;
  3166. /* If neither parses, compare strings. Also, the directory server admin
  3167. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  3168. return strcmp(a,b);
  3169. }
  3170. /** Sort a list of string-representations of versions in ascending order. */
  3171. void
  3172. sort_version_list(smartlist_t *versions, int remove_duplicates)
  3173. {
  3174. smartlist_sort(versions, _compare_tor_version_str_ptr);
  3175. if (remove_duplicates)
  3176. smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
  3177. }
  3178. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  3179. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  3180. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  3181. * encrypted introduction points to the newly allocated
  3182. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  3183. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  3184. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  3185. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  3186. * and -1 for failure.
  3187. */
  3188. int
  3189. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  3190. char *desc_id_out,
  3191. char **intro_points_encrypted_out,
  3192. size_t *intro_points_encrypted_size_out,
  3193. size_t *encoded_size_out,
  3194. const char **next_out, const char *desc)
  3195. {
  3196. rend_service_descriptor_t *result =
  3197. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3198. char desc_hash[DIGEST_LEN];
  3199. const char *eos;
  3200. smartlist_t *tokens = smartlist_create();
  3201. directory_token_t *tok;
  3202. char secret_id_part[DIGEST_LEN];
  3203. int i, version, num_ok=1;
  3204. smartlist_t *versions;
  3205. char public_key_hash[DIGEST_LEN];
  3206. char test_desc_id[DIGEST_LEN];
  3207. memarea_t *area = NULL;
  3208. tor_assert(desc);
  3209. /* Check if desc starts correctly. */
  3210. if (strncmp(desc, "rendezvous-service-descriptor ",
  3211. strlen("rendezvous-service-descriptor "))) {
  3212. log_info(LD_REND, "Descriptor does not start correctly.");
  3213. goto err;
  3214. }
  3215. /* Compute descriptor hash for later validation. */
  3216. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  3217. "rendezvous-service-descriptor ",
  3218. "\nsignature", '\n') < 0) {
  3219. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  3220. goto err;
  3221. }
  3222. /* Determine end of string. */
  3223. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  3224. if (!eos)
  3225. eos = desc + strlen(desc);
  3226. else
  3227. eos = eos + 1;
  3228. /* Check length. */
  3229. if (strlen(desc) > REND_DESC_MAX_SIZE) {
  3230. log_warn(LD_REND, "Descriptor length is %i which exceeds "
  3231. "maximum rendezvous descriptor size of %i kilobytes.",
  3232. (int)strlen(desc), REND_DESC_MAX_SIZE);
  3233. goto err;
  3234. }
  3235. /* Tokenize descriptor. */
  3236. area = memarea_new();
  3237. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  3238. log_warn(LD_REND, "Error tokenizing descriptor.");
  3239. goto err;
  3240. }
  3241. /* Set next to next descriptor, if available. */
  3242. *next_out = eos;
  3243. /* Set length of encoded descriptor. */
  3244. *encoded_size_out = eos - desc;
  3245. /* Check min allowed length of token list. */
  3246. if (smartlist_len(tokens) < 7) {
  3247. log_warn(LD_REND, "Impossibly short descriptor.");
  3248. goto err;
  3249. }
  3250. /* Parse base32-encoded descriptor ID. */
  3251. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  3252. tor_assert(tok == smartlist_get(tokens, 0));
  3253. tor_assert(tok->n_args == 1);
  3254. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  3255. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  3256. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  3257. goto err;
  3258. }
  3259. if (base32_decode(desc_id_out, DIGEST_LEN,
  3260. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  3261. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  3262. tok->args[0]);
  3263. goto err;
  3264. }
  3265. /* Parse descriptor version. */
  3266. tok = find_by_keyword(tokens, R_VERSION);
  3267. tor_assert(tok->n_args == 1);
  3268. result->version =
  3269. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  3270. if (result->version != 2 || !num_ok) {
  3271. /* If it's <2, it shouldn't be under this format. If the number
  3272. * is greater than 2, we bumped it because we broke backward
  3273. * compatibility. See how version numbers in our other formats
  3274. * work. */
  3275. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  3276. escaped(tok->args[0]));
  3277. goto err;
  3278. }
  3279. /* Parse public key. */
  3280. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  3281. result->pk = tok->key;
  3282. tok->key = NULL; /* Prevent free */
  3283. /* Parse secret ID part. */
  3284. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  3285. tor_assert(tok->n_args == 1);
  3286. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  3287. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  3288. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  3289. goto err;
  3290. }
  3291. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  3292. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  3293. tok->args[0]);
  3294. goto err;
  3295. }
  3296. /* Parse publication time -- up-to-date check is done when storing the
  3297. * descriptor. */
  3298. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  3299. tor_assert(tok->n_args == 1);
  3300. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  3301. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  3302. goto err;
  3303. }
  3304. /* Parse protocol versions. */
  3305. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  3306. tor_assert(tok->n_args == 1);
  3307. versions = smartlist_create();
  3308. smartlist_split_string(versions, tok->args[0], ",",
  3309. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3310. for (i = 0; i < smartlist_len(versions); i++) {
  3311. version = (int) tor_parse_long(smartlist_get(versions, i),
  3312. 10, 0, INT_MAX, &num_ok, NULL);
  3313. if (!num_ok) /* It's a string; let's ignore it. */
  3314. continue;
  3315. result->protocols |= 1 << version;
  3316. }
  3317. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  3318. smartlist_free(versions);
  3319. /* Parse encrypted introduction points. Don't verify. */
  3320. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  3321. if (tok) {
  3322. if (strcmp(tok->object_type, "MESSAGE")) {
  3323. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  3324. "type MESSAGE");
  3325. goto err;
  3326. }
  3327. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  3328. tok->object_size);
  3329. *intro_points_encrypted_size_out = tok->object_size;
  3330. } else {
  3331. *intro_points_encrypted_out = NULL;
  3332. *intro_points_encrypted_size_out = 0;
  3333. }
  3334. /* Parse and verify signature. */
  3335. tok = find_by_keyword(tokens, R_SIGNATURE);
  3336. note_crypto_pk_op(VERIFY_RTR);
  3337. if (check_signature_token(desc_hash, tok, result->pk, 0,
  3338. "v2 rendezvous service descriptor") < 0)
  3339. goto err;
  3340. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3341. crypto_pk_get_digest(result->pk, public_key_hash);
  3342. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3343. secret_id_part);
  3344. if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3345. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3346. "computed descriptor ID.");
  3347. goto err;
  3348. }
  3349. goto done;
  3350. err:
  3351. if (result)
  3352. rend_service_descriptor_free(result);
  3353. result = NULL;
  3354. done:
  3355. if (tokens) {
  3356. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3357. smartlist_free(tokens);
  3358. }
  3359. if (area)
  3360. memarea_drop_all(area);
  3361. *parsed_out = result;
  3362. if (result)
  3363. return 0;
  3364. return -1;
  3365. }
  3366. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  3367. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  3368. * write the result to a newly allocated string that is pointed to by
  3369. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  3370. * Return 0 if decryption was successful and -1 otherwise. */
  3371. int
  3372. rend_decrypt_introduction_points(char **ipos_decrypted,
  3373. size_t *ipos_decrypted_size,
  3374. const char *descriptor_cookie,
  3375. const char *ipos_encrypted,
  3376. size_t ipos_encrypted_size)
  3377. {
  3378. tor_assert(ipos_encrypted);
  3379. tor_assert(descriptor_cookie);
  3380. if (ipos_encrypted_size < 2) {
  3381. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3382. "small.");
  3383. return -1;
  3384. }
  3385. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  3386. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  3387. session_key[CIPHER_KEY_LEN], *dec;
  3388. int declen, client_blocks;
  3389. size_t pos = 0, len, client_entries_len;
  3390. crypto_digest_env_t *digest;
  3391. crypto_cipher_env_t *cipher;
  3392. client_blocks = (int) ipos_encrypted[1];
  3393. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  3394. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  3395. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  3396. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3397. "small.");
  3398. return -1;
  3399. }
  3400. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  3401. digest = crypto_new_digest_env();
  3402. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  3403. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  3404. crypto_digest_get_digest(digest, client_id,
  3405. REND_BASIC_AUTH_CLIENT_ID_LEN);
  3406. crypto_free_digest_env(digest);
  3407. for (pos = 2; pos < 2 + client_entries_len;
  3408. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  3409. if (!memcmp(ipos_encrypted + pos, client_id,
  3410. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  3411. /* Attempt to decrypt introduction points. */
  3412. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3413. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  3414. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  3415. CIPHER_KEY_LEN) < 0) {
  3416. log_warn(LD_REND, "Could not decrypt session key for client.");
  3417. crypto_free_cipher_env(cipher);
  3418. return -1;
  3419. }
  3420. crypto_free_cipher_env(cipher);
  3421. cipher = crypto_create_init_cipher(session_key, 0);
  3422. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  3423. dec = tor_malloc(len);
  3424. declen = crypto_cipher_decrypt_with_iv(cipher, dec, len,
  3425. ipos_encrypted + 2 + client_entries_len,
  3426. ipos_encrypted_size - 2 - client_entries_len);
  3427. crypto_free_cipher_env(cipher);
  3428. if (declen < 0) {
  3429. log_warn(LD_REND, "Could not decrypt introduction point string.");
  3430. tor_free(dec);
  3431. return -1;
  3432. }
  3433. if (memcmpstart(dec, declen, "introduction-point ")) {
  3434. log_warn(LD_REND, "Decrypted introduction points don't "
  3435. "look like we could parse them.");
  3436. tor_free(dec);
  3437. continue;
  3438. }
  3439. *ipos_decrypted = dec;
  3440. *ipos_decrypted_size = declen;
  3441. return 0;
  3442. }
  3443. }
  3444. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  3445. "check your authorization for this service!");
  3446. return -1;
  3447. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  3448. crypto_cipher_env_t *cipher;
  3449. char *dec;
  3450. int declen;
  3451. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  3452. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3453. declen = crypto_cipher_decrypt_with_iv(cipher, dec,
  3454. ipos_encrypted_size -
  3455. CIPHER_IV_LEN - 1,
  3456. ipos_encrypted + 1,
  3457. ipos_encrypted_size - 1);
  3458. crypto_free_cipher_env(cipher);
  3459. if (declen < 0) {
  3460. log_warn(LD_REND, "Decrypting introduction points failed!");
  3461. tor_free(dec);
  3462. return -1;
  3463. }
  3464. *ipos_decrypted = dec;
  3465. *ipos_decrypted_size = declen;
  3466. return 0;
  3467. } else {
  3468. log_warn(LD_REND, "Unknown authorization type number: %d",
  3469. ipos_encrypted[0]);
  3470. return -1;
  3471. }
  3472. }
  3473. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  3474. * length <b>intro_points_encoded_size</b> and write the result to the
  3475. * descriptor in <b>parsed</b>; return the number of successfully parsed
  3476. * introduction points or -1 in case of a failure. */
  3477. int
  3478. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  3479. const char *intro_points_encoded,
  3480. size_t intro_points_encoded_size)
  3481. {
  3482. const char *current_ipo, *end_of_intro_points;
  3483. smartlist_t *tokens;
  3484. directory_token_t *tok;
  3485. rend_intro_point_t *intro;
  3486. extend_info_t *info;
  3487. int result, num_ok=1;
  3488. memarea_t *area = NULL;
  3489. tor_assert(parsed);
  3490. /** Function may only be invoked once. */
  3491. tor_assert(!parsed->intro_nodes);
  3492. tor_assert(intro_points_encoded);
  3493. tor_assert(intro_points_encoded_size > 0);
  3494. /* Consider one intro point after the other. */
  3495. current_ipo = intro_points_encoded;
  3496. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  3497. tokens = smartlist_create();
  3498. parsed->intro_nodes = smartlist_create();
  3499. area = memarea_new();
  3500. while (!memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  3501. "introduction-point ")) {
  3502. /* Determine end of string. */
  3503. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  3504. "\nintroduction-point ");
  3505. if (!eos)
  3506. eos = end_of_intro_points;
  3507. else
  3508. eos = eos+1;
  3509. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  3510. /* Free tokens and clear token list. */
  3511. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3512. smartlist_clear(tokens);
  3513. memarea_clear(area);
  3514. /* Tokenize string. */
  3515. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  3516. log_warn(LD_REND, "Error tokenizing introduction point");
  3517. goto err;
  3518. }
  3519. /* Advance to next introduction point, if available. */
  3520. current_ipo = eos;
  3521. /* Check minimum allowed length of introduction point. */
  3522. if (smartlist_len(tokens) < 5) {
  3523. log_warn(LD_REND, "Impossibly short introduction point.");
  3524. goto err;
  3525. }
  3526. /* Allocate new intro point and extend info. */
  3527. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3528. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3529. /* Parse identifier. */
  3530. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  3531. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3532. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3533. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3534. tok->args[0]);
  3535. rend_intro_point_free(intro);
  3536. goto err;
  3537. }
  3538. /* Write identifier to nickname. */
  3539. info->nickname[0] = '$';
  3540. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3541. info->identity_digest, DIGEST_LEN);
  3542. /* Parse IP address. */
  3543. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3544. if (tor_addr_from_str(&info->addr, tok->args[0])<0) {
  3545. log_warn(LD_REND, "Could not parse introduction point address.");
  3546. rend_intro_point_free(intro);
  3547. goto err;
  3548. }
  3549. if (tor_addr_family(&info->addr) != AF_INET) {
  3550. log_warn(LD_REND, "Introduction point address was not ipv4.");
  3551. rend_intro_point_free(intro);
  3552. goto err;
  3553. }
  3554. /* Parse onion port. */
  3555. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  3556. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3557. &num_ok,NULL);
  3558. if (!info->port || !num_ok) {
  3559. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3560. escaped(tok->args[0]));
  3561. rend_intro_point_free(intro);
  3562. goto err;
  3563. }
  3564. /* Parse onion key. */
  3565. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  3566. info->onion_key = tok->key;
  3567. tok->key = NULL; /* Prevent free */
  3568. /* Parse service key. */
  3569. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3570. intro->intro_key = tok->key;
  3571. tok->key = NULL; /* Prevent free */
  3572. /* Add extend info to list of introduction points. */
  3573. smartlist_add(parsed->intro_nodes, intro);
  3574. }
  3575. result = smartlist_len(parsed->intro_nodes);
  3576. goto done;
  3577. err:
  3578. result = -1;
  3579. done:
  3580. /* Free tokens and clear token list. */
  3581. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3582. smartlist_free(tokens);
  3583. if (area)
  3584. memarea_drop_all(area);
  3585. return result;
  3586. }
  3587. /** Parse the content of a client_key file in <b>ckstr</b> and add
  3588. * rend_authorized_client_t's for each parsed client to
  3589. * <b>parsed_clients</b>. Return the number of parsed clients as result
  3590. * or -1 for failure. */
  3591. int
  3592. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  3593. {
  3594. int result = -1;
  3595. smartlist_t *tokens;
  3596. directory_token_t *tok;
  3597. const char *current_entry = NULL;
  3598. memarea_t *area = NULL;
  3599. if (!ckstr || strlen(ckstr) == 0)
  3600. return -1;
  3601. tokens = smartlist_create();
  3602. /* Begin parsing with first entry, skipping comments or whitespace at the
  3603. * beginning. */
  3604. area = memarea_new();
  3605. current_entry = eat_whitespace(ckstr);
  3606. while (!strcmpstart(current_entry, "client-name ")) {
  3607. rend_authorized_client_t *parsed_entry;
  3608. size_t len;
  3609. char descriptor_cookie_base64[REND_DESC_COOKIE_LEN_BASE64+2+1];
  3610. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  3611. /* Determine end of string. */
  3612. const char *eos = strstr(current_entry, "\nclient-name ");
  3613. if (!eos)
  3614. eos = current_entry + strlen(current_entry);
  3615. else
  3616. eos = eos + 1;
  3617. /* Free tokens and clear token list. */
  3618. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3619. smartlist_clear(tokens);
  3620. memarea_clear(area);
  3621. /* Tokenize string. */
  3622. if (tokenize_string(area, current_entry, eos, tokens,
  3623. client_keys_token_table, 0)) {
  3624. log_warn(LD_REND, "Error tokenizing client keys file.");
  3625. goto err;
  3626. }
  3627. /* Advance to next entry, if available. */
  3628. current_entry = eos;
  3629. /* Check minimum allowed length of token list. */
  3630. if (smartlist_len(tokens) < 2) {
  3631. log_warn(LD_REND, "Impossibly short client key entry.");
  3632. goto err;
  3633. }
  3634. /* Parse client name. */
  3635. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  3636. tor_assert(tok == smartlist_get(tokens, 0));
  3637. tor_assert(tok->n_args == 1);
  3638. len = strlen(tok->args[0]);
  3639. if (len < 1 || len > 19 ||
  3640. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  3641. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  3642. "between 1 and 19, and valid characters are "
  3643. "[A-Za-z0-9+-_].)", tok->args[0]);
  3644. goto err;
  3645. }
  3646. /* Check if client name is duplicate. */
  3647. if (strmap_get(parsed_clients, tok->args[0])) {
  3648. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  3649. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  3650. goto err;
  3651. }
  3652. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  3653. parsed_entry->client_name = tor_strdup(tok->args[0]);
  3654. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  3655. /* Parse client key. */
  3656. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  3657. if (tok) {
  3658. parsed_entry->client_key = tok->key;
  3659. tok->key = NULL; /* Prevent free */
  3660. }
  3661. /* Parse descriptor cookie. */
  3662. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  3663. tor_assert(tok->n_args == 1);
  3664. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  3665. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  3666. escaped(tok->args[0]));
  3667. goto err;
  3668. }
  3669. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  3670. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  3671. * cases. */
  3672. if ((base64_decode(descriptor_cookie_tmp, REND_DESC_COOKIE_LEN+2,
  3673. tok->args[0], REND_DESC_COOKIE_LEN_BASE64+2+1)
  3674. != REND_DESC_COOKIE_LEN)) {
  3675. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  3676. "%s", descriptor_cookie_base64);
  3677. goto err;
  3678. }
  3679. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  3680. REND_DESC_COOKIE_LEN);
  3681. }
  3682. result = strmap_size(parsed_clients);
  3683. goto done;
  3684. err:
  3685. result = -1;
  3686. done:
  3687. /* Free tokens and clear token list. */
  3688. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3689. smartlist_free(tokens);
  3690. if (area)
  3691. memarea_drop_all(area);
  3692. return result;
  3693. }