routerparse.c 133 KB

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