routerparse.c 150 KB

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