routerparse.c 173 KB

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