routerparse.c 115 KB

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