routerparse.c 170 KB

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