routerparse.c 115 KB

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