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