routerparse.c 114 KB

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