routerparse.c 116 KB

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