routerparse.c 118 KB

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