routerparse.c 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204
  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-2016, 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. #define ROUTERPARSE_PRIVATE
  11. #include "or.h"
  12. #include "config.h"
  13. #include "circuitstats.h"
  14. #include "dirserv.h"
  15. #include "dirvote.h"
  16. #include "policies.h"
  17. #include "rendcommon.h"
  18. #include "router.h"
  19. #include "routerlist.h"
  20. #include "memarea.h"
  21. #include "microdesc.h"
  22. #include "networkstatus.h"
  23. #include "rephist.h"
  24. #include "routerkeys.h"
  25. #include "routerparse.h"
  26. #include "entrynodes.h"
  27. #include "torcert.h"
  28. #include "sandbox.h"
  29. #include "shared_random.h"
  30. #undef log
  31. #include <math.h>
  32. /****************************************************************************/
  33. /** Enumeration of possible token types. The ones starting with K_ correspond
  34. * to directory 'keywords'. A_ is for an annotation, R or C is related to
  35. * hidden services, ERR_ is an error in the tokenizing process, EOF_ is an
  36. * end-of-file marker, and NIL_ is used to encode not-a-token.
  37. */
  38. typedef enum {
  39. K_ACCEPT = 0,
  40. K_ACCEPT6,
  41. K_DIRECTORY_SIGNATURE,
  42. K_RECOMMENDED_SOFTWARE,
  43. K_REJECT,
  44. K_REJECT6,
  45. K_ROUTER,
  46. K_SIGNED_DIRECTORY,
  47. K_SIGNING_KEY,
  48. K_ONION_KEY,
  49. K_ONION_KEY_NTOR,
  50. K_ROUTER_SIGNATURE,
  51. K_PUBLISHED,
  52. K_RUNNING_ROUTERS,
  53. K_ROUTER_STATUS,
  54. K_PLATFORM,
  55. K_OPT,
  56. K_BANDWIDTH,
  57. K_CONTACT,
  58. K_NETWORK_STATUS,
  59. K_UPTIME,
  60. K_DIR_SIGNING_KEY,
  61. K_FAMILY,
  62. K_FINGERPRINT,
  63. K_HIBERNATING,
  64. K_READ_HISTORY,
  65. K_WRITE_HISTORY,
  66. K_NETWORK_STATUS_VERSION,
  67. K_DIR_SOURCE,
  68. K_DIR_OPTIONS,
  69. K_CLIENT_VERSIONS,
  70. K_SERVER_VERSIONS,
  71. K_OR_ADDRESS,
  72. K_ID,
  73. K_P,
  74. K_P6,
  75. K_R,
  76. K_A,
  77. K_S,
  78. K_V,
  79. K_W,
  80. K_M,
  81. K_EXTRA_INFO,
  82. K_EXTRA_INFO_DIGEST,
  83. K_CACHES_EXTRA_INFO,
  84. K_HIDDEN_SERVICE_DIR,
  85. K_ALLOW_SINGLE_HOP_EXITS,
  86. K_IPV6_POLICY,
  87. K_ROUTER_SIG_ED25519,
  88. K_IDENTITY_ED25519,
  89. K_MASTER_KEY_ED25519,
  90. K_ONION_KEY_CROSSCERT,
  91. K_NTOR_ONION_KEY_CROSSCERT,
  92. K_DIRREQ_END,
  93. K_DIRREQ_V2_IPS,
  94. K_DIRREQ_V3_IPS,
  95. K_DIRREQ_V2_REQS,
  96. K_DIRREQ_V3_REQS,
  97. K_DIRREQ_V2_SHARE,
  98. K_DIRREQ_V3_SHARE,
  99. K_DIRREQ_V2_RESP,
  100. K_DIRREQ_V3_RESP,
  101. K_DIRREQ_V2_DIR,
  102. K_DIRREQ_V3_DIR,
  103. K_DIRREQ_V2_TUN,
  104. K_DIRREQ_V3_TUN,
  105. K_ENTRY_END,
  106. K_ENTRY_IPS,
  107. K_CELL_END,
  108. K_CELL_PROCESSED,
  109. K_CELL_QUEUED,
  110. K_CELL_TIME,
  111. K_CELL_CIRCS,
  112. K_EXIT_END,
  113. K_EXIT_WRITTEN,
  114. K_EXIT_READ,
  115. K_EXIT_OPENED,
  116. K_DIR_KEY_CERTIFICATE_VERSION,
  117. K_DIR_IDENTITY_KEY,
  118. K_DIR_KEY_PUBLISHED,
  119. K_DIR_KEY_EXPIRES,
  120. K_DIR_KEY_CERTIFICATION,
  121. K_DIR_KEY_CROSSCERT,
  122. K_DIR_ADDRESS,
  123. K_DIR_TUNNELLED,
  124. K_VOTE_STATUS,
  125. K_VALID_AFTER,
  126. K_FRESH_UNTIL,
  127. K_VALID_UNTIL,
  128. K_VOTING_DELAY,
  129. K_KNOWN_FLAGS,
  130. K_PARAMS,
  131. K_BW_WEIGHTS,
  132. K_VOTE_DIGEST,
  133. K_CONSENSUS_DIGEST,
  134. K_ADDITIONAL_DIGEST,
  135. K_ADDITIONAL_SIGNATURE,
  136. K_CONSENSUS_METHODS,
  137. K_CONSENSUS_METHOD,
  138. K_LEGACY_DIR_KEY,
  139. K_DIRECTORY_FOOTER,
  140. K_SIGNING_CERT_ED,
  141. K_SR_FLAG,
  142. K_COMMIT,
  143. K_PREVIOUS_SRV,
  144. K_CURRENT_SRV,
  145. K_PACKAGE,
  146. A_PURPOSE,
  147. A_LAST_LISTED,
  148. A_UNKNOWN_,
  149. R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  150. R_VERSION,
  151. R_PERMANENT_KEY,
  152. R_SECRET_ID_PART,
  153. R_PUBLICATION_TIME,
  154. R_PROTOCOL_VERSIONS,
  155. R_INTRODUCTION_POINTS,
  156. R_SIGNATURE,
  157. R_IPO_IDENTIFIER,
  158. R_IPO_IP_ADDRESS,
  159. R_IPO_ONION_PORT,
  160. R_IPO_ONION_KEY,
  161. R_IPO_SERVICE_KEY,
  162. C_CLIENT_NAME,
  163. C_DESCRIPTOR_COOKIE,
  164. C_CLIENT_KEY,
  165. ERR_,
  166. EOF_,
  167. NIL_
  168. } directory_keyword;
  169. #define MIN_ANNOTATION A_PURPOSE
  170. #define MAX_ANNOTATION A_UNKNOWN_
  171. /** Structure to hold a single directory token.
  172. *
  173. * We parse a directory by breaking it into "tokens", each consisting
  174. * of a keyword, a line full of arguments, and a binary object. The
  175. * arguments and object are both optional, depending on the keyword
  176. * type.
  177. *
  178. * This structure is only allocated in memareas; do not allocate it on
  179. * the heap, or token_clear() won't work.
  180. */
  181. typedef struct directory_token_t {
  182. directory_keyword tp; /**< Type of the token. */
  183. int n_args:30; /**< Number of elements in args */
  184. char **args; /**< Array of arguments from keyword line. */
  185. char *object_type; /**< -----BEGIN [object_type]-----*/
  186. size_t object_size; /**< Bytes in object_body */
  187. char *object_body; /**< Contents of object, base64-decoded. */
  188. crypto_pk_t *key; /**< For public keys only. Heap-allocated. */
  189. char *error; /**< For ERR_ tokens only. */
  190. } directory_token_t;
  191. /* ********************************************************************** */
  192. /** We use a table of rules to decide how to parse each token type. */
  193. /** Rules for whether the keyword needs an object. */
  194. typedef enum {
  195. NO_OBJ, /**< No object, ever. */
  196. NEED_OBJ, /**< Object is required. */
  197. NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
  198. NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  199. NEED_KEY, /**< Object is required, and must be a public key. */
  200. OBJ_OK, /**< Object is optional. */
  201. } obj_syntax;
  202. #define AT_START 1
  203. #define AT_END 2
  204. /** Determines the parsing rules for a single token type. */
  205. typedef struct token_rule_t {
  206. /** The string value of the keyword identifying the type of item. */
  207. const char *t;
  208. /** The corresponding directory_keyword enum. */
  209. directory_keyword v;
  210. /** Minimum number of arguments for this item */
  211. int min_args;
  212. /** Maximum number of arguments for this item */
  213. int max_args;
  214. /** If true, we concatenate all arguments for this item into a single
  215. * string. */
  216. int concat_args;
  217. /** Requirements on object syntax for this item. */
  218. obj_syntax os;
  219. /** Lowest number of times this item may appear in a document. */
  220. int min_cnt;
  221. /** Highest number of times this item may appear in a document. */
  222. int max_cnt;
  223. /** One or more of AT_START/AT_END to limit where the item may appear in a
  224. * document. */
  225. int pos;
  226. /** True iff this token is an annotation. */
  227. int is_annotation;
  228. } token_rule_t;
  229. /*
  230. * Helper macros to define token tables. 's' is a string, 't' is a
  231. * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
  232. * object syntax.
  233. *
  234. */
  235. /** Appears to indicate the end of a table. */
  236. #define END_OF_TABLE { NULL, NIL_, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
  237. /** An item with no restrictions: used for obsolete document types */
  238. #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  239. /** An item with no restrictions on multiplicity or location. */
  240. #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  241. /** An item that must appear exactly once */
  242. #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0, 0 }
  243. /** An item that must appear exactly once, at the start of the document */
  244. #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START, 0 }
  245. /** An item that must appear exactly once, at the end of the document */
  246. #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END, 0 }
  247. /** An item that must appear one or more times */
  248. #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0, 0 }
  249. /** An item that must appear no more than once */
  250. #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
  251. /** An annotation that must appear no more than once */
  252. #define A01(s,t,a,o) { s, t, a, o, 0, 1, 0, 1 }
  253. /* Argument multiplicity: any number of arguments. */
  254. #define ARGS 0,INT_MAX,0
  255. /* Argument multiplicity: no arguments. */
  256. #define NO_ARGS 0,0,0
  257. /* Argument multiplicity: concatenate all arguments. */
  258. #define CONCAT_ARGS 1,1,1
  259. /* Argument multiplicity: at least <b>n</b> arguments. */
  260. #define GE(n) n,INT_MAX,0
  261. /* Argument multiplicity: exactly <b>n</b> arguments. */
  262. #define EQ(n) n,n,0
  263. /** List of tokens recognized in router descriptors */
  264. static token_rule_t routerdesc_token_table[] = {
  265. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  266. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  267. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  268. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  269. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  270. T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
  271. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  272. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  273. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  274. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  275. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  276. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  277. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  278. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  279. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  280. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  281. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  282. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  283. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  284. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  285. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  286. T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
  287. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  288. T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
  289. T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
  290. EQ(1), NEED_OBJ ),
  291. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  292. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  293. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  294. T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
  295. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  296. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  297. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  298. T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
  299. END_OF_TABLE
  300. };
  301. /** List of tokens recognized in extra-info documents. */
  302. static token_rule_t extrainfo_token_table[] = {
  303. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  304. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  305. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  306. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  307. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  308. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  309. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  310. T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
  311. T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
  312. T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
  313. T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
  314. T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
  315. T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
  316. T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
  317. T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
  318. T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
  319. T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
  320. T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
  321. T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
  322. T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
  323. T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
  324. T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
  325. T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
  326. T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
  327. T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
  328. T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
  329. T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
  330. T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
  331. T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
  332. T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
  333. T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
  334. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  335. END_OF_TABLE
  336. };
  337. /** List of tokens recognized in the body part of v3 networkstatus
  338. * documents. */
  339. static token_rule_t rtrstatus_token_table[] = {
  340. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  341. T1( "r", K_R, GE(7), NO_OBJ ),
  342. T0N("a", K_A, GE(1), NO_OBJ ),
  343. T1( "s", K_S, ARGS, NO_OBJ ),
  344. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  345. T01("w", K_W, ARGS, NO_OBJ ),
  346. T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
  347. T0N("id", K_ID, GE(2), NO_OBJ ),
  348. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  349. END_OF_TABLE
  350. };
  351. /** List of tokens common to V3 authority certificates and V3 consensuses. */
  352. #define CERTIFICATE_MEMBERS \
  353. T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
  354. GE(1), NO_OBJ ), \
  355. T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
  356. T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
  357. T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
  358. T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
  359. T1("dir-key-crosscert", K_DIR_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),\
  360. T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
  361. NO_ARGS, NEED_OBJ), \
  362. T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
  363. /** List of tokens recognized in V3 authority certificates. */
  364. static token_rule_t dir_key_certificate_table[] = {
  365. CERTIFICATE_MEMBERS
  366. T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  367. END_OF_TABLE
  368. };
  369. /** List of tokens recognized in rendezvous service descriptors */
  370. static token_rule_t desc_token_table[] = {
  371. T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  372. EQ(1), NO_OBJ),
  373. T1("version", R_VERSION, EQ(1), NO_OBJ),
  374. T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
  375. T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
  376. T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
  377. T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
  378. T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
  379. T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
  380. END_OF_TABLE
  381. };
  382. /** List of tokens recognized in the (encrypted) list of introduction points of
  383. * rendezvous service descriptors */
  384. static token_rule_t ipo_token_table[] = {
  385. T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
  386. T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
  387. T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
  388. T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  389. T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
  390. END_OF_TABLE
  391. };
  392. /** List of tokens recognized in the (possibly encrypted) list of introduction
  393. * points of rendezvous service descriptors */
  394. static token_rule_t client_keys_token_table[] = {
  395. T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
  396. T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
  397. T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
  398. END_OF_TABLE
  399. };
  400. /** List of tokens recognized in V3 networkstatus votes. */
  401. static token_rule_t networkstatus_token_table[] = {
  402. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  403. GE(1), NO_OBJ ),
  404. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  405. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  406. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  407. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  408. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  409. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  410. T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
  411. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  412. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  413. T01("signing-ed25519", K_SIGNING_CERT_ED, NO_ARGS , NEED_OBJ ),
  414. T01("shared-rand-participate",K_SR_FLAG, NO_ARGS, NO_OBJ ),
  415. T0N("shared-rand-commit", K_COMMIT, GE(3), NO_OBJ ),
  416. T01("shared-rand-previous-value", K_PREVIOUS_SRV,EQ(2), NO_OBJ ),
  417. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  418. T0N("package", K_PACKAGE, CONCAT_ARGS, NO_OBJ ),
  419. CERTIFICATE_MEMBERS
  420. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  421. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  422. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  423. T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
  424. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  425. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  426. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  427. T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
  428. END_OF_TABLE
  429. };
  430. /** List of tokens recognized in V3 networkstatus consensuses. */
  431. static token_rule_t networkstatus_consensus_token_table[] = {
  432. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  433. GE(1), NO_OBJ ),
  434. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  435. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  436. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  437. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  438. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  439. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  440. T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  441. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  442. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  443. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  444. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  445. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  446. T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
  447. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  448. T01("shared-rand-previous-value", K_PREVIOUS_SRV, EQ(2), NO_OBJ ),
  449. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  450. END_OF_TABLE
  451. };
  452. /** List of tokens recognized in the footer of v1 directory footers. */
  453. static token_rule_t networkstatus_vote_footer_token_table[] = {
  454. T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
  455. T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
  456. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  457. END_OF_TABLE
  458. };
  459. /** List of tokens recognized in detached networkstatus signature documents. */
  460. static token_rule_t networkstatus_detached_signature_token_table[] = {
  461. T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
  462. T("additional-digest", K_ADDITIONAL_DIGEST,GE(3), NO_OBJ ),
  463. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  464. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  465. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  466. T("additional-signature", K_ADDITIONAL_SIGNATURE, GE(4), NEED_OBJ ),
  467. T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  468. END_OF_TABLE
  469. };
  470. /** List of tokens recognized in microdescriptors */
  471. static token_rule_t microdesc_token_table[] = {
  472. T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  473. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  474. T0N("id", K_ID, GE(2), NO_OBJ ),
  475. T0N("a", K_A, GE(1), NO_OBJ ),
  476. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  477. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  478. T01("p6", K_P6, CONCAT_ARGS, NO_OBJ ),
  479. A01("@last-listed", A_LAST_LISTED, CONCAT_ARGS, NO_OBJ ),
  480. END_OF_TABLE
  481. };
  482. #undef T
  483. /* static function prototypes */
  484. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  485. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
  486. unsigned fmt_flags);
  487. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  488. static int router_get_hash_impl_helper(const char *s, size_t s_len,
  489. const char *start_str,
  490. const char *end_str, char end_c,
  491. const char **start_out, const char **end_out);
  492. static int router_get_hash_impl(const char *s, size_t s_len, char *digest,
  493. const char *start_str, const char *end_str,
  494. char end_char,
  495. digest_algorithm_t alg);
  496. static int router_get_hashes_impl(const char *s, size_t s_len,
  497. common_digests_t *digests,
  498. const char *start_str, const char *end_str,
  499. char end_char);
  500. static void token_clear(directory_token_t *tok);
  501. static smartlist_t *find_all_by_keyword(smartlist_t *s, directory_keyword k);
  502. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  503. static directory_token_t *find_by_keyword_(smartlist_t *s,
  504. directory_keyword keyword,
  505. const char *keyword_str);
  506. #define find_by_keyword(s, keyword) find_by_keyword_((s), (keyword), #keyword)
  507. static directory_token_t *find_opt_by_keyword(smartlist_t *s,
  508. directory_keyword keyword);
  509. #define TS_ANNOTATIONS_OK 1
  510. #define TS_NOCHECK 2
  511. #define TS_NO_NEW_ANNOTATIONS 4
  512. static int tokenize_string(memarea_t *area,
  513. const char *start, const char *end,
  514. smartlist_t *out,
  515. token_rule_t *table,
  516. int flags);
  517. static directory_token_t *get_next_token(memarea_t *area,
  518. const char **s,
  519. const char *eos,
  520. token_rule_t *table);
  521. #define CST_CHECK_AUTHORITY (1<<0)
  522. #define CST_NO_CHECK_OBJTYPE (1<<1)
  523. static int check_signature_token(const char *digest,
  524. ssize_t digest_len,
  525. directory_token_t *tok,
  526. crypto_pk_t *pkey,
  527. int flags,
  528. const char *doctype);
  529. #undef DEBUG_AREA_ALLOC
  530. #ifdef DEBUG_AREA_ALLOC
  531. #define DUMP_AREA(a,name) STMT_BEGIN \
  532. size_t alloc=0, used=0; \
  533. memarea_get_stats((a),&alloc,&used); \
  534. log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
  535. name, (unsigned long)alloc, (unsigned long)used); \
  536. STMT_END
  537. #else
  538. #define DUMP_AREA(a,name) STMT_NIL
  539. #endif
  540. /* Dump mechanism for unparseable descriptors */
  541. /** List of dumped descriptors for FIFO cleanup purposes */
  542. STATIC smartlist_t *descs_dumped = NULL;
  543. /** Total size of dumped descriptors for FIFO cleanup */
  544. STATIC uint64_t len_descs_dumped = 0;
  545. /** Directory to stash dumps in */
  546. static int have_dump_desc_dir = 0;
  547. static int problem_with_dump_desc_dir = 0;
  548. #define DESC_DUMP_DATADIR_SUBDIR "unparseable-descs"
  549. #define DESC_DUMP_BASE_FILENAME "unparseable-desc"
  550. /** Find the dump directory and check if we'll be able to create it */
  551. static void
  552. dump_desc_init(void)
  553. {
  554. char *dump_desc_dir;
  555. dump_desc_dir = get_datadir_fname(DESC_DUMP_DATADIR_SUBDIR);
  556. /*
  557. * We just check for it, don't create it at this point; we'll
  558. * create it when we need it if it isn't already there.
  559. */
  560. if (check_private_dir(dump_desc_dir, CPD_CHECK, get_options()->User) < 0) {
  561. /* Error, log and flag it as having a problem */
  562. log_notice(LD_DIR,
  563. "Doesn't look like we'll be able to create descriptor dump "
  564. "directory %s; dumps will be disabled.",
  565. dump_desc_dir);
  566. problem_with_dump_desc_dir = 1;
  567. tor_free(dump_desc_dir);
  568. return;
  569. }
  570. /* Check if it exists */
  571. switch (file_status(dump_desc_dir)) {
  572. case FN_DIR:
  573. /* We already have a directory */
  574. have_dump_desc_dir = 1;
  575. break;
  576. case FN_NOENT:
  577. /* Nothing, we'll need to create it later */
  578. have_dump_desc_dir = 0;
  579. break;
  580. case FN_ERROR:
  581. /* Log and flag having a problem */
  582. log_notice(LD_DIR,
  583. "Couldn't check whether descriptor dump directory %s already"
  584. " exists: %s",
  585. dump_desc_dir, strerror(errno));
  586. problem_with_dump_desc_dir = 1;
  587. break;
  588. case FN_FILE:
  589. case FN_EMPTY:
  590. default:
  591. /* Something else was here! */
  592. log_notice(LD_DIR,
  593. "Descriptor dump directory %s already exists and isn't a "
  594. "directory",
  595. dump_desc_dir);
  596. problem_with_dump_desc_dir = 1;
  597. }
  598. if (have_dump_desc_dir && !problem_with_dump_desc_dir) {
  599. dump_desc_populate_fifo_from_directory(dump_desc_dir);
  600. }
  601. tor_free(dump_desc_dir);
  602. }
  603. /** Create the dump directory if needed and possible */
  604. static void
  605. dump_desc_create_dir(void)
  606. {
  607. char *dump_desc_dir;
  608. /* If the problem flag is set, skip it */
  609. if (problem_with_dump_desc_dir) return;
  610. /* Do we need it? */
  611. if (!have_dump_desc_dir) {
  612. dump_desc_dir = get_datadir_fname(DESC_DUMP_DATADIR_SUBDIR);
  613. if (check_private_dir(dump_desc_dir, CPD_CREATE,
  614. get_options()->User) < 0) {
  615. log_notice(LD_DIR,
  616. "Failed to create descriptor dump directory %s",
  617. dump_desc_dir);
  618. problem_with_dump_desc_dir = 1;
  619. }
  620. /* Okay, we created it */
  621. have_dump_desc_dir = 1;
  622. tor_free(dump_desc_dir);
  623. }
  624. }
  625. /** Dump desc FIFO/cleanup; take ownership of the given filename, add it to
  626. * the FIFO, and clean up the oldest entries to the extent they exceed the
  627. * configured cap. If any old entries with a matching hash existed, they
  628. * just got overwritten right before this was called and we should adjust
  629. * the total size counter without deleting them.
  630. */
  631. static void
  632. dump_desc_fifo_add_and_clean(char *filename, const uint8_t *digest_sha256,
  633. size_t len)
  634. {
  635. dumped_desc_t *ent = NULL, *tmp;
  636. uint64_t max_len;
  637. tor_assert(filename != NULL);
  638. tor_assert(digest_sha256 != NULL);
  639. if (descs_dumped == NULL) {
  640. /* We better have no length, then */
  641. tor_assert(len_descs_dumped == 0);
  642. /* Make a smartlist */
  643. descs_dumped = smartlist_new();
  644. }
  645. /* Make a new entry to put this one in */
  646. ent = tor_malloc_zero(sizeof(*ent));
  647. ent->filename = filename;
  648. ent->len = len;
  649. ent->when = time(NULL);
  650. memcpy(ent->digest_sha256, digest_sha256, DIGEST256_LEN);
  651. /* Do we need to do some cleanup? */
  652. max_len = get_options()->MaxUnparseableDescSizeToLog;
  653. /* Iterate over the list until we've freed enough space */
  654. while (len > max_len - len_descs_dumped &&
  655. smartlist_len(descs_dumped) > 0) {
  656. /* Get the oldest thing on the list */
  657. tmp = (dumped_desc_t *)(smartlist_get(descs_dumped, 0));
  658. /*
  659. * Check if it matches the filename we just added, so we don't delete
  660. * something we just emitted if we get repeated identical descriptors.
  661. */
  662. if (strcmp(tmp->filename, filename) != 0) {
  663. /* Delete it and adjust the length counter */
  664. tor_unlink(tmp->filename);
  665. tor_assert(len_descs_dumped >= tmp->len);
  666. len_descs_dumped -= tmp->len;
  667. log_info(LD_DIR,
  668. "Deleting old unparseable descriptor dump %s due to "
  669. "space limits",
  670. tmp->filename);
  671. } else {
  672. /*
  673. * Don't delete, but do adjust the counter since we will bump it
  674. * later
  675. */
  676. tor_assert(len_descs_dumped >= tmp->len);
  677. len_descs_dumped -= tmp->len;
  678. log_info(LD_DIR,
  679. "Replacing old descriptor dump %s with new identical one",
  680. tmp->filename);
  681. }
  682. /* Free it and remove it from the list */
  683. smartlist_del_keeporder(descs_dumped, 0);
  684. tor_free(tmp->filename);
  685. tor_free(tmp);
  686. }
  687. /* Append our entry to the end of the list and bump the counter */
  688. smartlist_add(descs_dumped, ent);
  689. len_descs_dumped += len;
  690. }
  691. /** Check if we already have a descriptor for this hash and move it to the
  692. * head of the queue if so. Return 1 if one existed and 0 otherwise.
  693. */
  694. static int
  695. dump_desc_fifo_bump_hash(const uint8_t *digest_sha256)
  696. {
  697. dumped_desc_t *match = NULL;
  698. tor_assert(digest_sha256);
  699. if (descs_dumped) {
  700. /* Find a match if one exists */
  701. SMARTLIST_FOREACH_BEGIN(descs_dumped, dumped_desc_t *, ent) {
  702. if (ent &&
  703. tor_memeq(ent->digest_sha256, digest_sha256, DIGEST256_LEN)) {
  704. /*
  705. * Save a pointer to the match and remove it from its current
  706. * position.
  707. */
  708. match = ent;
  709. SMARTLIST_DEL_CURRENT_KEEPORDER(descs_dumped, ent);
  710. break;
  711. }
  712. } SMARTLIST_FOREACH_END(ent);
  713. if (match) {
  714. /* Update the timestamp */
  715. match->when = time(NULL);
  716. /* Add it back at the end of the list */
  717. smartlist_add(descs_dumped, match);
  718. /* Indicate we found one */
  719. return 1;
  720. }
  721. }
  722. return 0;
  723. }
  724. /** Clean up on exit; just memory, leave the dumps behind
  725. */
  726. STATIC void
  727. dump_desc_fifo_cleanup(void)
  728. {
  729. if (descs_dumped) {
  730. /* Free each descriptor */
  731. SMARTLIST_FOREACH_BEGIN(descs_dumped, dumped_desc_t *, ent) {
  732. tor_assert(ent);
  733. tor_free(ent->filename);
  734. tor_free(ent);
  735. } SMARTLIST_FOREACH_END(ent);
  736. /* Free the list */
  737. smartlist_free(descs_dumped);
  738. descs_dumped = NULL;
  739. len_descs_dumped = 0;
  740. }
  741. }
  742. /** Handle one file for dump_desc_populate_fifo_from_directory(); make sure
  743. * the filename is sensibly formed and matches the file content, and either
  744. * return a dumped_desc_t for it or remove the file and return NULL.
  745. */
  746. MOCK_IMPL(STATIC dumped_desc_t *,
  747. dump_desc_populate_one_file, (const char *dirname, const char *f))
  748. {
  749. dumped_desc_t *ent = NULL;
  750. char *path = NULL, *desc = NULL;
  751. const char *digest_str;
  752. char digest[DIGEST256_LEN], content_digest[DIGEST256_LEN];
  753. /* Expected prefix before digest in filenames */
  754. const char *f_pfx = DESC_DUMP_BASE_FILENAME ".";
  755. /*
  756. * Stat while reading; this is important in case the file
  757. * contains a NUL character.
  758. */
  759. struct stat st;
  760. /* Sanity-check args */
  761. tor_assert(dirname != NULL);
  762. tor_assert(f != NULL);
  763. /* Form the full path */
  764. tor_asprintf(&path, "%s" PATH_SEPARATOR "%s", dirname, f);
  765. /* Check that f has the form DESC_DUMP_BASE_FILENAME.<digest256> */
  766. if (!strcmpstart(f, f_pfx)) {
  767. /* It matches the form, but is the digest parseable as such? */
  768. digest_str = f + strlen(f_pfx);
  769. if (base16_decode(digest, DIGEST256_LEN,
  770. digest_str, strlen(digest_str)) != DIGEST256_LEN) {
  771. /* We failed to decode it */
  772. digest_str = NULL;
  773. }
  774. } else {
  775. /* No match */
  776. digest_str = NULL;
  777. }
  778. if (!digest_str) {
  779. /* We couldn't get a sensible digest */
  780. log_notice(LD_DIR,
  781. "Removing unrecognized filename %s from unparseable "
  782. "descriptors directory", f);
  783. tor_unlink(path);
  784. /* We're done */
  785. goto done;
  786. }
  787. /*
  788. * The filename has the form DESC_DUMP_BASE_FILENAME "." <digest256> and
  789. * we've decoded the digest. Next, check that we can read it and the
  790. * content matches this digest. We are relying on the fact that if the
  791. * file contains a '\0', read_file_to_str() will allocate space for and
  792. * read the entire file and return the correct size in st.
  793. */
  794. desc = read_file_to_str(path, RFTS_IGNORE_MISSING|RFTS_BIN, &st);
  795. if (!desc) {
  796. /* We couldn't read it */
  797. log_notice(LD_DIR,
  798. "Failed to read %s from unparseable descriptors directory; "
  799. "attempting to remove it.", f);
  800. tor_unlink(path);
  801. /* We're done */
  802. goto done;
  803. }
  804. #if SIZE_MAX > UINT64_MAX
  805. if (BUG((uint64_t)st.st_size > (uint64_t)SIZE_MAX)) {
  806. /* LCOV_EXCL_START
  807. * Should be impossible since RFTS above should have failed to read the
  808. * huge file into RAM. */
  809. goto done;
  810. /* LCOV_EXCL_STOP */
  811. }
  812. #endif
  813. if (BUG(st.st_size < 0)) {
  814. /* LCOV_EXCL_START
  815. * Should be impossible, since the OS isn't supposed to be b0rken. */
  816. goto done;
  817. /* LCOV_EXCL_STOP */
  818. }
  819. /* (Now we can be sure that st.st_size is safe to cast to a size_t.) */
  820. /*
  821. * We got one; now compute its digest and check that it matches the
  822. * filename.
  823. */
  824. if (crypto_digest256((char *)content_digest, desc, (size_t) st.st_size,
  825. DIGEST_SHA256) != 0) {
  826. /* Weird, but okay */
  827. log_info(LD_DIR,
  828. "Unable to hash content of %s from unparseable descriptors "
  829. "directory", f);
  830. tor_unlink(path);
  831. /* We're done */
  832. goto done;
  833. }
  834. /* Compare the digests */
  835. if (tor_memneq(digest, content_digest, DIGEST256_LEN)) {
  836. /* No match */
  837. log_info(LD_DIR,
  838. "Hash of %s from unparseable descriptors directory didn't "
  839. "match its filename; removing it", f);
  840. tor_unlink(path);
  841. /* We're done */
  842. goto done;
  843. }
  844. /* Okay, it's a match, we should prepare ent */
  845. ent = tor_malloc_zero(sizeof(dumped_desc_t));
  846. ent->filename = path;
  847. memcpy(ent->digest_sha256, digest, DIGEST256_LEN);
  848. ent->len = (size_t) st.st_size;
  849. ent->when = st.st_mtime;
  850. /* Null out path so we don't free it out from under ent */
  851. path = NULL;
  852. done:
  853. /* Free allocations if we had them */
  854. tor_free(desc);
  855. tor_free(path);
  856. return ent;
  857. }
  858. /** Sort helper for dump_desc_populate_fifo_from_directory(); compares
  859. * the when field of dumped_desc_ts in a smartlist to put the FIFO in
  860. * the correct order after reconstructing it from the directory.
  861. */
  862. static int
  863. dump_desc_compare_fifo_entries(const void **a_v, const void **b_v)
  864. {
  865. const dumped_desc_t **a = (const dumped_desc_t **)a_v;
  866. const dumped_desc_t **b = (const dumped_desc_t **)b_v;
  867. if ((a != NULL) && (*a != NULL)) {
  868. if ((b != NULL) && (*b != NULL)) {
  869. /* We have sensible dumped_desc_ts to compare */
  870. if ((*a)->when < (*b)->when) {
  871. return -1;
  872. } else if ((*a)->when == (*b)->when) {
  873. return 0;
  874. } else {
  875. return 1;
  876. }
  877. } else {
  878. /*
  879. * We shouldn't see this, but what the hell, NULLs precede everythin
  880. * else
  881. */
  882. return 1;
  883. }
  884. } else {
  885. return -1;
  886. }
  887. }
  888. /** Scan the contents of the directory, and update FIFO/counters; this will
  889. * consistency-check descriptor dump filenames against hashes of descriptor
  890. * dump file content, and remove any inconsistent/unreadable dumps, and then
  891. * reconstruct the dump FIFO as closely as possible for the last time the
  892. * tor process shut down. If a previous dump was repeated more than once and
  893. * moved ahead in the FIFO, the mtime will not have been updated and the
  894. * reconstructed order will be wrong, but will always be a permutation of
  895. * the original.
  896. */
  897. STATIC void
  898. dump_desc_populate_fifo_from_directory(const char *dirname)
  899. {
  900. smartlist_t *files = NULL;
  901. dumped_desc_t *ent = NULL;
  902. tor_assert(dirname != NULL);
  903. /* Get a list of files */
  904. files = tor_listdir(dirname);
  905. if (!files) {
  906. log_notice(LD_DIR,
  907. "Unable to get contents of unparseable descriptor dump "
  908. "directory %s",
  909. dirname);
  910. return;
  911. }
  912. /*
  913. * Iterate through the list and decide which files should go in the
  914. * FIFO and which should be purged.
  915. */
  916. SMARTLIST_FOREACH_BEGIN(files, char *, f) {
  917. /* Try to get a FIFO entry */
  918. ent = dump_desc_populate_one_file(dirname, f);
  919. if (ent) {
  920. /*
  921. * We got one; add it to the FIFO. No need for duplicate checking
  922. * here since we just verified the name and digest match.
  923. */
  924. /* Make sure we have a list to add it to */
  925. if (!descs_dumped) {
  926. descs_dumped = smartlist_new();
  927. len_descs_dumped = 0;
  928. }
  929. /* Add it and adjust the counter */
  930. smartlist_add(descs_dumped, ent);
  931. len_descs_dumped += ent->len;
  932. }
  933. /*
  934. * If we didn't, we will have unlinked the file if necessary and
  935. * possible, and emitted a log message about it, so just go on to
  936. * the next.
  937. */
  938. } SMARTLIST_FOREACH_END(f);
  939. /* Did we get anything? */
  940. if (descs_dumped != NULL) {
  941. /* Sort the FIFO in order of increasing timestamp */
  942. smartlist_sort(descs_dumped, dump_desc_compare_fifo_entries);
  943. /* Log some stats */
  944. log_info(LD_DIR,
  945. "Reloaded unparseable descriptor dump FIFO with %d dump(s) "
  946. "totaling " U64_FORMAT " bytes",
  947. smartlist_len(descs_dumped), U64_PRINTF_ARG(len_descs_dumped));
  948. }
  949. /* Free the original list */
  950. SMARTLIST_FOREACH(files, char *, f, tor_free(f));
  951. smartlist_free(files);
  952. }
  953. /** For debugging purposes, dump unparseable descriptor *<b>desc</b> of
  954. * type *<b>type</b> to file $DATADIR/unparseable-desc. Do not write more
  955. * than one descriptor to disk per minute. If there is already such a
  956. * file in the data directory, overwrite it. */
  957. STATIC void
  958. dump_desc(const char *desc, const char *type)
  959. {
  960. tor_assert(desc);
  961. tor_assert(type);
  962. size_t len;
  963. /* The SHA256 of the string */
  964. uint8_t digest_sha256[DIGEST256_LEN];
  965. char digest_sha256_hex[HEX_DIGEST256_LEN+1];
  966. /* Filename to log it to */
  967. char *debugfile, *debugfile_base;
  968. /* Get the hash for logging purposes anyway */
  969. len = strlen(desc);
  970. if (crypto_digest256((char *)digest_sha256, desc, len,
  971. DIGEST_SHA256) != 0) {
  972. log_info(LD_DIR,
  973. "Unable to parse descriptor of type %s, and unable to even hash"
  974. " it!", type);
  975. goto err;
  976. }
  977. base16_encode(digest_sha256_hex, sizeof(digest_sha256_hex),
  978. (const char *)digest_sha256, sizeof(digest_sha256));
  979. /*
  980. * We mention type and hash in the main log; don't clutter up the files
  981. * with anything but the exact dump.
  982. */
  983. tor_asprintf(&debugfile_base,
  984. DESC_DUMP_BASE_FILENAME ".%s", digest_sha256_hex);
  985. debugfile = get_datadir_fname2(DESC_DUMP_DATADIR_SUBDIR, debugfile_base);
  986. /*
  987. * Check if the sandbox is active or will become active; see comment
  988. * below at the log message for why.
  989. */
  990. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  991. if (len <= get_options()->MaxUnparseableDescSizeToLog) {
  992. if (!dump_desc_fifo_bump_hash(digest_sha256)) {
  993. /* Create the directory if needed */
  994. dump_desc_create_dir();
  995. /* Make sure we've got it */
  996. if (have_dump_desc_dir && !problem_with_dump_desc_dir) {
  997. /* Write it, and tell the main log about it */
  998. write_str_to_file(debugfile, desc, 1);
  999. log_info(LD_DIR,
  1000. "Unable to parse descriptor of type %s with hash %s and "
  1001. "length %lu. See file %s in data directory for details.",
  1002. type, digest_sha256_hex, (unsigned long)len,
  1003. debugfile_base);
  1004. dump_desc_fifo_add_and_clean(debugfile, digest_sha256, len);
  1005. /* Since we handed ownership over, don't free debugfile later */
  1006. debugfile = NULL;
  1007. } else {
  1008. /* Problem with the subdirectory */
  1009. log_info(LD_DIR,
  1010. "Unable to parse descriptor of type %s with hash %s and "
  1011. "length %lu. Descriptor not dumped because we had a "
  1012. "problem creating the " DESC_DUMP_DATADIR_SUBDIR
  1013. " subdirectory",
  1014. type, digest_sha256_hex, (unsigned long)len);
  1015. /* We do have to free debugfile in this case */
  1016. }
  1017. } else {
  1018. /* We already had one with this hash dumped */
  1019. log_info(LD_DIR,
  1020. "Unable to parse descriptor of type %s with hash %s and "
  1021. "length %lu. Descriptor not dumped because one with that "
  1022. "hash has already been dumped.",
  1023. type, digest_sha256_hex, (unsigned long)len);
  1024. /* We do have to free debugfile in this case */
  1025. }
  1026. } else {
  1027. /* Just log that it happened without dumping */
  1028. log_info(LD_DIR,
  1029. "Unable to parse descriptor of type %s with hash %s and "
  1030. "length %lu. Descriptor not dumped because it exceeds maximum"
  1031. " log size all by itself.",
  1032. type, digest_sha256_hex, (unsigned long)len);
  1033. /* We do have to free debugfile in this case */
  1034. }
  1035. } else {
  1036. /*
  1037. * Not logging because the sandbox is active and seccomp2 apparently
  1038. * doesn't have a sensible way to allow filenames according to a pattern
  1039. * match. (If we ever figure out how to say "allow writes to /regex/",
  1040. * remove this checK).
  1041. */
  1042. log_info(LD_DIR,
  1043. "Unable to parse descriptor of type %s with hash %s and "
  1044. "length %lu. Descriptor not dumped because the sandbox is "
  1045. "configured",
  1046. type, digest_sha256_hex, (unsigned long)len);
  1047. }
  1048. tor_free(debugfile_base);
  1049. tor_free(debugfile);
  1050. err:
  1051. return;
  1052. }
  1053. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  1054. * <b>s</b>. Return 0 on success, -1 on failure.
  1055. */
  1056. int
  1057. router_get_dir_hash(const char *s, char *digest)
  1058. {
  1059. return router_get_hash_impl(s, strlen(s), digest,
  1060. "signed-directory","\ndirectory-signature",'\n',
  1061. DIGEST_SHA1);
  1062. }
  1063. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  1064. * <b>s</b>. Return 0 on success, -1 on failure.
  1065. */
  1066. int
  1067. router_get_router_hash(const char *s, size_t s_len, char *digest)
  1068. {
  1069. return router_get_hash_impl(s, s_len, digest,
  1070. "router ","\nrouter-signature", '\n',
  1071. DIGEST_SHA1);
  1072. }
  1073. /** Set <b>digests</b> to all the digests of the consensus document in
  1074. * <b>s</b> */
  1075. int
  1076. router_get_networkstatus_v3_hashes(const char *s, common_digests_t *digests)
  1077. {
  1078. return router_get_hashes_impl(s,strlen(s),digests,
  1079. "network-status-version",
  1080. "\ndirectory-signature",
  1081. ' ');
  1082. }
  1083. /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
  1084. * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
  1085. int
  1086. router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
  1087. {
  1088. return router_get_hash_impl(s, s_len, digest, "extra-info",
  1089. "\nrouter-signature",'\n', DIGEST_SHA1);
  1090. }
  1091. /** Helper: used to generate signatures for routers, directories and
  1092. * network-status objects. Given a <b>digest_len</b>-byte digest in
  1093. * <b>digest</b> and a secret <b>private_key</b>, generate an PKCS1-padded
  1094. * signature, BASE64-encode it, surround it with -----BEGIN/END----- pairs,
  1095. * and return the new signature on success or NULL on failure.
  1096. */
  1097. char *
  1098. router_get_dirobj_signature(const char *digest,
  1099. size_t digest_len,
  1100. const crypto_pk_t *private_key)
  1101. {
  1102. char *signature;
  1103. size_t i, keysize;
  1104. int siglen;
  1105. char *buf = NULL;
  1106. size_t buf_len;
  1107. /* overestimate of BEGIN/END lines total len. */
  1108. #define BEGIN_END_OVERHEAD_LEN 64
  1109. keysize = crypto_pk_keysize(private_key);
  1110. signature = tor_malloc(keysize);
  1111. siglen = crypto_pk_private_sign(private_key, signature, keysize,
  1112. digest, digest_len);
  1113. if (siglen < 0) {
  1114. log_warn(LD_BUG,"Couldn't sign digest.");
  1115. goto err;
  1116. }
  1117. /* The *2 here is a ridiculous overestimate of base-64 overhead. */
  1118. buf_len = (siglen * 2) + BEGIN_END_OVERHEAD_LEN;
  1119. buf = tor_malloc(buf_len);
  1120. if (strlcpy(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  1121. goto truncated;
  1122. i = strlen(buf);
  1123. if (base64_encode(buf+i, buf_len-i, signature, siglen,
  1124. BASE64_ENCODE_MULTILINE) < 0) {
  1125. log_warn(LD_BUG,"couldn't base64-encode signature");
  1126. goto err;
  1127. }
  1128. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  1129. goto truncated;
  1130. tor_free(signature);
  1131. return buf;
  1132. truncated:
  1133. log_warn(LD_BUG,"tried to exceed string length.");
  1134. err:
  1135. tor_free(signature);
  1136. tor_free(buf);
  1137. return NULL;
  1138. }
  1139. /** Helper: used to generate signatures for routers, directories and
  1140. * network-status objects. Given a digest in <b>digest</b> and a secret
  1141. * <b>private_key</b>, generate a PKCS1-padded signature, BASE64-encode it,
  1142. * surround it with -----BEGIN/END----- pairs, and write it to the
  1143. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  1144. * failure.
  1145. */
  1146. int
  1147. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  1148. size_t digest_len, crypto_pk_t *private_key)
  1149. {
  1150. size_t sig_len, s_len;
  1151. char *sig = router_get_dirobj_signature(digest, digest_len, private_key);
  1152. if (!sig) {
  1153. log_warn(LD_BUG, "No signature generated");
  1154. return -1;
  1155. }
  1156. sig_len = strlen(sig);
  1157. s_len = strlen(buf);
  1158. if (sig_len + s_len + 1 > buf_len) {
  1159. log_warn(LD_BUG, "Not enough room for signature");
  1160. tor_free(sig);
  1161. return -1;
  1162. }
  1163. memcpy(buf+s_len, sig, sig_len+1);
  1164. tor_free(sig);
  1165. return 0;
  1166. }
  1167. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  1168. * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
  1169. * entries. Else, return VS_OLD if every member of
  1170. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  1171. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  1172. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  1173. * is newer than <b>myversion.</b>. Else, return VS_NEW if every member of
  1174. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  1175. * VS_UNRECOMMENDED.
  1176. *
  1177. * (versionlist is a comma-separated list of version strings,
  1178. * optionally prefixed with "Tor". Versions that can't be parsed are
  1179. * ignored.)
  1180. */
  1181. version_status_t
  1182. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  1183. {
  1184. tor_version_t mine, other;
  1185. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  1186. found_any_in_series = 0, r, same;
  1187. version_status_t ret = VS_UNRECOMMENDED;
  1188. smartlist_t *version_sl;
  1189. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  1190. myversion, versionlist);
  1191. if (tor_version_parse(myversion, &mine)) {
  1192. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  1193. tor_assert(0);
  1194. }
  1195. version_sl = smartlist_new();
  1196. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  1197. if (!strlen(versionlist)) { /* no authorities cared or agreed */
  1198. ret = VS_EMPTY;
  1199. goto done;
  1200. }
  1201. SMARTLIST_FOREACH_BEGIN(version_sl, const char *, cp) {
  1202. if (!strcmpstart(cp, "Tor "))
  1203. cp += 4;
  1204. if (tor_version_parse(cp, &other)) {
  1205. /* Couldn't parse other; it can't be a match. */
  1206. } else {
  1207. same = tor_version_same_series(&mine, &other);
  1208. if (same)
  1209. found_any_in_series = 1;
  1210. r = tor_version_compare(&mine, &other);
  1211. if (r==0) {
  1212. ret = VS_RECOMMENDED;
  1213. goto done;
  1214. } else if (r<0) {
  1215. found_newer = 1;
  1216. if (same)
  1217. found_newer_in_series = 1;
  1218. } else if (r>0) {
  1219. found_older = 1;
  1220. }
  1221. }
  1222. } SMARTLIST_FOREACH_END(cp);
  1223. /* We didn't find the listed version. Is it new or old? */
  1224. if (found_any_in_series && !found_newer_in_series && found_newer) {
  1225. ret = VS_NEW_IN_SERIES;
  1226. } else if (found_newer && !found_older) {
  1227. ret = VS_OLD;
  1228. } else if (found_older && !found_newer) {
  1229. ret = VS_NEW;
  1230. } else {
  1231. ret = VS_UNRECOMMENDED;
  1232. }
  1233. done:
  1234. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  1235. smartlist_free(version_sl);
  1236. return ret;
  1237. }
  1238. /** Return true iff <b>key</b> is allowed to sign directories.
  1239. */
  1240. static int
  1241. dir_signing_key_is_trusted(crypto_pk_t *key)
  1242. {
  1243. char digest[DIGEST_LEN];
  1244. if (!key) return 0;
  1245. if (crypto_pk_get_digest(key, digest) < 0) {
  1246. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  1247. return 0;
  1248. }
  1249. if (!router_digest_is_trusted_dir(digest)) {
  1250. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  1251. return 0;
  1252. }
  1253. return 1;
  1254. }
  1255. /** Check whether the object body of the token in <b>tok</b> has a good
  1256. * signature for <b>digest</b> using key <b>pkey</b>. If
  1257. * <b>CST_CHECK_AUTHORITY</b> is set, make sure that <b>pkey</b> is the key of
  1258. * a directory authority. If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
  1259. * the object type of the signature object. Use <b>doctype</b> as the type of
  1260. * the document when generating log messages. Return 0 on success, negative
  1261. * on failure.
  1262. */
  1263. static int
  1264. check_signature_token(const char *digest,
  1265. ssize_t digest_len,
  1266. directory_token_t *tok,
  1267. crypto_pk_t *pkey,
  1268. int flags,
  1269. const char *doctype)
  1270. {
  1271. char *signed_digest;
  1272. size_t keysize;
  1273. const int check_authority = (flags & CST_CHECK_AUTHORITY);
  1274. const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
  1275. tor_assert(pkey);
  1276. tor_assert(tok);
  1277. tor_assert(digest);
  1278. tor_assert(doctype);
  1279. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  1280. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  1281. doctype);
  1282. return -1;
  1283. }
  1284. if (check_objtype) {
  1285. if (strcmp(tok->object_type, "SIGNATURE")) {
  1286. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  1287. return -1;
  1288. }
  1289. }
  1290. keysize = crypto_pk_keysize(pkey);
  1291. signed_digest = tor_malloc(keysize);
  1292. if (crypto_pk_public_checksig(pkey, signed_digest, keysize,
  1293. tok->object_body, tok->object_size)
  1294. < digest_len) {
  1295. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  1296. tor_free(signed_digest);
  1297. return -1;
  1298. }
  1299. // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  1300. // hex_str(signed_digest,4));
  1301. if (tor_memneq(digest, signed_digest, digest_len)) {
  1302. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  1303. tor_free(signed_digest);
  1304. return -1;
  1305. }
  1306. tor_free(signed_digest);
  1307. return 0;
  1308. }
  1309. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  1310. * or to the first of the annotations proceeding the next router or
  1311. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  1312. * we found an extrainfo, or false if found a router. Do not scan beyond
  1313. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  1314. static int
  1315. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  1316. const char *eos,
  1317. int *is_extrainfo_out)
  1318. {
  1319. const char *annotations = NULL;
  1320. const char *s = *s_ptr;
  1321. s = eat_whitespace_eos(s, eos);
  1322. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  1323. /* We're at the start of a line. */
  1324. tor_assert(*s != '\n');
  1325. if (*s == '@' && !annotations) {
  1326. annotations = s;
  1327. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  1328. *s_ptr = annotations ? annotations : s;
  1329. *is_extrainfo_out = 0;
  1330. return 0;
  1331. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  1332. *s_ptr = annotations ? annotations : s;
  1333. *is_extrainfo_out = 1;
  1334. return 0;
  1335. }
  1336. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  1337. break;
  1338. s = eat_whitespace_eos(s, eos);
  1339. }
  1340. return -1;
  1341. }
  1342. /** Given a string *<b>s</b> containing a concatenated sequence of router
  1343. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  1344. * them and stores the result in <b>dest</b>. All routers are marked running
  1345. * and valid. Advances *s to a point immediately following the last router
  1346. * entry. Ignore any trailing router entries that are not complete.
  1347. *
  1348. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  1349. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  1350. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  1351. *
  1352. * Returns 0 on success and -1 on failure. Adds a digest to
  1353. * <b>invalid_digests_out</b> for every entry that was unparseable or
  1354. * invalid. (This may cause duplicate entries.)
  1355. */
  1356. int
  1357. router_parse_list_from_string(const char **s, const char *eos,
  1358. smartlist_t *dest,
  1359. saved_location_t saved_location,
  1360. int want_extrainfo,
  1361. int allow_annotations,
  1362. const char *prepend_annotations,
  1363. smartlist_t *invalid_digests_out)
  1364. {
  1365. routerinfo_t *router;
  1366. extrainfo_t *extrainfo;
  1367. signed_descriptor_t *signed_desc = NULL;
  1368. void *elt;
  1369. const char *end, *start;
  1370. int have_extrainfo;
  1371. tor_assert(s);
  1372. tor_assert(*s);
  1373. tor_assert(dest);
  1374. start = *s;
  1375. if (!eos)
  1376. eos = *s + strlen(*s);
  1377. tor_assert(eos >= *s);
  1378. while (1) {
  1379. char raw_digest[DIGEST_LEN];
  1380. int have_raw_digest = 0;
  1381. int dl_again = 0;
  1382. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  1383. break;
  1384. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  1385. if (end)
  1386. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  1387. if (end)
  1388. end += strlen("\n-----END SIGNATURE-----\n");
  1389. if (!end)
  1390. break;
  1391. elt = NULL;
  1392. if (have_extrainfo && want_extrainfo) {
  1393. routerlist_t *rl = router_get_routerlist();
  1394. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  1395. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  1396. saved_location != SAVED_IN_CACHE,
  1397. rl->identity_map, &dl_again);
  1398. if (extrainfo) {
  1399. signed_desc = &extrainfo->cache_info;
  1400. elt = extrainfo;
  1401. }
  1402. } else if (!have_extrainfo && !want_extrainfo) {
  1403. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  1404. router = router_parse_entry_from_string(*s, end,
  1405. saved_location != SAVED_IN_CACHE,
  1406. allow_annotations,
  1407. prepend_annotations, &dl_again);
  1408. if (router) {
  1409. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  1410. router_describe(router),
  1411. router_purpose_to_string(router->purpose));
  1412. signed_desc = &router->cache_info;
  1413. elt = router;
  1414. }
  1415. }
  1416. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  1417. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  1418. }
  1419. if (!elt) {
  1420. *s = end;
  1421. continue;
  1422. }
  1423. if (saved_location != SAVED_NOWHERE) {
  1424. tor_assert(signed_desc);
  1425. signed_desc->saved_location = saved_location;
  1426. signed_desc->saved_offset = *s - start;
  1427. }
  1428. *s = end;
  1429. smartlist_add(dest, elt);
  1430. }
  1431. return 0;
  1432. }
  1433. /* For debugging: define to count every descriptor digest we've seen so we
  1434. * know if we need to try harder to avoid duplicate verifies. */
  1435. #undef COUNT_DISTINCT_DIGESTS
  1436. #ifdef COUNT_DISTINCT_DIGESTS
  1437. static digestmap_t *verified_digests = NULL;
  1438. #endif
  1439. /** Log the total count of the number of distinct router digests we've ever
  1440. * verified. When compared to the number of times we've verified routerdesc
  1441. * signatures <i>in toto</i>, this will tell us if we're doing too much
  1442. * multiple-verification. */
  1443. void
  1444. dump_distinct_digest_count(int severity)
  1445. {
  1446. #ifdef COUNT_DISTINCT_DIGESTS
  1447. if (!verified_digests)
  1448. verified_digests = digestmap_new();
  1449. tor_log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  1450. digestmap_size(verified_digests));
  1451. #else
  1452. (void)severity; /* suppress "unused parameter" warning */
  1453. #endif
  1454. }
  1455. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  1456. * with at least one argument (use GE(1) in setup). If found, store
  1457. * address and port number to <b>addr_out</b> and
  1458. * <b>port_out</b>. Return number of OR ports found. */
  1459. static int
  1460. find_single_ipv6_orport(const smartlist_t *list,
  1461. tor_addr_t *addr_out,
  1462. uint16_t *port_out)
  1463. {
  1464. int ret = 0;
  1465. tor_assert(list != NULL);
  1466. tor_assert(addr_out != NULL);
  1467. tor_assert(port_out != NULL);
  1468. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  1469. tor_addr_t a;
  1470. maskbits_t bits;
  1471. uint16_t port_min, port_max;
  1472. tor_assert(t->n_args >= 1);
  1473. /* XXXX Prop186 the full spec allows much more than this. */
  1474. if (tor_addr_parse_mask_ports(t->args[0], 0,
  1475. &a, &bits, &port_min,
  1476. &port_max) == AF_INET6 &&
  1477. bits == 128 &&
  1478. port_min == port_max) {
  1479. /* Okay, this is one we can understand. Use it and ignore
  1480. any potential more addresses in list. */
  1481. tor_addr_copy(addr_out, &a);
  1482. *port_out = port_min;
  1483. ret = 1;
  1484. break;
  1485. }
  1486. } SMARTLIST_FOREACH_END(t);
  1487. return ret;
  1488. }
  1489. /** Helper function: reads a single router entry from *<b>s</b> ...
  1490. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  1491. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  1492. * s through end into the signed_descriptor_body of the resulting
  1493. * routerinfo_t.
  1494. *
  1495. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  1496. *
  1497. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  1498. * before the router; if it's false, reject the router if it's annotated. If
  1499. * <b>prepend_annotations</b> is set, it should contain some annotations:
  1500. * append them to the front of the router before parsing it, and keep them
  1501. * around when caching the router.
  1502. *
  1503. * Only one of allow_annotations and prepend_annotations may be set.
  1504. *
  1505. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1506. * if it's okay to try to download a descriptor with this same digest again,
  1507. * and 0 if it isn't. (It might not be okay to download it again if part of
  1508. * the part covered by the digest is invalid.)
  1509. */
  1510. routerinfo_t *
  1511. router_parse_entry_from_string(const char *s, const char *end,
  1512. int cache_copy, int allow_annotations,
  1513. const char *prepend_annotations,
  1514. int *can_dl_again_out)
  1515. {
  1516. routerinfo_t *router = NULL;
  1517. char digest[128];
  1518. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  1519. directory_token_t *tok;
  1520. struct in_addr in;
  1521. const char *start_of_annotations, *cp, *s_dup = s;
  1522. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  1523. int ok = 1;
  1524. memarea_t *area = NULL;
  1525. tor_cert_t *ntor_cc_cert = NULL;
  1526. /* Do not set this to '1' until we have parsed everything that we intend to
  1527. * parse that's covered by the hash. */
  1528. int can_dl_again = 0;
  1529. tor_assert(!allow_annotations || !prepend_annotations);
  1530. if (!end) {
  1531. end = s + strlen(s);
  1532. }
  1533. /* point 'end' to a point immediately after the final newline. */
  1534. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1535. --end;
  1536. area = memarea_new();
  1537. tokens = smartlist_new();
  1538. if (prepend_annotations) {
  1539. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  1540. routerdesc_token_table,TS_NOCHECK)) {
  1541. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1542. goto err;
  1543. }
  1544. }
  1545. start_of_annotations = s;
  1546. cp = tor_memstr(s, end-s, "\nrouter ");
  1547. if (!cp) {
  1548. if (end-s < 7 || strcmpstart(s, "router ")) {
  1549. log_warn(LD_DIR, "No router keyword found.");
  1550. goto err;
  1551. }
  1552. } else {
  1553. s = cp+1;
  1554. }
  1555. if (start_of_annotations != s) { /* We have annotations */
  1556. if (allow_annotations) {
  1557. if (tokenize_string(area,start_of_annotations,s,tokens,
  1558. routerdesc_token_table,TS_NOCHECK)) {
  1559. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1560. goto err;
  1561. }
  1562. } else {
  1563. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  1564. "loaded from disk. Dropping it.");
  1565. goto err;
  1566. }
  1567. }
  1568. if (router_get_router_hash(s, end - s, digest) < 0) {
  1569. log_warn(LD_DIR, "Couldn't compute router hash.");
  1570. goto err;
  1571. }
  1572. {
  1573. int flags = 0;
  1574. if (allow_annotations)
  1575. flags |= TS_ANNOTATIONS_OK;
  1576. if (prepend_annotations)
  1577. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  1578. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  1579. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1580. goto err;
  1581. }
  1582. }
  1583. if (smartlist_len(tokens) < 2) {
  1584. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1585. goto err;
  1586. }
  1587. tok = find_by_keyword(tokens, K_ROUTER);
  1588. const int router_token_pos = smartlist_pos(tokens, tok);
  1589. tor_assert(tok->n_args >= 5);
  1590. router = tor_malloc_zero(sizeof(routerinfo_t));
  1591. router->cert_expiration_time = TIME_MAX;
  1592. router->cache_info.routerlist_index = -1;
  1593. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  1594. router->cache_info.signed_descriptor_len = end-s;
  1595. if (cache_copy) {
  1596. size_t len = router->cache_info.signed_descriptor_len +
  1597. router->cache_info.annotations_len;
  1598. char *signed_body =
  1599. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1600. if (prepend_annotations) {
  1601. memcpy(signed_body, prepend_annotations, prepend_len);
  1602. signed_body += prepend_len;
  1603. }
  1604. /* This assertion will always succeed.
  1605. * len == signed_desc_len + annotations_len
  1606. * == end-s + s-start_of_annotations + prepend_len
  1607. * == end-start_of_annotations + prepend_len
  1608. * We already wrote prepend_len bytes into the buffer; now we're
  1609. * writing end-start_of_annotations -NM. */
  1610. tor_assert(signed_body+(end-start_of_annotations) ==
  1611. router->cache_info.signed_descriptor_body+len);
  1612. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  1613. router->cache_info.signed_descriptor_body[len] = '\0';
  1614. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1615. }
  1616. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1617. router->nickname = tor_strdup(tok->args[0]);
  1618. if (!is_legal_nickname(router->nickname)) {
  1619. log_warn(LD_DIR,"Router nickname is invalid");
  1620. goto err;
  1621. }
  1622. if (!tor_inet_aton(tok->args[1], &in)) {
  1623. log_warn(LD_DIR,"Router address is not an IP address.");
  1624. goto err;
  1625. }
  1626. router->addr = ntohl(in.s_addr);
  1627. router->or_port =
  1628. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1629. if (!ok) {
  1630. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1631. goto err;
  1632. }
  1633. router->dir_port =
  1634. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1635. if (!ok) {
  1636. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1637. goto err;
  1638. }
  1639. tok = find_by_keyword(tokens, K_BANDWIDTH);
  1640. tor_assert(tok->n_args >= 3);
  1641. router->bandwidthrate = (int)
  1642. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1643. if (!ok) {
  1644. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1645. escaped(tok->args[0]));
  1646. goto err;
  1647. }
  1648. router->bandwidthburst =
  1649. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1650. if (!ok) {
  1651. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1652. goto err;
  1653. }
  1654. router->bandwidthcapacity = (int)
  1655. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1656. if (!ok) {
  1657. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1658. goto err;
  1659. }
  1660. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  1661. tor_assert(tok->n_args);
  1662. router->purpose = router_purpose_from_string(tok->args[0]);
  1663. } else {
  1664. router->purpose = ROUTER_PURPOSE_GENERAL;
  1665. }
  1666. router->cache_info.send_unencrypted =
  1667. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1668. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  1669. tor_assert(tok->n_args >= 1);
  1670. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1671. if (!ok) {
  1672. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1673. goto err;
  1674. }
  1675. }
  1676. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  1677. tor_assert(tok->n_args >= 1);
  1678. router->is_hibernating
  1679. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1680. }
  1681. tok = find_by_keyword(tokens, K_PUBLISHED);
  1682. tor_assert(tok->n_args == 1);
  1683. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1684. goto err;
  1685. tok = find_by_keyword(tokens, K_ONION_KEY);
  1686. if (!crypto_pk_public_exponent_ok(tok->key)) {
  1687. log_warn(LD_DIR,
  1688. "Relay's onion key had invalid exponent.");
  1689. goto err;
  1690. }
  1691. router->onion_pkey = tok->key;
  1692. tok->key = NULL; /* Prevent free */
  1693. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  1694. curve25519_public_key_t k;
  1695. tor_assert(tok->n_args >= 1);
  1696. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  1697. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  1698. goto err;
  1699. }
  1700. router->onion_curve25519_pkey =
  1701. tor_memdup(&k, sizeof(curve25519_public_key_t));
  1702. }
  1703. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1704. router->identity_pkey = tok->key;
  1705. tok->key = NULL; /* Prevent free */
  1706. if (crypto_pk_get_digest(router->identity_pkey,
  1707. router->cache_info.identity_digest)) {
  1708. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1709. }
  1710. {
  1711. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  1712. *master_key_tok;
  1713. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1714. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1715. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  1716. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  1717. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  1718. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  1719. !!cc_tap_tok + !!cc_ntor_tok;
  1720. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  1721. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  1722. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1723. "cross-certification support");
  1724. goto err;
  1725. }
  1726. if (master_key_tok && !ed_sig_tok) {
  1727. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  1728. "certificate");
  1729. goto err;
  1730. }
  1731. if (ed_sig_tok) {
  1732. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  1733. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1734. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  1735. (ed_cert_token_pos != router_token_pos + 1 &&
  1736. ed_cert_token_pos != router_token_pos - 1)) {
  1737. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1738. goto err;
  1739. }
  1740. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1741. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1742. goto err;
  1743. }
  1744. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1745. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1746. goto err;
  1747. }
  1748. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  1749. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  1750. "in decriptor");
  1751. goto err;
  1752. }
  1753. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  1754. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  1755. "in decriptor");
  1756. goto err;
  1757. }
  1758. if (strcmp(cc_ntor_tok->args[0], "0") &&
  1759. strcmp(cc_ntor_tok->args[0], "1")) {
  1760. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  1761. goto err;
  1762. }
  1763. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  1764. uint8_t d256[DIGEST256_LEN];
  1765. const char *signed_start, *signed_end;
  1766. tor_cert_t *cert = tor_cert_parse(
  1767. (const uint8_t*)ed_cert_tok->object_body,
  1768. ed_cert_tok->object_size);
  1769. if (! cert) {
  1770. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1771. goto err;
  1772. }
  1773. /* makes sure it gets freed. */
  1774. router->cache_info.signing_key_cert = cert;
  1775. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1776. ! cert->signing_key_included) {
  1777. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1778. goto err;
  1779. }
  1780. if (master_key_tok) {
  1781. /* This token is optional, but if it's present, it must match
  1782. * the signature in the signing cert, or supplant it. */
  1783. tor_assert(master_key_tok->n_args >= 1);
  1784. ed25519_public_key_t pkey;
  1785. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  1786. log_warn(LD_DIR, "Can't parse ed25519 master key");
  1787. goto err;
  1788. }
  1789. if (fast_memneq(&cert->signing_key.pubkey,
  1790. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  1791. log_warn(LD_DIR, "Ed25519 master key does not match "
  1792. "key in certificate");
  1793. goto err;
  1794. }
  1795. }
  1796. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  1797. cc_ntor_tok->object_size);
  1798. if (!ntor_cc_cert) {
  1799. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  1800. goto err;
  1801. }
  1802. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  1803. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  1804. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  1805. goto err;
  1806. }
  1807. ed25519_public_key_t ntor_cc_pk;
  1808. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  1809. router->onion_curve25519_pkey,
  1810. ntor_cc_sign_bit)<0) {
  1811. log_warn(LD_DIR, "Error converting onion key to ed25519");
  1812. goto err;
  1813. }
  1814. if (router_get_hash_impl_helper(s, end-s, "router ",
  1815. "\nrouter-sig-ed25519",
  1816. ' ', &signed_start, &signed_end) < 0) {
  1817. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  1818. goto err;
  1819. }
  1820. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1821. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1822. strlen(ED_DESC_SIGNATURE_PREFIX));
  1823. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1824. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1825. crypto_digest_free(d);
  1826. ed25519_checkable_t check[3];
  1827. int check_ok[3];
  1828. if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
  1829. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1830. goto err;
  1831. }
  1832. if (tor_cert_get_checkable_sig(&check[1],
  1833. ntor_cc_cert, &ntor_cc_pk) < 0) {
  1834. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  1835. goto err;
  1836. }
  1837. if (ed25519_signature_from_base64(&check[2].signature,
  1838. ed_sig_tok->args[0])<0) {
  1839. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1840. goto err;
  1841. }
  1842. check[2].pubkey = &cert->signed_key;
  1843. check[2].msg = d256;
  1844. check[2].len = DIGEST256_LEN;
  1845. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  1846. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1847. goto err;
  1848. }
  1849. if (check_tap_onion_key_crosscert(
  1850. (const uint8_t*)cc_tap_tok->object_body,
  1851. (int)cc_tap_tok->object_size,
  1852. router->onion_pkey,
  1853. &cert->signing_key,
  1854. (const uint8_t*)router->cache_info.identity_digest)<0) {
  1855. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  1856. goto err;
  1857. }
  1858. /* We check this before adding it to the routerlist. */
  1859. if (cert->valid_until < ntor_cc_cert->valid_until)
  1860. router->cert_expiration_time = cert->valid_until;
  1861. else
  1862. router->cert_expiration_time = ntor_cc_cert->valid_until;
  1863. }
  1864. }
  1865. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1866. /* If there's a fingerprint line, it must match the identity digest. */
  1867. char d[DIGEST_LEN];
  1868. tor_assert(tok->n_args == 1);
  1869. tor_strstrip(tok->args[0], " ");
  1870. if (base16_decode(d, DIGEST_LEN,
  1871. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  1872. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1873. escaped(tok->args[0]));
  1874. goto err;
  1875. }
  1876. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1877. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1878. tok->args[0]);
  1879. goto err;
  1880. }
  1881. }
  1882. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1883. router->platform = tor_strdup(tok->args[0]);
  1884. }
  1885. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1886. router->contact_info = tor_strdup(tok->args[0]);
  1887. }
  1888. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1889. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1890. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1891. "older Tors.");
  1892. goto err;
  1893. }
  1894. {
  1895. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1896. if (or_addresses) {
  1897. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1898. &router->ipv6_orport);
  1899. smartlist_free(or_addresses);
  1900. }
  1901. }
  1902. exit_policy_tokens = find_all_exitpolicy(tokens);
  1903. if (!smartlist_len(exit_policy_tokens)) {
  1904. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1905. goto err;
  1906. }
  1907. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1908. if (router_add_exit_policy(router,t)<0) {
  1909. log_warn(LD_DIR,"Error in exit policy");
  1910. goto err;
  1911. });
  1912. policy_expand_private(&router->exit_policy);
  1913. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1914. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1915. if (! router->ipv6_exit_policy) {
  1916. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1917. goto err;
  1918. }
  1919. }
  1920. if (policy_is_reject_star(router->exit_policy, AF_INET) &&
  1921. (!router->ipv6_exit_policy ||
  1922. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1923. router->policy_is_reject_star = 1;
  1924. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1925. int i;
  1926. router->declared_family = smartlist_new();
  1927. for (i=0;i<tok->n_args;++i) {
  1928. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1929. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1930. escaped(tok->args[i]));
  1931. goto err;
  1932. }
  1933. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1934. }
  1935. }
  1936. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1937. router->caches_extra_info = 1;
  1938. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1939. router->allow_single_hop_exits = 1;
  1940. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1941. tor_assert(tok->n_args >= 1);
  1942. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1943. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  1944. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1945. log_warn(LD_DIR,"Invalid extra info digest");
  1946. }
  1947. } else {
  1948. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1949. }
  1950. if (tok->n_args >= 2) {
  1951. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  1952. tok->args[1]) < 0) {
  1953. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  1954. escaped(tok->args[1]));
  1955. }
  1956. }
  1957. }
  1958. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1959. router->wants_to_be_hs_dir = 1;
  1960. }
  1961. /* This router accepts tunnelled directory requests via begindir if it has
  1962. * an open dirport or it included "tunnelled-dir-server". */
  1963. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1964. router->supports_tunnelled_dir_requests = 1;
  1965. }
  1966. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1967. note_crypto_pk_op(VERIFY_RTR);
  1968. #ifdef COUNT_DISTINCT_DIGESTS
  1969. if (!verified_digests)
  1970. verified_digests = digestmap_new();
  1971. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1972. #endif
  1973. if (!router->or_port) {
  1974. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1975. goto err;
  1976. }
  1977. /* We've checked everything that's covered by the hash. */
  1978. can_dl_again = 1;
  1979. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1980. "router descriptor") < 0)
  1981. goto err;
  1982. if (!router->platform) {
  1983. router->platform = tor_strdup("<unknown>");
  1984. }
  1985. goto done;
  1986. err:
  1987. dump_desc(s_dup, "router descriptor");
  1988. routerinfo_free(router);
  1989. router = NULL;
  1990. done:
  1991. tor_cert_free(ntor_cc_cert);
  1992. if (tokens) {
  1993. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1994. smartlist_free(tokens);
  1995. }
  1996. smartlist_free(exit_policy_tokens);
  1997. if (area) {
  1998. DUMP_AREA(area, "routerinfo");
  1999. memarea_drop_all(area);
  2000. }
  2001. if (can_dl_again_out)
  2002. *can_dl_again_out = can_dl_again;
  2003. return router;
  2004. }
  2005. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  2006. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  2007. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  2008. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  2009. * as a map from router identity to routerinfo_t when looking up signing keys.
  2010. *
  2011. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  2012. * if it's okay to try to download an extrainfo with this same digest again,
  2013. * and 0 if it isn't. (It might not be okay to download it again if part of
  2014. * the part covered by the digest is invalid.)
  2015. */
  2016. extrainfo_t *
  2017. extrainfo_parse_entry_from_string(const char *s, const char *end,
  2018. int cache_copy, struct digest_ri_map_t *routermap,
  2019. int *can_dl_again_out)
  2020. {
  2021. extrainfo_t *extrainfo = NULL;
  2022. char digest[128];
  2023. smartlist_t *tokens = NULL;
  2024. directory_token_t *tok;
  2025. crypto_pk_t *key = NULL;
  2026. routerinfo_t *router = NULL;
  2027. memarea_t *area = NULL;
  2028. const char *s_dup = s;
  2029. /* Do not set this to '1' until we have parsed everything that we intend to
  2030. * parse that's covered by the hash. */
  2031. int can_dl_again = 0;
  2032. if (!end) {
  2033. end = s + strlen(s);
  2034. }
  2035. /* point 'end' to a point immediately after the final newline. */
  2036. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  2037. --end;
  2038. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  2039. log_warn(LD_DIR, "Couldn't compute router hash.");
  2040. goto err;
  2041. }
  2042. tokens = smartlist_new();
  2043. area = memarea_new();
  2044. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  2045. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  2046. goto err;
  2047. }
  2048. if (smartlist_len(tokens) < 2) {
  2049. log_warn(LD_DIR, "Impossibly short extra-info document.");
  2050. goto err;
  2051. }
  2052. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  2053. tok = smartlist_get(tokens,0);
  2054. if (tok->tp != K_EXTRA_INFO) {
  2055. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  2056. goto err;
  2057. }
  2058. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  2059. extrainfo->cache_info.is_extrainfo = 1;
  2060. if (cache_copy)
  2061. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  2062. extrainfo->cache_info.signed_descriptor_len = end-s;
  2063. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  2064. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  2065. tor_assert(tok->n_args >= 2);
  2066. if (!is_legal_nickname(tok->args[0])) {
  2067. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  2068. goto err;
  2069. }
  2070. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  2071. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2072. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  2073. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  2074. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  2075. escaped(tok->args[1]));
  2076. goto err;
  2077. }
  2078. tok = find_by_keyword(tokens, K_PUBLISHED);
  2079. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  2080. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  2081. escaped(tok->args[0]));
  2082. goto err;
  2083. }
  2084. {
  2085. directory_token_t *ed_sig_tok, *ed_cert_tok;
  2086. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  2087. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  2088. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  2089. if (n_ed_toks != 0 && n_ed_toks != 2) {
  2090. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  2091. "cross-certification support");
  2092. goto err;
  2093. }
  2094. if (ed_sig_tok) {
  2095. tor_assert(ed_cert_tok);
  2096. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  2097. if (ed_cert_token_pos != 1) {
  2098. /* Accept this in position 0 XXXX */
  2099. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  2100. goto err;
  2101. }
  2102. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  2103. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  2104. goto err;
  2105. }
  2106. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  2107. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  2108. goto err;
  2109. }
  2110. uint8_t d256[DIGEST256_LEN];
  2111. const char *signed_start, *signed_end;
  2112. tor_cert_t *cert = tor_cert_parse(
  2113. (const uint8_t*)ed_cert_tok->object_body,
  2114. ed_cert_tok->object_size);
  2115. if (! cert) {
  2116. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  2117. goto err;
  2118. }
  2119. /* makes sure it gets freed. */
  2120. extrainfo->cache_info.signing_key_cert = cert;
  2121. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  2122. ! cert->signing_key_included) {
  2123. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  2124. goto err;
  2125. }
  2126. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  2127. "\nrouter-sig-ed25519",
  2128. ' ', &signed_start, &signed_end) < 0) {
  2129. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  2130. goto err;
  2131. }
  2132. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  2133. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  2134. strlen(ED_DESC_SIGNATURE_PREFIX));
  2135. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  2136. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  2137. crypto_digest_free(d);
  2138. ed25519_checkable_t check[2];
  2139. int check_ok[2];
  2140. if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
  2141. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  2142. goto err;
  2143. }
  2144. if (ed25519_signature_from_base64(&check[1].signature,
  2145. ed_sig_tok->args[0])<0) {
  2146. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  2147. goto err;
  2148. }
  2149. check[1].pubkey = &cert->signed_key;
  2150. check[1].msg = d256;
  2151. check[1].len = DIGEST256_LEN;
  2152. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  2153. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  2154. goto err;
  2155. }
  2156. /* We don't check the certificate expiration time: checking that it
  2157. * matches the cert in the router descriptor is adequate. */
  2158. }
  2159. }
  2160. /* We've checked everything that's covered by the hash. */
  2161. can_dl_again = 1;
  2162. if (routermap &&
  2163. (router = digestmap_get((digestmap_t*)routermap,
  2164. extrainfo->cache_info.identity_digest))) {
  2165. key = router->identity_pkey;
  2166. }
  2167. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  2168. if (strcmp(tok->object_type, "SIGNATURE") ||
  2169. tok->object_size < 128 || tok->object_size > 512) {
  2170. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  2171. goto err;
  2172. }
  2173. if (key) {
  2174. note_crypto_pk_op(VERIFY_RTR);
  2175. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  2176. "extra-info") < 0)
  2177. goto err;
  2178. if (router)
  2179. extrainfo->cache_info.send_unencrypted =
  2180. router->cache_info.send_unencrypted;
  2181. } else {
  2182. extrainfo->pending_sig = tor_memdup(tok->object_body,
  2183. tok->object_size);
  2184. extrainfo->pending_sig_len = tok->object_size;
  2185. }
  2186. goto done;
  2187. err:
  2188. dump_desc(s_dup, "extra-info descriptor");
  2189. extrainfo_free(extrainfo);
  2190. extrainfo = NULL;
  2191. done:
  2192. if (tokens) {
  2193. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2194. smartlist_free(tokens);
  2195. }
  2196. if (area) {
  2197. DUMP_AREA(area, "extrainfo");
  2198. memarea_drop_all(area);
  2199. }
  2200. if (can_dl_again_out)
  2201. *can_dl_again_out = can_dl_again;
  2202. return extrainfo;
  2203. }
  2204. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  2205. * the first character after the certificate. */
  2206. authority_cert_t *
  2207. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  2208. {
  2209. /** Reject any certificate at least this big; it is probably an overflow, an
  2210. * attack, a bug, or some other nonsense. */
  2211. #define MAX_CERT_SIZE (128*1024)
  2212. authority_cert_t *cert = NULL, *old_cert;
  2213. smartlist_t *tokens = NULL;
  2214. char digest[DIGEST_LEN];
  2215. directory_token_t *tok;
  2216. char fp_declared[DIGEST_LEN];
  2217. char *eos;
  2218. size_t len;
  2219. int found;
  2220. memarea_t *area = NULL;
  2221. const char *s_dup = s;
  2222. s = eat_whitespace(s);
  2223. eos = strstr(s, "\ndir-key-certification");
  2224. if (! eos) {
  2225. log_warn(LD_DIR, "No signature found on key certificate");
  2226. return NULL;
  2227. }
  2228. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  2229. if (! eos) {
  2230. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  2231. return NULL;
  2232. }
  2233. eos = strchr(eos+2, '\n');
  2234. tor_assert(eos);
  2235. ++eos;
  2236. len = eos - s;
  2237. if (len > MAX_CERT_SIZE) {
  2238. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  2239. "rejecting", (unsigned long)len);
  2240. return NULL;
  2241. }
  2242. tokens = smartlist_new();
  2243. area = memarea_new();
  2244. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  2245. log_warn(LD_DIR, "Error tokenizing key certificate");
  2246. goto err;
  2247. }
  2248. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  2249. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  2250. goto err;
  2251. tok = smartlist_get(tokens, 0);
  2252. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  2253. log_warn(LD_DIR,
  2254. "Key certificate does not begin with a recognized version (3).");
  2255. goto err;
  2256. }
  2257. cert = tor_malloc_zero(sizeof(authority_cert_t));
  2258. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  2259. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  2260. tor_assert(tok->key);
  2261. cert->signing_key = tok->key;
  2262. tok->key = NULL;
  2263. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  2264. goto err;
  2265. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  2266. tor_assert(tok->key);
  2267. cert->identity_key = tok->key;
  2268. tok->key = NULL;
  2269. tok = find_by_keyword(tokens, K_FINGERPRINT);
  2270. tor_assert(tok->n_args);
  2271. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  2272. strlen(tok->args[0])) != DIGEST_LEN) {
  2273. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  2274. escaped(tok->args[0]));
  2275. goto err;
  2276. }
  2277. if (crypto_pk_get_digest(cert->identity_key,
  2278. cert->cache_info.identity_digest))
  2279. goto err;
  2280. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  2281. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  2282. "fingerprint");
  2283. goto err;
  2284. }
  2285. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  2286. if (tok) {
  2287. struct in_addr in;
  2288. char *address = NULL;
  2289. tor_assert(tok->n_args);
  2290. /* XXX++ use some tor_addr parse function below instead. -RD */
  2291. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  2292. &cert->dir_port) < 0 ||
  2293. tor_inet_aton(address, &in) == 0) {
  2294. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  2295. tor_free(address);
  2296. goto err;
  2297. }
  2298. cert->addr = ntohl(in.s_addr);
  2299. tor_free(address);
  2300. }
  2301. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  2302. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  2303. goto err;
  2304. }
  2305. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  2306. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  2307. goto err;
  2308. }
  2309. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  2310. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  2311. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  2312. goto err;
  2313. }
  2314. /* If we already have this cert, don't bother checking the signature. */
  2315. old_cert = authority_cert_get_by_digests(
  2316. cert->cache_info.identity_digest,
  2317. cert->signing_key_digest);
  2318. found = 0;
  2319. if (old_cert) {
  2320. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  2321. * buy us much. */
  2322. if (old_cert->cache_info.signed_descriptor_len == len &&
  2323. old_cert->cache_info.signed_descriptor_body &&
  2324. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  2325. log_debug(LD_DIR, "We already checked the signature on this "
  2326. "certificate; no need to do so again.");
  2327. found = 1;
  2328. }
  2329. }
  2330. if (!found) {
  2331. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  2332. "key certificate")) {
  2333. goto err;
  2334. }
  2335. tok = find_by_keyword(tokens, K_DIR_KEY_CROSSCERT);
  2336. if (check_signature_token(cert->cache_info.identity_digest,
  2337. DIGEST_LEN,
  2338. tok,
  2339. cert->signing_key,
  2340. CST_NO_CHECK_OBJTYPE,
  2341. "key cross-certification")) {
  2342. goto err;
  2343. }
  2344. }
  2345. cert->cache_info.signed_descriptor_len = len;
  2346. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  2347. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  2348. cert->cache_info.signed_descriptor_body[len] = 0;
  2349. cert->cache_info.saved_location = SAVED_NOWHERE;
  2350. if (end_of_string) {
  2351. *end_of_string = eat_whitespace(eos);
  2352. }
  2353. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2354. smartlist_free(tokens);
  2355. if (area) {
  2356. DUMP_AREA(area, "authority cert");
  2357. memarea_drop_all(area);
  2358. }
  2359. return cert;
  2360. err:
  2361. dump_desc(s_dup, "authority cert");
  2362. authority_cert_free(cert);
  2363. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2364. smartlist_free(tokens);
  2365. if (area) {
  2366. DUMP_AREA(area, "authority cert");
  2367. memarea_drop_all(area);
  2368. }
  2369. return NULL;
  2370. }
  2371. /** Helper: given a string <b>s</b>, return the start of the next router-status
  2372. * object (starting with "r " at the start of a line). If none is found,
  2373. * return the start of the directory footer, or the next directory signature.
  2374. * If none is found, return the end of the string. */
  2375. static inline const char *
  2376. find_start_of_next_routerstatus(const char *s)
  2377. {
  2378. const char *eos, *footer, *sig;
  2379. if ((eos = strstr(s, "\nr ")))
  2380. ++eos;
  2381. else
  2382. eos = s + strlen(s);
  2383. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  2384. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  2385. if (footer && sig)
  2386. return MIN(footer, sig) + 1;
  2387. else if (footer)
  2388. return footer+1;
  2389. else if (sig)
  2390. return sig+1;
  2391. else
  2392. return eos;
  2393. }
  2394. /** Parse the GuardFraction string from a consensus or vote.
  2395. *
  2396. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  2397. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  2398. * the same semantic as in routerstatus_parse_entry_from_string(). */
  2399. STATIC int
  2400. routerstatus_parse_guardfraction(const char *guardfraction_str,
  2401. networkstatus_t *vote,
  2402. vote_routerstatus_t *vote_rs,
  2403. routerstatus_t *rs)
  2404. {
  2405. int ok;
  2406. const char *end_of_header = NULL;
  2407. int is_consensus = !vote_rs;
  2408. uint32_t guardfraction;
  2409. tor_assert(bool_eq(vote, vote_rs));
  2410. /* If this info comes from a consensus, but we should't apply
  2411. guardfraction, just exit. */
  2412. if (is_consensus && !should_apply_guardfraction(NULL)) {
  2413. return 0;
  2414. }
  2415. end_of_header = strchr(guardfraction_str, '=');
  2416. if (!end_of_header) {
  2417. return -1;
  2418. }
  2419. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  2420. 10, 0, 100, &ok, NULL);
  2421. if (!ok) {
  2422. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  2423. return -1;
  2424. }
  2425. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  2426. is_consensus ? "consensus" : "vote",
  2427. guardfraction_str, rs->nickname);
  2428. if (!is_consensus) { /* We are parsing a vote */
  2429. vote_rs->status.guardfraction_percentage = guardfraction;
  2430. vote_rs->status.has_guardfraction = 1;
  2431. } else {
  2432. /* We are parsing a consensus. Only apply guardfraction to guards. */
  2433. if (rs->is_possible_guard) {
  2434. rs->guardfraction_percentage = guardfraction;
  2435. rs->has_guardfraction = 1;
  2436. } else {
  2437. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  2438. "This is not supposed to happen. Not applying. ", rs->nickname);
  2439. }
  2440. }
  2441. return 0;
  2442. }
  2443. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  2444. * empty smartlist at <b>tokens</b>, parse and return the first router status
  2445. * object in the string, and advance *<b>s</b> to just after the end of the
  2446. * router status. Return NULL and advance *<b>s</b> on error.
  2447. *
  2448. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  2449. * routerstatus but use <b>vote_rs</b> instead.
  2450. *
  2451. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  2452. * consensus, and we should parse it according to the method used to
  2453. * make that consensus.
  2454. *
  2455. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  2456. **/
  2457. static routerstatus_t *
  2458. routerstatus_parse_entry_from_string(memarea_t *area,
  2459. const char **s, smartlist_t *tokens,
  2460. networkstatus_t *vote,
  2461. vote_routerstatus_t *vote_rs,
  2462. int consensus_method,
  2463. consensus_flavor_t flav)
  2464. {
  2465. const char *eos, *s_dup = *s;
  2466. routerstatus_t *rs = NULL;
  2467. directory_token_t *tok;
  2468. char timebuf[ISO_TIME_LEN+1];
  2469. struct in_addr in;
  2470. int offset = 0;
  2471. tor_assert(tokens);
  2472. tor_assert(bool_eq(vote, vote_rs));
  2473. if (!consensus_method)
  2474. flav = FLAV_NS;
  2475. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  2476. eos = find_start_of_next_routerstatus(*s);
  2477. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  2478. log_warn(LD_DIR, "Error tokenizing router status");
  2479. goto err;
  2480. }
  2481. if (smartlist_len(tokens) < 1) {
  2482. log_warn(LD_DIR, "Impossibly short router status");
  2483. goto err;
  2484. }
  2485. tok = find_by_keyword(tokens, K_R);
  2486. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  2487. if (flav == FLAV_NS) {
  2488. if (tok->n_args < 8) {
  2489. log_warn(LD_DIR, "Too few arguments to r");
  2490. goto err;
  2491. }
  2492. } else if (flav == FLAV_MICRODESC) {
  2493. offset = -1; /* There is no identity digest */
  2494. }
  2495. if (vote_rs) {
  2496. rs = &vote_rs->status;
  2497. } else {
  2498. rs = tor_malloc_zero(sizeof(routerstatus_t));
  2499. }
  2500. if (!is_legal_nickname(tok->args[0])) {
  2501. log_warn(LD_DIR,
  2502. "Invalid nickname %s in router status; skipping.",
  2503. escaped(tok->args[0]));
  2504. goto err;
  2505. }
  2506. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  2507. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  2508. log_warn(LD_DIR, "Error decoding identity digest %s",
  2509. escaped(tok->args[1]));
  2510. goto err;
  2511. }
  2512. if (flav == FLAV_NS) {
  2513. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  2514. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  2515. escaped(tok->args[2]));
  2516. goto err;
  2517. }
  2518. }
  2519. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  2520. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  2521. parse_iso_time(timebuf, &rs->published_on)<0) {
  2522. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  2523. tok->args[3+offset], tok->args[4+offset],
  2524. offset, (int)flav);
  2525. goto err;
  2526. }
  2527. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  2528. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  2529. escaped(tok->args[5+offset]));
  2530. goto err;
  2531. }
  2532. rs->addr = ntohl(in.s_addr);
  2533. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  2534. 10,0,65535,NULL,NULL);
  2535. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  2536. 10,0,65535,NULL,NULL);
  2537. {
  2538. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  2539. if (a_lines) {
  2540. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  2541. smartlist_free(a_lines);
  2542. }
  2543. }
  2544. tok = find_opt_by_keyword(tokens, K_S);
  2545. if (tok && vote) {
  2546. int i;
  2547. vote_rs->flags = 0;
  2548. for (i=0; i < tok->n_args; ++i) {
  2549. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  2550. if (p >= 0) {
  2551. vote_rs->flags |= (U64_LITERAL(1)<<p);
  2552. } else {
  2553. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  2554. escaped(tok->args[i]));
  2555. goto err;
  2556. }
  2557. }
  2558. } else if (tok) {
  2559. int i;
  2560. for (i=0; i < tok->n_args; ++i) {
  2561. if (!strcmp(tok->args[i], "Exit"))
  2562. rs->is_exit = 1;
  2563. else if (!strcmp(tok->args[i], "Stable"))
  2564. rs->is_stable = 1;
  2565. else if (!strcmp(tok->args[i], "Fast"))
  2566. rs->is_fast = 1;
  2567. else if (!strcmp(tok->args[i], "Running"))
  2568. rs->is_flagged_running = 1;
  2569. else if (!strcmp(tok->args[i], "Named"))
  2570. rs->is_named = 1;
  2571. else if (!strcmp(tok->args[i], "Valid"))
  2572. rs->is_valid = 1;
  2573. else if (!strcmp(tok->args[i], "Guard"))
  2574. rs->is_possible_guard = 1;
  2575. else if (!strcmp(tok->args[i], "BadExit"))
  2576. rs->is_bad_exit = 1;
  2577. else if (!strcmp(tok->args[i], "Authority"))
  2578. rs->is_authority = 1;
  2579. else if (!strcmp(tok->args[i], "Unnamed") &&
  2580. consensus_method >= 2) {
  2581. /* Unnamed is computed right by consensus method 2 and later. */
  2582. rs->is_unnamed = 1;
  2583. } else if (!strcmp(tok->args[i], "HSDir")) {
  2584. rs->is_hs_dir = 1;
  2585. } else if (!strcmp(tok->args[i], "V2Dir")) {
  2586. rs->is_v2_dir = 1;
  2587. }
  2588. }
  2589. }
  2590. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  2591. tor_assert(tok->n_args == 1);
  2592. rs->version_known = 1;
  2593. if (strcmpstart(tok->args[0], "Tor ")) {
  2594. } else {
  2595. rs->version_supports_extend2_cells =
  2596. tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
  2597. }
  2598. if (vote_rs) {
  2599. vote_rs->version = tor_strdup(tok->args[0]);
  2600. }
  2601. }
  2602. /* handle weighting/bandwidth info */
  2603. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  2604. int i;
  2605. for (i=0; i < tok->n_args; ++i) {
  2606. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  2607. int ok;
  2608. rs->bandwidth_kb =
  2609. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2610. 10, 0, UINT32_MAX,
  2611. &ok, NULL);
  2612. if (!ok) {
  2613. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  2614. goto err;
  2615. }
  2616. rs->has_bandwidth = 1;
  2617. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  2618. int ok;
  2619. vote_rs->measured_bw_kb =
  2620. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2621. 10, 0, UINT32_MAX, &ok, NULL);
  2622. if (!ok) {
  2623. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  2624. escaped(tok->args[i]));
  2625. goto err;
  2626. }
  2627. vote_rs->has_measured_bw = 1;
  2628. vote->has_measured_bws = 1;
  2629. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  2630. rs->bw_is_unmeasured = 1;
  2631. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  2632. if (routerstatus_parse_guardfraction(tok->args[i],
  2633. vote, vote_rs, rs) < 0) {
  2634. goto err;
  2635. }
  2636. }
  2637. }
  2638. }
  2639. /* parse exit policy summaries */
  2640. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  2641. tor_assert(tok->n_args == 1);
  2642. if (strcmpstart(tok->args[0], "accept ") &&
  2643. strcmpstart(tok->args[0], "reject ")) {
  2644. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  2645. escaped(tok->args[0]));
  2646. goto err;
  2647. }
  2648. /* XXX weasel: parse this into ports and represent them somehow smart,
  2649. * maybe not here but somewhere on if we need it for the client.
  2650. * we should still parse it here to check it's valid tho.
  2651. */
  2652. rs->exitsummary = tor_strdup(tok->args[0]);
  2653. rs->has_exitsummary = 1;
  2654. }
  2655. if (vote_rs) {
  2656. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2657. if (t->tp == K_M && t->n_args) {
  2658. vote_microdesc_hash_t *line =
  2659. tor_malloc(sizeof(vote_microdesc_hash_t));
  2660. line->next = vote_rs->microdesc;
  2661. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2662. vote_rs->microdesc = line;
  2663. }
  2664. if (t->tp == K_ID) {
  2665. tor_assert(t->n_args >= 2);
  2666. if (!strcmp(t->args[0], "ed25519")) {
  2667. vote_rs->has_ed25519_listing = 1;
  2668. if (strcmp(t->args[1], "none") &&
  2669. digest256_from_base64((char*)vote_rs->ed25519_id,
  2670. t->args[1])<0) {
  2671. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  2672. goto err;
  2673. }
  2674. }
  2675. }
  2676. } SMARTLIST_FOREACH_END(t);
  2677. } else if (flav == FLAV_MICRODESC) {
  2678. tok = find_opt_by_keyword(tokens, K_M);
  2679. if (tok) {
  2680. tor_assert(tok->n_args);
  2681. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2682. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2683. escaped(tok->args[0]));
  2684. goto err;
  2685. }
  2686. } else {
  2687. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2688. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  2689. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2690. fmt_addr32(rs->addr), rs->or_port);
  2691. }
  2692. }
  2693. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2694. rs->is_named = 0;
  2695. goto done;
  2696. err:
  2697. dump_desc(s_dup, "routerstatus entry");
  2698. if (rs && !vote_rs)
  2699. routerstatus_free(rs);
  2700. rs = NULL;
  2701. done:
  2702. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2703. smartlist_clear(tokens);
  2704. if (area) {
  2705. DUMP_AREA(area, "routerstatus entry");
  2706. memarea_clear(area);
  2707. }
  2708. *s = eos;
  2709. return rs;
  2710. }
  2711. int
  2712. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  2713. {
  2714. const vote_routerstatus_t *a = *_a, *b = *_b;
  2715. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  2716. DIGEST_LEN);
  2717. }
  2718. /** Verify the bandwidth weights of a network status document */
  2719. int
  2720. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  2721. {
  2722. int64_t weight_scale;
  2723. int64_t G=0, M=0, E=0, D=0, T=0;
  2724. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2725. double Gtotal=0, Mtotal=0, Etotal=0;
  2726. const char *casename = NULL;
  2727. int valid = 1;
  2728. (void) consensus_method;
  2729. weight_scale = networkstatus_get_weight_scale_param(ns);
  2730. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2731. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2732. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2733. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2734. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2735. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2736. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2737. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2738. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2739. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2740. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2741. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2742. || Wem<0 || Wee<0 || Wed<0) {
  2743. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2744. return 0;
  2745. }
  2746. // First, sanity check basic summing properties that hold for all cases
  2747. // We use > 1 as the check for these because they are computed as integers.
  2748. // Sometimes there are rounding errors.
  2749. if (fabs(Wmm - weight_scale) > 1) {
  2750. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2751. Wmm, I64_PRINTF_ARG(weight_scale));
  2752. valid = 0;
  2753. }
  2754. if (fabs(Wem - Wee) > 1) {
  2755. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2756. valid = 0;
  2757. }
  2758. if (fabs(Wgm - Wgg) > 1) {
  2759. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2760. valid = 0;
  2761. }
  2762. if (fabs(Weg - Wed) > 1) {
  2763. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2764. valid = 0;
  2765. }
  2766. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2767. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2768. I64_PRINTF_ARG(weight_scale), Wmg);
  2769. valid = 0;
  2770. }
  2771. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2772. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2773. I64_PRINTF_ARG(weight_scale), Wme);
  2774. valid = 0;
  2775. }
  2776. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2777. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2778. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2779. valid = 0;
  2780. }
  2781. Wgg /= weight_scale;
  2782. Wgm /= weight_scale;
  2783. Wgd /= weight_scale;
  2784. Wmg /= weight_scale;
  2785. Wmm /= weight_scale;
  2786. Wme /= weight_scale;
  2787. Wmd /= weight_scale;
  2788. Weg /= weight_scale;
  2789. Wem /= weight_scale;
  2790. Wee /= weight_scale;
  2791. Wed /= weight_scale;
  2792. // Then, gather G, M, E, D, T to determine case
  2793. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2794. int is_exit = 0;
  2795. /* Bug #2203: Don't count bad exits as exits for balancing */
  2796. is_exit = rs->is_exit && !rs->is_bad_exit;
  2797. if (rs->has_bandwidth) {
  2798. T += rs->bandwidth_kb;
  2799. if (is_exit && rs->is_possible_guard) {
  2800. D += rs->bandwidth_kb;
  2801. Gtotal += Wgd*rs->bandwidth_kb;
  2802. Mtotal += Wmd*rs->bandwidth_kb;
  2803. Etotal += Wed*rs->bandwidth_kb;
  2804. } else if (is_exit) {
  2805. E += rs->bandwidth_kb;
  2806. Mtotal += Wme*rs->bandwidth_kb;
  2807. Etotal += Wee*rs->bandwidth_kb;
  2808. } else if (rs->is_possible_guard) {
  2809. G += rs->bandwidth_kb;
  2810. Gtotal += Wgg*rs->bandwidth_kb;
  2811. Mtotal += Wmg*rs->bandwidth_kb;
  2812. } else {
  2813. M += rs->bandwidth_kb;
  2814. Mtotal += Wmm*rs->bandwidth_kb;
  2815. }
  2816. } else {
  2817. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2818. routerstatus_describe(rs));
  2819. }
  2820. } SMARTLIST_FOREACH_END(rs);
  2821. // Finally, check equality conditions depending upon case 1, 2 or 3
  2822. // Full equality cases: 1, 3b
  2823. // Partial equality cases: 2b (E=G), 3a (M=E)
  2824. // Fully unknown: 2a
  2825. if (3*E >= T && 3*G >= T) {
  2826. // Case 1: Neither are scarce
  2827. casename = "Case 1";
  2828. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2829. log_warn(LD_DIR,
  2830. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2831. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2832. " T="I64_FORMAT". "
  2833. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2834. casename, Etotal, Mtotal,
  2835. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2836. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2837. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2838. valid = 0;
  2839. }
  2840. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2841. log_warn(LD_DIR,
  2842. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2843. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2844. " T="I64_FORMAT". "
  2845. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2846. casename, Etotal, Gtotal,
  2847. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2848. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2849. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2850. valid = 0;
  2851. }
  2852. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2853. log_warn(LD_DIR,
  2854. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2855. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2856. " T="I64_FORMAT". "
  2857. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2858. casename, Mtotal, Gtotal,
  2859. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2860. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2861. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2862. valid = 0;
  2863. }
  2864. } else if (3*E < T && 3*G < T) {
  2865. int64_t R = MIN(E, G);
  2866. int64_t S = MAX(E, G);
  2867. /*
  2868. * Case 2: Both Guards and Exits are scarce
  2869. * Balance D between E and G, depending upon
  2870. * D capacity and scarcity. Devote no extra
  2871. * bandwidth to middle nodes.
  2872. */
  2873. if (R+D < S) { // Subcase a
  2874. double Rtotal, Stotal;
  2875. if (E < G) {
  2876. Rtotal = Etotal;
  2877. Stotal = Gtotal;
  2878. } else {
  2879. Rtotal = Gtotal;
  2880. Stotal = Etotal;
  2881. }
  2882. casename = "Case 2a";
  2883. // Rtotal < Stotal
  2884. if (Rtotal > Stotal) {
  2885. log_warn(LD_DIR,
  2886. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2887. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2888. " T="I64_FORMAT". "
  2889. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2890. casename, Rtotal, Stotal,
  2891. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2892. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2893. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2894. valid = 0;
  2895. }
  2896. // Rtotal < T/3
  2897. if (3*Rtotal > T) {
  2898. log_warn(LD_DIR,
  2899. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2900. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2901. " D="I64_FORMAT" T="I64_FORMAT". "
  2902. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2903. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2904. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2905. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2906. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2907. valid = 0;
  2908. }
  2909. // Stotal < T/3
  2910. if (3*Stotal > T) {
  2911. log_warn(LD_DIR,
  2912. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2913. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2914. " D="I64_FORMAT" T="I64_FORMAT". "
  2915. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2916. casename, Stotal*3, I64_PRINTF_ARG(T),
  2917. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2918. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2919. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2920. valid = 0;
  2921. }
  2922. // Mtotal > T/3
  2923. if (3*Mtotal < T) {
  2924. log_warn(LD_DIR,
  2925. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2926. I64_FORMAT". "
  2927. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2928. " T="I64_FORMAT". "
  2929. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2930. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2931. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2932. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2933. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2934. valid = 0;
  2935. }
  2936. } else { // Subcase b: R+D > S
  2937. casename = "Case 2b";
  2938. /* Check the rare-M redirect case. */
  2939. if (D != 0 && 3*M < T) {
  2940. casename = "Case 2b (balanced)";
  2941. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2942. log_warn(LD_DIR,
  2943. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2944. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2945. " T="I64_FORMAT". "
  2946. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2947. casename, Etotal, Mtotal,
  2948. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2949. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2950. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2951. valid = 0;
  2952. }
  2953. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2954. log_warn(LD_DIR,
  2955. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2956. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2957. " T="I64_FORMAT". "
  2958. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2959. casename, Etotal, Gtotal,
  2960. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2961. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2962. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2963. valid = 0;
  2964. }
  2965. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2966. log_warn(LD_DIR,
  2967. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2968. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2969. " T="I64_FORMAT". "
  2970. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2971. casename, Mtotal, Gtotal,
  2972. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2973. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2974. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2975. valid = 0;
  2976. }
  2977. } else {
  2978. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2979. log_warn(LD_DIR,
  2980. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2981. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2982. " T="I64_FORMAT". "
  2983. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2984. casename, Etotal, Gtotal,
  2985. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2986. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2987. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2988. valid = 0;
  2989. }
  2990. }
  2991. }
  2992. } else { // if (E < T/3 || G < T/3) {
  2993. int64_t S = MIN(E, G);
  2994. int64_t NS = MAX(E, G);
  2995. if (3*(S+D) < T) { // Subcase a:
  2996. double Stotal;
  2997. double NStotal;
  2998. if (G < E) {
  2999. casename = "Case 3a (G scarce)";
  3000. Stotal = Gtotal;
  3001. NStotal = Etotal;
  3002. } else { // if (G >= E) {
  3003. casename = "Case 3a (E scarce)";
  3004. NStotal = Gtotal;
  3005. Stotal = Etotal;
  3006. }
  3007. // Stotal < T/3
  3008. if (3*Stotal > T) {
  3009. log_warn(LD_DIR,
  3010. "Bw Weight Failure for %s: 3*Stotal %f > T "
  3011. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  3012. " D="I64_FORMAT" T="I64_FORMAT". "
  3013. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3014. casename, Stotal*3, I64_PRINTF_ARG(T),
  3015. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3016. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3017. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3018. valid = 0;
  3019. }
  3020. if (NS >= M) {
  3021. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  3022. log_warn(LD_DIR,
  3023. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  3024. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3025. " T="I64_FORMAT". "
  3026. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3027. casename, NStotal, Mtotal,
  3028. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3029. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3030. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3031. valid = 0;
  3032. }
  3033. } else {
  3034. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  3035. if (3*NStotal < T) {
  3036. log_warn(LD_DIR,
  3037. "Bw Weight Failure for %s: 3*NStotal %f < T "
  3038. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  3039. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  3040. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3041. casename, NStotal*3, I64_PRINTF_ARG(T),
  3042. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3043. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3044. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3045. valid = 0;
  3046. }
  3047. }
  3048. } else { // Subcase b: S+D >= T/3
  3049. casename = "Case 3b";
  3050. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  3051. log_warn(LD_DIR,
  3052. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  3053. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3054. " T="I64_FORMAT". "
  3055. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3056. casename, Etotal, Mtotal,
  3057. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3058. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3059. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3060. valid = 0;
  3061. }
  3062. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  3063. log_warn(LD_DIR,
  3064. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  3065. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3066. " T="I64_FORMAT". "
  3067. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3068. casename, Etotal, Gtotal,
  3069. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3070. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3071. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3072. valid = 0;
  3073. }
  3074. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  3075. log_warn(LD_DIR,
  3076. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  3077. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3078. " T="I64_FORMAT". "
  3079. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3080. casename, Mtotal, Gtotal,
  3081. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3082. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3083. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3084. valid = 0;
  3085. }
  3086. }
  3087. }
  3088. if (valid)
  3089. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  3090. casename);
  3091. return valid;
  3092. }
  3093. /** Parse and extract all SR commits from <b>tokens</b> and place them in
  3094. * <b>ns</b>. */
  3095. static void
  3096. extract_shared_random_commits(networkstatus_t *ns, smartlist_t *tokens)
  3097. {
  3098. smartlist_t *chunks = NULL;
  3099. tor_assert(ns);
  3100. tor_assert(tokens);
  3101. /* Commits are only present in a vote. */
  3102. tor_assert(ns->type == NS_TYPE_VOTE);
  3103. ns->sr_info.commits = smartlist_new();
  3104. smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
  3105. /* It's normal that a vote might contain no commits even if it participates
  3106. * in the SR protocol. Don't treat it as an error. */
  3107. if (commits == NULL) {
  3108. goto end;
  3109. }
  3110. /* Parse the commit. We do NO validation of number of arguments or ordering
  3111. * for forward compatibility, it's the parse commit job to inform us if it's
  3112. * supported or not. */
  3113. chunks = smartlist_new();
  3114. SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
  3115. /* Extract all arguments and put them in the chunks list. */
  3116. for (int i = 0; i < tok->n_args; i++) {
  3117. smartlist_add(chunks, tok->args[i]);
  3118. }
  3119. sr_commit_t *commit = sr_parse_commit(chunks);
  3120. smartlist_clear(chunks);
  3121. if (commit == NULL) {
  3122. /* Get voter identity so we can warn that this dirauth vote contains
  3123. * commit we can't parse. */
  3124. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  3125. tor_assert(voter);
  3126. log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
  3127. escaped(tok->object_body),
  3128. hex_str(voter->identity_digest,
  3129. sizeof(voter->identity_digest)));
  3130. /* Commitment couldn't be parsed. Continue onto the next commit because
  3131. * this one could be unsupported for instance. */
  3132. continue;
  3133. }
  3134. /* Add newly created commit object to the vote. */
  3135. smartlist_add(ns->sr_info.commits, commit);
  3136. } SMARTLIST_FOREACH_END(tok);
  3137. end:
  3138. smartlist_free(chunks);
  3139. smartlist_free(commits);
  3140. }
  3141. /** Check if a shared random value of type <b>srv_type</b> is in
  3142. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  3143. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  3144. * it's the responsibility of the caller to free it. */
  3145. static int
  3146. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  3147. sr_srv_t **srv_out)
  3148. {
  3149. int ret = -1;
  3150. directory_token_t *tok;
  3151. sr_srv_t *srv = NULL;
  3152. smartlist_t *chunks;
  3153. tor_assert(tokens);
  3154. chunks = smartlist_new();
  3155. tok = find_opt_by_keyword(tokens, srv_type);
  3156. if (!tok) {
  3157. /* That's fine, no SRV is allowed. */
  3158. ret = 0;
  3159. goto end;
  3160. }
  3161. for (int i = 0; i < tok->n_args; i++) {
  3162. smartlist_add(chunks, tok->args[i]);
  3163. }
  3164. srv = sr_parse_srv(chunks);
  3165. if (srv == NULL) {
  3166. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  3167. goto end;
  3168. }
  3169. /* All is good. */
  3170. *srv_out = srv;
  3171. ret = 0;
  3172. end:
  3173. smartlist_free(chunks);
  3174. return ret;
  3175. }
  3176. /** Extract any shared random values found in <b>tokens</b> and place them in
  3177. * the networkstatus <b>ns</b>. */
  3178. static void
  3179. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  3180. {
  3181. const char *voter_identity;
  3182. networkstatus_voter_info_t *voter;
  3183. tor_assert(ns);
  3184. tor_assert(tokens);
  3185. /* Can be only one of them else code flow. */
  3186. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  3187. if (ns->type == NS_TYPE_VOTE) {
  3188. voter = smartlist_get(ns->voters, 0);
  3189. tor_assert(voter);
  3190. voter_identity = hex_str(voter->identity_digest,
  3191. sizeof(voter->identity_digest));
  3192. } else {
  3193. /* Consensus has multiple voters so no specific voter. */
  3194. voter_identity = "consensus";
  3195. }
  3196. /* We extract both and on error, everything is stopped because it means
  3197. * the votes is malformed for the shared random value(s). */
  3198. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  3199. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  3200. voter_identity);
  3201. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  3202. }
  3203. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  3204. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  3205. voter_identity);
  3206. }
  3207. }
  3208. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  3209. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  3210. networkstatus_t *
  3211. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  3212. networkstatus_type_t ns_type)
  3213. {
  3214. smartlist_t *tokens = smartlist_new();
  3215. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  3216. networkstatus_voter_info_t *voter = NULL;
  3217. networkstatus_t *ns = NULL;
  3218. common_digests_t ns_digests;
  3219. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  3220. directory_token_t *tok;
  3221. struct in_addr in;
  3222. int i, inorder, n_signatures = 0;
  3223. memarea_t *area = NULL, *rs_area = NULL;
  3224. consensus_flavor_t flav = FLAV_NS;
  3225. char *last_kwd=NULL;
  3226. tor_assert(s);
  3227. if (eos_out)
  3228. *eos_out = NULL;
  3229. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  3230. log_warn(LD_DIR, "Unable to compute digest of network-status");
  3231. goto err;
  3232. }
  3233. area = memarea_new();
  3234. end_of_header = find_start_of_next_routerstatus(s);
  3235. if (tokenize_string(area, s, end_of_header, tokens,
  3236. (ns_type == NS_TYPE_CONSENSUS) ?
  3237. networkstatus_consensus_token_table :
  3238. networkstatus_token_table, 0)) {
  3239. log_warn(LD_DIR, "Error tokenizing network-status header");
  3240. goto err;
  3241. }
  3242. ns = tor_malloc_zero(sizeof(networkstatus_t));
  3243. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  3244. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  3245. tor_assert(tok);
  3246. if (tok->n_args > 1) {
  3247. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  3248. if (flavor < 0) {
  3249. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  3250. escaped(tok->args[1]));
  3251. goto err;
  3252. }
  3253. ns->flavor = flav = flavor;
  3254. }
  3255. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  3256. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  3257. goto err;
  3258. }
  3259. if (ns_type != NS_TYPE_CONSENSUS) {
  3260. const char *end_of_cert = NULL;
  3261. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  3262. goto err;
  3263. ++cert;
  3264. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  3265. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  3266. goto err;
  3267. }
  3268. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  3269. tor_assert(tok->n_args);
  3270. if (!strcmp(tok->args[0], "vote")) {
  3271. ns->type = NS_TYPE_VOTE;
  3272. } else if (!strcmp(tok->args[0], "consensus")) {
  3273. ns->type = NS_TYPE_CONSENSUS;
  3274. } else if (!strcmp(tok->args[0], "opinion")) {
  3275. ns->type = NS_TYPE_OPINION;
  3276. } else {
  3277. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  3278. escaped(tok->args[0]));
  3279. goto err;
  3280. }
  3281. if (ns_type != ns->type) {
  3282. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  3283. goto err;
  3284. }
  3285. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  3286. tok = find_by_keyword(tokens, K_PUBLISHED);
  3287. if (parse_iso_time(tok->args[0], &ns->published))
  3288. goto err;
  3289. ns->supported_methods = smartlist_new();
  3290. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  3291. if (tok) {
  3292. for (i=0; i < tok->n_args; ++i)
  3293. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  3294. } else {
  3295. smartlist_add(ns->supported_methods, tor_strdup("1"));
  3296. }
  3297. } else {
  3298. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  3299. if (tok) {
  3300. int num_ok;
  3301. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  3302. &num_ok, NULL);
  3303. if (!num_ok)
  3304. goto err;
  3305. } else {
  3306. ns->consensus_method = 1;
  3307. }
  3308. }
  3309. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3310. if (parse_iso_time(tok->args[0], &ns->valid_after))
  3311. goto err;
  3312. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3313. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  3314. goto err;
  3315. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3316. if (parse_iso_time(tok->args[0], &ns->valid_until))
  3317. goto err;
  3318. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  3319. tor_assert(tok->n_args >= 2);
  3320. {
  3321. int ok;
  3322. ns->vote_seconds =
  3323. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  3324. if (!ok)
  3325. goto err;
  3326. ns->dist_seconds =
  3327. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  3328. if (!ok)
  3329. goto err;
  3330. }
  3331. if (ns->valid_after +
  3332. (get_options()->TestingTorNetwork ?
  3333. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  3334. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  3335. goto err;
  3336. }
  3337. if (ns->valid_after +
  3338. (get_options()->TestingTorNetwork ?
  3339. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  3340. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  3341. goto err;
  3342. }
  3343. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  3344. log_warn(LD_DIR, "Vote seconds is too short");
  3345. goto err;
  3346. }
  3347. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  3348. log_warn(LD_DIR, "Dist seconds is too short");
  3349. goto err;
  3350. }
  3351. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  3352. ns->client_versions = tor_strdup(tok->args[0]);
  3353. }
  3354. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  3355. ns->server_versions = tor_strdup(tok->args[0]);
  3356. }
  3357. {
  3358. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  3359. ns->package_lines = smartlist_new();
  3360. if (package_lst) {
  3361. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  3362. smartlist_add(ns->package_lines, tor_strdup(t->args[0])));
  3363. }
  3364. smartlist_free(package_lst);
  3365. }
  3366. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  3367. ns->known_flags = smartlist_new();
  3368. inorder = 1;
  3369. for (i = 0; i < tok->n_args; ++i) {
  3370. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  3371. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  3372. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3373. inorder = 0;
  3374. }
  3375. }
  3376. if (!inorder) {
  3377. log_warn(LD_DIR, "known-flags not in order");
  3378. goto err;
  3379. }
  3380. if (ns->type != NS_TYPE_CONSENSUS &&
  3381. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  3382. /* If we allowed more than 64 flags in votes, then parsing them would make
  3383. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  3384. * bit-shift. This is only for votes and opinions: consensus users don't
  3385. * care about flags they don't recognize, and so don't build a bitfield
  3386. * for them. */
  3387. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  3388. goto err;
  3389. }
  3390. tok = find_opt_by_keyword(tokens, K_PARAMS);
  3391. if (tok) {
  3392. int any_dups = 0;
  3393. inorder = 1;
  3394. ns->net_params = smartlist_new();
  3395. for (i = 0; i < tok->n_args; ++i) {
  3396. int ok=0;
  3397. char *eq = strchr(tok->args[i], '=');
  3398. size_t eq_pos;
  3399. if (!eq) {
  3400. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3401. goto err;
  3402. }
  3403. eq_pos = eq-tok->args[i];
  3404. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3405. if (!ok) {
  3406. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3407. goto err;
  3408. }
  3409. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  3410. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3411. inorder = 0;
  3412. }
  3413. if (last_kwd && eq_pos == strlen(last_kwd) &&
  3414. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  3415. log_warn(LD_DIR, "Duplicate value for %s parameter",
  3416. escaped(tok->args[i]));
  3417. any_dups = 1;
  3418. }
  3419. tor_free(last_kwd);
  3420. last_kwd = tor_strndup(tok->args[i], eq_pos);
  3421. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  3422. }
  3423. if (!inorder) {
  3424. log_warn(LD_DIR, "params not in order");
  3425. goto err;
  3426. }
  3427. if (any_dups) {
  3428. log_warn(LD_DIR, "Duplicate in parameters");
  3429. goto err;
  3430. }
  3431. }
  3432. ns->voters = smartlist_new();
  3433. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3434. tok = _tok;
  3435. if (tok->tp == K_DIR_SOURCE) {
  3436. tor_assert(tok->n_args >= 6);
  3437. if (voter)
  3438. smartlist_add(ns->voters, voter);
  3439. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  3440. voter->sigs = smartlist_new();
  3441. if (ns->type != NS_TYPE_CONSENSUS)
  3442. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  3443. voter->nickname = tor_strdup(tok->args[0]);
  3444. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  3445. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  3446. tok->args[1], HEX_DIGEST_LEN)
  3447. != sizeof(voter->identity_digest)) {
  3448. log_warn(LD_DIR, "Error decoding identity digest %s in "
  3449. "network-status document.", escaped(tok->args[1]));
  3450. goto err;
  3451. }
  3452. if (ns->type != NS_TYPE_CONSENSUS &&
  3453. tor_memneq(ns->cert->cache_info.identity_digest,
  3454. voter->identity_digest, DIGEST_LEN)) {
  3455. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  3456. goto err;
  3457. }
  3458. if (ns->type != NS_TYPE_CONSENSUS) {
  3459. if (authority_cert_is_blacklisted(ns->cert)) {
  3460. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  3461. "signing key %s",
  3462. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  3463. goto err;
  3464. }
  3465. }
  3466. voter->address = tor_strdup(tok->args[2]);
  3467. if (!tor_inet_aton(tok->args[3], &in)) {
  3468. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  3469. escaped(tok->args[3]));
  3470. goto err;
  3471. }
  3472. voter->addr = ntohl(in.s_addr);
  3473. int ok;
  3474. voter->dir_port = (uint16_t)
  3475. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  3476. if (!ok)
  3477. goto err;
  3478. voter->or_port = (uint16_t)
  3479. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  3480. if (!ok)
  3481. goto err;
  3482. } else if (tok->tp == K_CONTACT) {
  3483. if (!voter || voter->contact) {
  3484. log_warn(LD_DIR, "contact element is out of place.");
  3485. goto err;
  3486. }
  3487. voter->contact = tor_strdup(tok->args[0]);
  3488. } else if (tok->tp == K_VOTE_DIGEST) {
  3489. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  3490. tor_assert(tok->n_args >= 1);
  3491. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  3492. log_warn(LD_DIR, "vote-digest element is out of place.");
  3493. goto err;
  3494. }
  3495. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  3496. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  3497. tok->args[0], HEX_DIGEST_LEN)
  3498. != sizeof(voter->vote_digest)) {
  3499. log_warn(LD_DIR, "Error decoding vote digest %s in "
  3500. "network-status consensus.", escaped(tok->args[0]));
  3501. goto err;
  3502. }
  3503. }
  3504. } SMARTLIST_FOREACH_END(_tok);
  3505. if (voter) {
  3506. smartlist_add(ns->voters, voter);
  3507. voter = NULL;
  3508. }
  3509. if (smartlist_len(ns->voters) == 0) {
  3510. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  3511. goto err;
  3512. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  3513. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  3514. goto err;
  3515. }
  3516. if (ns->type != NS_TYPE_CONSENSUS &&
  3517. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  3518. int bad = 1;
  3519. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  3520. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  3521. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  3522. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  3523. bad = 1;
  3524. else
  3525. bad = 0;
  3526. }
  3527. if (bad) {
  3528. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  3529. escaped(tok->args[0]));
  3530. }
  3531. }
  3532. /* If this is a vote document, check if information about the shared
  3533. randomness protocol is included, and extract it. */
  3534. if (ns->type == NS_TYPE_VOTE) {
  3535. /* Does this authority participates in the SR protocol? */
  3536. tok = find_opt_by_keyword(tokens, K_SR_FLAG);
  3537. if (tok) {
  3538. ns->sr_info.participate = 1;
  3539. /* Get the SR commitments and reveals from the vote. */
  3540. extract_shared_random_commits(ns, tokens);
  3541. }
  3542. }
  3543. /* For both a vote and consensus, extract the shared random values. */
  3544. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  3545. extract_shared_random_srvs(ns, tokens);
  3546. }
  3547. /* Parse routerstatus lines. */
  3548. rs_tokens = smartlist_new();
  3549. rs_area = memarea_new();
  3550. s = end_of_header;
  3551. ns->routerstatus_list = smartlist_new();
  3552. while (!strcmpstart(s, "r ")) {
  3553. if (ns->type != NS_TYPE_CONSENSUS) {
  3554. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3555. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  3556. rs, 0, 0))
  3557. smartlist_add(ns->routerstatus_list, rs);
  3558. else {
  3559. tor_free(rs->version);
  3560. tor_free(rs);
  3561. }
  3562. } else {
  3563. routerstatus_t *rs;
  3564. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  3565. NULL, NULL,
  3566. ns->consensus_method,
  3567. flav))) {
  3568. /* Use exponential-backoff scheduling when downloading microdescs */
  3569. rs->dl_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
  3570. smartlist_add(ns->routerstatus_list, rs);
  3571. }
  3572. }
  3573. }
  3574. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  3575. routerstatus_t *rs1, *rs2;
  3576. if (ns->type != NS_TYPE_CONSENSUS) {
  3577. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  3578. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  3579. rs1 = &a->status; rs2 = &b->status;
  3580. } else {
  3581. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  3582. rs2 = smartlist_get(ns->routerstatus_list, i);
  3583. }
  3584. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  3585. >= 0) {
  3586. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  3587. goto err;
  3588. }
  3589. }
  3590. if (ns_type != NS_TYPE_CONSENSUS) {
  3591. digest256map_t *ed_id_map = digest256map_new();
  3592. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  3593. vrs) {
  3594. if (! vrs->has_ed25519_listing ||
  3595. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  3596. continue;
  3597. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  3598. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  3599. "unique");
  3600. digest256map_free(ed_id_map, NULL);
  3601. goto err;
  3602. }
  3603. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  3604. } SMARTLIST_FOREACH_END(vrs);
  3605. digest256map_free(ed_id_map, NULL);
  3606. }
  3607. /* Parse footer; check signature. */
  3608. footer_tokens = smartlist_new();
  3609. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  3610. ++end_of_footer;
  3611. else
  3612. end_of_footer = s + strlen(s);
  3613. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  3614. networkstatus_vote_footer_token_table, 0)) {
  3615. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  3616. goto err;
  3617. }
  3618. {
  3619. int found_sig = 0;
  3620. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3621. tok = _tok;
  3622. if (tok->tp == K_DIRECTORY_SIGNATURE)
  3623. found_sig = 1;
  3624. else if (found_sig) {
  3625. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  3626. goto err;
  3627. }
  3628. } SMARTLIST_FOREACH_END(_tok);
  3629. }
  3630. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  3631. if (tok != smartlist_get(footer_tokens, 0)) {
  3632. log_warn(LD_DIR, "Misplaced directory-footer token");
  3633. goto err;
  3634. }
  3635. }
  3636. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  3637. if (tok) {
  3638. ns->weight_params = smartlist_new();
  3639. for (i = 0; i < tok->n_args; ++i) {
  3640. int ok=0;
  3641. char *eq = strchr(tok->args[i], '=');
  3642. if (!eq) {
  3643. log_warn(LD_DIR, "Bad element '%s' in weight params",
  3644. escaped(tok->args[i]));
  3645. goto err;
  3646. }
  3647. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3648. if (!ok) {
  3649. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3650. goto err;
  3651. }
  3652. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  3653. }
  3654. }
  3655. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3656. char declared_identity[DIGEST_LEN];
  3657. networkstatus_voter_info_t *v;
  3658. document_signature_t *sig;
  3659. const char *id_hexdigest = NULL;
  3660. const char *sk_hexdigest = NULL;
  3661. digest_algorithm_t alg = DIGEST_SHA1;
  3662. tok = _tok;
  3663. if (tok->tp != K_DIRECTORY_SIGNATURE)
  3664. continue;
  3665. tor_assert(tok->n_args >= 2);
  3666. if (tok->n_args == 2) {
  3667. id_hexdigest = tok->args[0];
  3668. sk_hexdigest = tok->args[1];
  3669. } else {
  3670. const char *algname = tok->args[0];
  3671. int a;
  3672. id_hexdigest = tok->args[1];
  3673. sk_hexdigest = tok->args[2];
  3674. a = crypto_digest_algorithm_parse_name(algname);
  3675. if (a<0) {
  3676. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  3677. escaped(algname));
  3678. continue;
  3679. }
  3680. alg = a;
  3681. }
  3682. if (!tok->object_type ||
  3683. strcmp(tok->object_type, "SIGNATURE") ||
  3684. tok->object_size < 128 || tok->object_size > 512) {
  3685. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3686. goto err;
  3687. }
  3688. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3689. base16_decode(declared_identity, sizeof(declared_identity),
  3690. id_hexdigest, HEX_DIGEST_LEN)
  3691. != sizeof(declared_identity)) {
  3692. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3693. "network-status document.", escaped(id_hexdigest));
  3694. goto err;
  3695. }
  3696. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3697. log_warn(LD_DIR, "ID on signature on network-status document does "
  3698. "not match any declared directory source.");
  3699. goto err;
  3700. }
  3701. sig = tor_malloc_zero(sizeof(document_signature_t));
  3702. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3703. sig->alg = alg;
  3704. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3705. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3706. sk_hexdigest, HEX_DIGEST_LEN)
  3707. != sizeof(sig->signing_key_digest)) {
  3708. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3709. "network-status document.", escaped(sk_hexdigest));
  3710. tor_free(sig);
  3711. goto err;
  3712. }
  3713. if (ns->type != NS_TYPE_CONSENSUS) {
  3714. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3715. DIGEST_LEN)) {
  3716. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3717. "network-status vote.");
  3718. tor_free(sig);
  3719. goto err;
  3720. }
  3721. }
  3722. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3723. /* We already parsed a vote with this algorithm from this voter. Use the
  3724. first one. */
  3725. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3726. "that contains two signatures from the same voter with the same "
  3727. "algorithm. Ignoring the second signature.");
  3728. tor_free(sig);
  3729. continue;
  3730. }
  3731. if (ns->type != NS_TYPE_CONSENSUS) {
  3732. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3733. tok, ns->cert->signing_key, 0,
  3734. "network-status document")) {
  3735. tor_free(sig);
  3736. goto err;
  3737. }
  3738. sig->good_signature = 1;
  3739. } else {
  3740. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3741. tor_free(sig);
  3742. goto err;
  3743. }
  3744. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3745. sig->signature_len = (int) tok->object_size;
  3746. }
  3747. smartlist_add(v->sigs, sig);
  3748. ++n_signatures;
  3749. } SMARTLIST_FOREACH_END(_tok);
  3750. if (! n_signatures) {
  3751. log_warn(LD_DIR, "No signatures on networkstatus document.");
  3752. goto err;
  3753. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3754. log_warn(LD_DIR, "Received more than one signature on a "
  3755. "network-status vote.");
  3756. goto err;
  3757. }
  3758. if (eos_out)
  3759. *eos_out = end_of_footer;
  3760. goto done;
  3761. err:
  3762. dump_desc(s_dup, "v3 networkstatus");
  3763. networkstatus_vote_free(ns);
  3764. ns = NULL;
  3765. done:
  3766. if (tokens) {
  3767. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3768. smartlist_free(tokens);
  3769. }
  3770. if (voter) {
  3771. if (voter->sigs) {
  3772. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3773. document_signature_free(sig));
  3774. smartlist_free(voter->sigs);
  3775. }
  3776. tor_free(voter->nickname);
  3777. tor_free(voter->address);
  3778. tor_free(voter->contact);
  3779. tor_free(voter);
  3780. }
  3781. if (rs_tokens) {
  3782. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3783. smartlist_free(rs_tokens);
  3784. }
  3785. if (footer_tokens) {
  3786. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3787. smartlist_free(footer_tokens);
  3788. }
  3789. if (area) {
  3790. DUMP_AREA(area, "v3 networkstatus");
  3791. memarea_drop_all(area);
  3792. }
  3793. if (rs_area)
  3794. memarea_drop_all(rs_area);
  3795. tor_free(last_kwd);
  3796. return ns;
  3797. }
  3798. /** Return the common_digests_t that holds the digests of the
  3799. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3800. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  3801. * neeeded. */
  3802. static common_digests_t *
  3803. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3804. {
  3805. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  3806. if (!d) {
  3807. d = tor_malloc_zero(sizeof(common_digests_t));
  3808. strmap_set(sigs->digests, flavor_name, d);
  3809. }
  3810. return d;
  3811. }
  3812. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3813. * networkstatus according to the detached signatures document <b>sigs</b>,
  3814. * allocating a new common_digests_t as neeeded. */
  3815. static smartlist_t *
  3816. detached_get_signatures(ns_detached_signatures_t *sigs,
  3817. const char *flavor_name)
  3818. {
  3819. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3820. if (!sl) {
  3821. sl = smartlist_new();
  3822. strmap_set(sigs->signatures, flavor_name, sl);
  3823. }
  3824. return sl;
  3825. }
  3826. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3827. * <b>eos</b> and return the result. Return -1 on failure. */
  3828. ns_detached_signatures_t *
  3829. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3830. {
  3831. /* XXXX there is too much duplicate shared between this function and
  3832. * networkstatus_parse_vote_from_string(). */
  3833. directory_token_t *tok;
  3834. memarea_t *area = NULL;
  3835. common_digests_t *digests;
  3836. smartlist_t *tokens = smartlist_new();
  3837. ns_detached_signatures_t *sigs =
  3838. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3839. sigs->digests = strmap_new();
  3840. sigs->signatures = strmap_new();
  3841. if (!eos)
  3842. eos = s + strlen(s);
  3843. area = memarea_new();
  3844. if (tokenize_string(area,s, eos, tokens,
  3845. networkstatus_detached_signature_token_table, 0)) {
  3846. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3847. goto err;
  3848. }
  3849. /* Grab all the digest-like tokens. */
  3850. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3851. const char *algname;
  3852. digest_algorithm_t alg;
  3853. const char *flavor;
  3854. const char *hexdigest;
  3855. size_t expected_length, digest_length;
  3856. tok = _tok;
  3857. if (tok->tp == K_CONSENSUS_DIGEST) {
  3858. algname = "sha1";
  3859. alg = DIGEST_SHA1;
  3860. flavor = "ns";
  3861. hexdigest = tok->args[0];
  3862. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3863. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3864. if (a<0) {
  3865. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3866. continue;
  3867. }
  3868. alg = (digest_algorithm_t) a;
  3869. flavor = tok->args[0];
  3870. algname = tok->args[1];
  3871. hexdigest = tok->args[2];
  3872. } else {
  3873. continue;
  3874. }
  3875. digest_length = crypto_digest_algorithm_get_length(alg);
  3876. expected_length = digest_length * 2; /* hex encoding */
  3877. if (strlen(hexdigest) != expected_length) {
  3878. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3879. "networkstatus signatures");
  3880. goto err;
  3881. }
  3882. digests = detached_get_digests(sigs, flavor);
  3883. tor_assert(digests);
  3884. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  3885. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3886. "signatures document", flavor, algname);
  3887. continue;
  3888. }
  3889. if (base16_decode(digests->d[alg], digest_length,
  3890. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  3891. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3892. "networkstatus signatures");
  3893. goto err;
  3894. }
  3895. } SMARTLIST_FOREACH_END(_tok);
  3896. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3897. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3898. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3899. goto err;
  3900. }
  3901. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3902. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3903. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3904. goto err;
  3905. }
  3906. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3907. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3908. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3909. goto err;
  3910. }
  3911. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3912. const char *id_hexdigest;
  3913. const char *sk_hexdigest;
  3914. const char *algname;
  3915. const char *flavor;
  3916. digest_algorithm_t alg;
  3917. char id_digest[DIGEST_LEN];
  3918. char sk_digest[DIGEST_LEN];
  3919. smartlist_t *siglist;
  3920. document_signature_t *sig;
  3921. int is_duplicate;
  3922. tok = _tok;
  3923. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3924. tor_assert(tok->n_args >= 2);
  3925. flavor = "ns";
  3926. algname = "sha1";
  3927. id_hexdigest = tok->args[0];
  3928. sk_hexdigest = tok->args[1];
  3929. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3930. tor_assert(tok->n_args >= 4);
  3931. flavor = tok->args[0];
  3932. algname = tok->args[1];
  3933. id_hexdigest = tok->args[2];
  3934. sk_hexdigest = tok->args[3];
  3935. } else {
  3936. continue;
  3937. }
  3938. {
  3939. int a = crypto_digest_algorithm_parse_name(algname);
  3940. if (a<0) {
  3941. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3942. continue;
  3943. }
  3944. alg = (digest_algorithm_t) a;
  3945. }
  3946. if (!tok->object_type ||
  3947. strcmp(tok->object_type, "SIGNATURE") ||
  3948. tok->object_size < 128 || tok->object_size > 512) {
  3949. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3950. goto err;
  3951. }
  3952. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3953. base16_decode(id_digest, sizeof(id_digest),
  3954. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  3955. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3956. "network-status vote.", escaped(id_hexdigest));
  3957. goto err;
  3958. }
  3959. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3960. base16_decode(sk_digest, sizeof(sk_digest),
  3961. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  3962. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3963. "network-status vote.", escaped(sk_hexdigest));
  3964. goto err;
  3965. }
  3966. siglist = detached_get_signatures(sigs, flavor);
  3967. is_duplicate = 0;
  3968. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3969. if (dsig->alg == alg &&
  3970. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3971. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3972. is_duplicate = 1;
  3973. }
  3974. });
  3975. if (is_duplicate) {
  3976. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3977. "found.");
  3978. continue;
  3979. }
  3980. sig = tor_malloc_zero(sizeof(document_signature_t));
  3981. sig->alg = alg;
  3982. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3983. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3984. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3985. tor_free(sig);
  3986. goto err;
  3987. }
  3988. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3989. sig->signature_len = (int) tok->object_size;
  3990. smartlist_add(siglist, sig);
  3991. } SMARTLIST_FOREACH_END(_tok);
  3992. goto done;
  3993. err:
  3994. ns_detached_signatures_free(sigs);
  3995. sigs = NULL;
  3996. done:
  3997. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3998. smartlist_free(tokens);
  3999. if (area) {
  4000. DUMP_AREA(area, "detached signatures");
  4001. memarea_drop_all(area);
  4002. }
  4003. return sigs;
  4004. }
  4005. /** Parse the addr policy in the string <b>s</b> and return it. If
  4006. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  4007. * ADDR_POLICY_REJECT) for items that specify no action.
  4008. *
  4009. * Returns NULL on policy errors.
  4010. *
  4011. * Set *<b>malformed_list</b> to true if the entire policy list should be
  4012. * discarded. Otherwise, set it to false, and only this item should be ignored
  4013. * on error - the rest of the policy list can continue to be processed and
  4014. * used.
  4015. *
  4016. * The addr_policy_t returned by this function can have its address set to
  4017. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  4018. * of AF_INET and AF_INET6 items.
  4019. */
  4020. MOCK_IMPL(addr_policy_t *,
  4021. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  4022. int *malformed_list))
  4023. {
  4024. directory_token_t *tok = NULL;
  4025. const char *cp, *eos;
  4026. /* Longest possible policy is
  4027. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  4028. * which contains a max-length IPv6 address, plus 26 characters.
  4029. * But note that there can be an arbitrary amount of space between the
  4030. * accept and the address:mask/port element.
  4031. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  4032. * IPv6 address. But making the buffer shorter might cause valid long lines,
  4033. * which parsed in previous versions, to fail to parse in new versions.
  4034. * (These lines would have to have excessive amounts of whitespace.) */
  4035. char line[TOR_ADDR_BUF_LEN*2 + 32];
  4036. addr_policy_t *r;
  4037. memarea_t *area = NULL;
  4038. tor_assert(malformed_list);
  4039. *malformed_list = 0;
  4040. s = eat_whitespace(s);
  4041. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  4042. * and ":" (port separator) are ambiguous */
  4043. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  4044. if (tor_snprintf(line, sizeof(line), "%s %s",
  4045. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  4046. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  4047. return NULL;
  4048. }
  4049. cp = line;
  4050. tor_strlower(line);
  4051. } else { /* assume an already well-formed address policy line */
  4052. cp = s;
  4053. }
  4054. eos = cp + strlen(cp);
  4055. area = memarea_new();
  4056. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  4057. if (tok->tp == ERR_) {
  4058. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  4059. goto err;
  4060. }
  4061. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  4062. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  4063. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  4064. goto err;
  4065. }
  4066. /* Use the extended interpretation of accept/reject *,
  4067. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  4068. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  4069. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  4070. if (!r) {
  4071. goto err;
  4072. }
  4073. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  4074. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  4075. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  4076. * either an IPv4 or IPv6 address. */
  4077. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4078. tor_addr_family(&r->addr) != AF_INET6) {
  4079. /* This is a non-fatal error, just ignore this one entry. */
  4080. *malformed_list = 0;
  4081. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  4082. "exit policy. Ignoring, but continuing to parse rules. (Use "
  4083. "accept/reject with IPv4 addresses.)",
  4084. tok->n_args == 1 ? tok->args[0] : "");
  4085. addr_policy_free(r);
  4086. r = NULL;
  4087. goto done;
  4088. }
  4089. goto done;
  4090. err:
  4091. *malformed_list = 1;
  4092. r = NULL;
  4093. done:
  4094. token_clear(tok);
  4095. if (area) {
  4096. DUMP_AREA(area, "policy item");
  4097. memarea_drop_all(area);
  4098. }
  4099. return r;
  4100. }
  4101. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  4102. * <b>router</b>. Return 0 on success, -1 on failure. */
  4103. static int
  4104. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  4105. {
  4106. addr_policy_t *newe;
  4107. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  4108. newe = router_parse_addr_policy(tok, 0);
  4109. if (!newe)
  4110. return -1;
  4111. if (! router->exit_policy)
  4112. router->exit_policy = smartlist_new();
  4113. /* Ensure that in descriptors, accept/reject fields are followed by
  4114. * IPv4 addresses, and accept6/reject6 fields are followed by
  4115. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  4116. * accept/reject followed by IPv6. */
  4117. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4118. tor_addr_family(&newe->addr) == AF_INET)
  4119. ||
  4120. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  4121. tor_addr_family(&newe->addr) == AF_INET6)) {
  4122. /* There's nothing the user can do about other relays' descriptors,
  4123. * so we don't provide usage advice here. */
  4124. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  4125. "policy '%s'. Discarding entire router descriptor.",
  4126. tok->n_args == 1 ? tok->args[0] : "");
  4127. addr_policy_free(newe);
  4128. return -1;
  4129. }
  4130. smartlist_add(router->exit_policy, newe);
  4131. return 0;
  4132. }
  4133. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  4134. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  4135. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  4136. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  4137. * policies */
  4138. static addr_policy_t *
  4139. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  4140. {
  4141. addr_policy_t newe;
  4142. char *arg;
  4143. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  4144. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  4145. if (tok->n_args != 1)
  4146. return NULL;
  4147. arg = tok->args[0];
  4148. if (!strcmpstart(arg,"private"))
  4149. return router_parse_addr_policy_private(tok);
  4150. memset(&newe, 0, sizeof(newe));
  4151. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4152. newe.policy_type = ADDR_POLICY_REJECT;
  4153. else
  4154. newe.policy_type = ADDR_POLICY_ACCEPT;
  4155. /* accept6/reject6 * produces an IPv6 wildcard address only.
  4156. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  4157. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  4158. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  4159. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  4160. }
  4161. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  4162. &newe.prt_min, &newe.prt_max) < 0) {
  4163. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  4164. return NULL;
  4165. }
  4166. return addr_policy_get_canonical_entry(&newe);
  4167. }
  4168. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  4169. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  4170. * router descriptors until earlier versions are obsolete.
  4171. *
  4172. * accept/reject and accept6/reject6 private all produce rules for both
  4173. * IPv4 and IPv6 addresses.
  4174. */
  4175. static addr_policy_t *
  4176. router_parse_addr_policy_private(directory_token_t *tok)
  4177. {
  4178. const char *arg;
  4179. uint16_t port_min, port_max;
  4180. addr_policy_t result;
  4181. arg = tok->args[0];
  4182. if (strcmpstart(arg, "private"))
  4183. return NULL;
  4184. arg += strlen("private");
  4185. arg = (char*) eat_whitespace(arg);
  4186. if (!arg || *arg != ':')
  4187. return NULL;
  4188. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  4189. return NULL;
  4190. memset(&result, 0, sizeof(result));
  4191. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4192. result.policy_type = ADDR_POLICY_REJECT;
  4193. else
  4194. result.policy_type = ADDR_POLICY_ACCEPT;
  4195. result.is_private = 1;
  4196. result.prt_min = port_min;
  4197. result.prt_max = port_max;
  4198. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  4199. log_warn(LD_GENERAL,
  4200. "'%s' expands into rules which apply to all private IPv4 and "
  4201. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  4202. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  4203. }
  4204. return addr_policy_get_canonical_entry(&result);
  4205. }
  4206. /** Log and exit if <b>t</b> is malformed */
  4207. void
  4208. assert_addr_policy_ok(smartlist_t *lst)
  4209. {
  4210. if (!lst) return;
  4211. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  4212. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  4213. t->policy_type == ADDR_POLICY_ACCEPT);
  4214. tor_assert(t->prt_min <= t->prt_max);
  4215. });
  4216. }
  4217. /*
  4218. * Low-level tokenizer for router descriptors and directories.
  4219. */
  4220. /** Free all resources allocated for <b>tok</b> */
  4221. static void
  4222. token_clear(directory_token_t *tok)
  4223. {
  4224. if (tok->key)
  4225. crypto_pk_free(tok->key);
  4226. }
  4227. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  4228. #define ALLOC(sz) memarea_alloc(area,sz)
  4229. #define STRDUP(str) memarea_strdup(area,str)
  4230. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  4231. #define RET_ERR(msg) \
  4232. STMT_BEGIN \
  4233. if (tok) token_clear(tok); \
  4234. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  4235. tok->tp = ERR_; \
  4236. tok->error = STRDUP(msg); \
  4237. goto done_tokenizing; \
  4238. STMT_END
  4239. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  4240. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  4241. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  4242. * conform to the syntax we wanted.
  4243. **/
  4244. static inline directory_token_t *
  4245. token_check_object(memarea_t *area, const char *kwd,
  4246. directory_token_t *tok, obj_syntax o_syn)
  4247. {
  4248. char ebuf[128];
  4249. switch (o_syn) {
  4250. case NO_OBJ:
  4251. /* No object is allowed for this token. */
  4252. if (tok->object_body) {
  4253. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  4254. RET_ERR(ebuf);
  4255. }
  4256. if (tok->key) {
  4257. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  4258. RET_ERR(ebuf);
  4259. }
  4260. break;
  4261. case NEED_OBJ:
  4262. /* There must be a (non-key) object. */
  4263. if (!tok->object_body) {
  4264. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  4265. RET_ERR(ebuf);
  4266. }
  4267. break;
  4268. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  4269. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  4270. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  4271. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  4272. kwd, crypto_pk_num_bits(tok->key));
  4273. RET_ERR(ebuf);
  4274. }
  4275. /* fall through */
  4276. case NEED_KEY: /* There must be some kind of key. */
  4277. if (!tok->key) {
  4278. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  4279. RET_ERR(ebuf);
  4280. }
  4281. if (o_syn != NEED_SKEY_1024) {
  4282. if (crypto_pk_key_is_private(tok->key)) {
  4283. tor_snprintf(ebuf, sizeof(ebuf),
  4284. "Private key given for %s, which wants a public key", kwd);
  4285. RET_ERR(ebuf);
  4286. }
  4287. } else { /* o_syn == NEED_SKEY_1024 */
  4288. if (!crypto_pk_key_is_private(tok->key)) {
  4289. tor_snprintf(ebuf, sizeof(ebuf),
  4290. "Public key given for %s, which wants a private key", kwd);
  4291. RET_ERR(ebuf);
  4292. }
  4293. }
  4294. break;
  4295. case OBJ_OK:
  4296. /* Anything goes with this token. */
  4297. break;
  4298. }
  4299. done_tokenizing:
  4300. return tok;
  4301. }
  4302. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  4303. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  4304. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  4305. * all storage in <b>area</b>. Return the number of arguments parsed, or
  4306. * return -1 if there was an insanely high number of arguments. */
  4307. static inline int
  4308. get_token_arguments(memarea_t *area, directory_token_t *tok,
  4309. const char *s, const char *eol)
  4310. {
  4311. /** Largest number of arguments we'll accept to any token, ever. */
  4312. #define MAX_ARGS 512
  4313. char *mem = memarea_strndup(area, s, eol-s);
  4314. char *cp = mem;
  4315. int j = 0;
  4316. char *args[MAX_ARGS];
  4317. while (*cp) {
  4318. if (j == MAX_ARGS)
  4319. return -1;
  4320. args[j++] = cp;
  4321. cp = (char*)find_whitespace(cp);
  4322. if (!cp || !*cp)
  4323. break; /* End of the line. */
  4324. *cp++ = '\0';
  4325. cp = (char*)eat_whitespace(cp);
  4326. }
  4327. tok->n_args = j;
  4328. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  4329. return j;
  4330. #undef MAX_ARGS
  4331. }
  4332. /** Helper function: read the next token from *s, advance *s to the end of the
  4333. * token, and return the parsed token. Parse *<b>s</b> according to the list
  4334. * of tokens in <b>table</b>.
  4335. */
  4336. static directory_token_t *
  4337. get_next_token(memarea_t *area,
  4338. const char **s, const char *eos, token_rule_t *table)
  4339. {
  4340. /** Reject any object at least this big; it is probably an overflow, an
  4341. * attack, a bug, or some other nonsense. */
  4342. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  4343. /** Reject any line at least this big; it is probably an overflow, an
  4344. * attack, a bug, or some other nonsense. */
  4345. #define MAX_LINE_LENGTH (128*1024)
  4346. const char *next, *eol, *obstart;
  4347. size_t obname_len;
  4348. int i;
  4349. directory_token_t *tok;
  4350. obj_syntax o_syn = NO_OBJ;
  4351. char ebuf[128];
  4352. const char *kwd = "";
  4353. tor_assert(area);
  4354. tok = ALLOC_ZERO(sizeof(directory_token_t));
  4355. tok->tp = ERR_;
  4356. /* Set *s to first token, eol to end-of-line, next to after first token */
  4357. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  4358. tor_assert(eos >= *s);
  4359. eol = memchr(*s, '\n', eos-*s);
  4360. if (!eol)
  4361. eol = eos;
  4362. if (eol - *s > MAX_LINE_LENGTH) {
  4363. RET_ERR("Line far too long");
  4364. }
  4365. next = find_whitespace_eos(*s, eol);
  4366. if (!strcmp_len(*s, "opt", next-*s)) {
  4367. /* Skip past an "opt" at the start of the line. */
  4368. *s = eat_whitespace_eos_no_nl(next, eol);
  4369. next = find_whitespace_eos(*s, eol);
  4370. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  4371. RET_ERR("Unexpected EOF");
  4372. }
  4373. /* Search the table for the appropriate entry. (I tried a binary search
  4374. * instead, but it wasn't any faster.) */
  4375. for (i = 0; table[i].t ; ++i) {
  4376. if (!strcmp_len(*s, table[i].t, next-*s)) {
  4377. /* We've found the keyword. */
  4378. kwd = table[i].t;
  4379. tok->tp = table[i].v;
  4380. o_syn = table[i].os;
  4381. *s = eat_whitespace_eos_no_nl(next, eol);
  4382. /* We go ahead whether there are arguments or not, so that tok->args is
  4383. * always set if we want arguments. */
  4384. if (table[i].concat_args) {
  4385. /* The keyword takes the line as a single argument */
  4386. tok->args = ALLOC(sizeof(char*));
  4387. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  4388. tok->n_args = 1;
  4389. } else {
  4390. /* This keyword takes multiple arguments. */
  4391. if (get_token_arguments(area, tok, *s, eol)<0) {
  4392. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  4393. RET_ERR(ebuf);
  4394. }
  4395. *s = eol;
  4396. }
  4397. if (tok->n_args < table[i].min_args) {
  4398. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  4399. RET_ERR(ebuf);
  4400. } else if (tok->n_args > table[i].max_args) {
  4401. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  4402. RET_ERR(ebuf);
  4403. }
  4404. break;
  4405. }
  4406. }
  4407. if (tok->tp == ERR_) {
  4408. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  4409. if (**s == '@')
  4410. tok->tp = A_UNKNOWN_;
  4411. else
  4412. tok->tp = K_OPT;
  4413. tok->args = ALLOC(sizeof(char*));
  4414. tok->args[0] = STRNDUP(*s, eol-*s);
  4415. tok->n_args = 1;
  4416. o_syn = OBJ_OK;
  4417. }
  4418. /* Check whether there's an object present */
  4419. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  4420. tor_assert(eos >= *s);
  4421. eol = memchr(*s, '\n', eos-*s);
  4422. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  4423. goto check_object;
  4424. obstart = *s; /* Set obstart to start of object spec */
  4425. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  4426. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  4427. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  4428. RET_ERR("Malformed object: bad begin line");
  4429. }
  4430. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  4431. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  4432. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  4433. /* Go to the end of the object */
  4434. next = tor_memstr(*s, eos-*s, "-----END ");
  4435. if (!next) {
  4436. RET_ERR("Malformed object: missing object end line");
  4437. }
  4438. tor_assert(eos >= next);
  4439. eol = memchr(next, '\n', eos-next);
  4440. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  4441. eol = eos;
  4442. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  4443. if ((size_t)(eol-next) != 9+obname_len+5 ||
  4444. strcmp_len(next+9, tok->object_type, obname_len) ||
  4445. strcmp_len(eol-5, "-----", 5)) {
  4446. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  4447. tok->object_type);
  4448. ebuf[sizeof(ebuf)-1] = '\0';
  4449. RET_ERR(ebuf);
  4450. }
  4451. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  4452. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  4453. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  4454. tok->key = crypto_pk_new();
  4455. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  4456. RET_ERR("Couldn't parse public key.");
  4457. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  4458. tok->key = crypto_pk_new();
  4459. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  4460. RET_ERR("Couldn't parse private key.");
  4461. } else { /* If it's something else, try to base64-decode it */
  4462. int r;
  4463. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  4464. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  4465. if (r<0)
  4466. RET_ERR("Malformed object: bad base64-encoded data");
  4467. tok->object_size = r;
  4468. }
  4469. *s = eol;
  4470. check_object:
  4471. tok = token_check_object(area, kwd, tok, o_syn);
  4472. done_tokenizing:
  4473. return tok;
  4474. #undef RET_ERR
  4475. #undef ALLOC
  4476. #undef ALLOC_ZERO
  4477. #undef STRDUP
  4478. #undef STRNDUP
  4479. }
  4480. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  4481. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  4482. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  4483. * entire string.
  4484. */
  4485. static int
  4486. tokenize_string(memarea_t *area,
  4487. const char *start, const char *end, smartlist_t *out,
  4488. token_rule_t *table, int flags)
  4489. {
  4490. const char **s;
  4491. directory_token_t *tok = NULL;
  4492. int counts[NIL_];
  4493. int i;
  4494. int first_nonannotation;
  4495. int prev_len = smartlist_len(out);
  4496. tor_assert(area);
  4497. s = &start;
  4498. if (!end) {
  4499. end = start+strlen(start);
  4500. } else {
  4501. /* it's only meaningful to check for nuls if we got an end-of-string ptr */
  4502. if (memchr(start, '\0', end-start)) {
  4503. log_warn(LD_DIR, "parse error: internal NUL character.");
  4504. return -1;
  4505. }
  4506. }
  4507. for (i = 0; i < NIL_; ++i)
  4508. counts[i] = 0;
  4509. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  4510. while (*s < end && (!tok || tok->tp != EOF_)) {
  4511. tok = get_next_token(area, s, end, table);
  4512. if (tok->tp == ERR_) {
  4513. log_warn(LD_DIR, "parse error: %s", tok->error);
  4514. token_clear(tok);
  4515. return -1;
  4516. }
  4517. ++counts[tok->tp];
  4518. smartlist_add(out, tok);
  4519. *s = eat_whitespace_eos(*s, end);
  4520. }
  4521. if (flags & TS_NOCHECK)
  4522. return 0;
  4523. if ((flags & TS_ANNOTATIONS_OK)) {
  4524. first_nonannotation = -1;
  4525. for (i = 0; i < smartlist_len(out); ++i) {
  4526. tok = smartlist_get(out, i);
  4527. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  4528. first_nonannotation = i;
  4529. break;
  4530. }
  4531. }
  4532. if (first_nonannotation < 0) {
  4533. log_warn(LD_DIR, "parse error: item contains only annotations");
  4534. return -1;
  4535. }
  4536. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  4537. tok = smartlist_get(out, i);
  4538. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4539. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  4540. return -1;
  4541. }
  4542. }
  4543. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  4544. if (first_nonannotation != prev_len) {
  4545. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  4546. return -1;
  4547. }
  4548. }
  4549. } else {
  4550. for (i=0; i < smartlist_len(out); ++i) {
  4551. tok = smartlist_get(out, i);
  4552. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4553. log_warn(LD_DIR, "parse error: no annotations allowed.");
  4554. return -1;
  4555. }
  4556. }
  4557. first_nonannotation = 0;
  4558. }
  4559. for (i = 0; table[i].t; ++i) {
  4560. if (counts[table[i].v] < table[i].min_cnt) {
  4561. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  4562. return -1;
  4563. }
  4564. if (counts[table[i].v] > table[i].max_cnt) {
  4565. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  4566. return -1;
  4567. }
  4568. if (table[i].pos & AT_START) {
  4569. if (smartlist_len(out) < 1 ||
  4570. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  4571. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  4572. return -1;
  4573. }
  4574. }
  4575. if (table[i].pos & AT_END) {
  4576. if (smartlist_len(out) < 1 ||
  4577. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  4578. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  4579. return -1;
  4580. }
  4581. }
  4582. }
  4583. return 0;
  4584. }
  4585. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  4586. * NULL if no such keyword is found.
  4587. */
  4588. static directory_token_t *
  4589. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  4590. {
  4591. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  4592. return NULL;
  4593. }
  4594. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  4595. * with an assert if no such keyword is found.
  4596. */
  4597. static directory_token_t *
  4598. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  4599. const char *keyword_as_string)
  4600. {
  4601. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  4602. if (PREDICT_UNLIKELY(!tok)) {
  4603. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  4604. "been validated. Internal error.", keyword_as_string, (int)keyword);
  4605. tor_assert(tok);
  4606. }
  4607. return tok;
  4608. }
  4609. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  4610. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  4611. * in the same order in which they occur in <b>s</b>. Otherwise return
  4612. * NULL. */
  4613. static smartlist_t *
  4614. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  4615. {
  4616. smartlist_t *out = NULL;
  4617. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4618. if (t->tp == k) {
  4619. if (!out)
  4620. out = smartlist_new();
  4621. smartlist_add(out, t);
  4622. });
  4623. return out;
  4624. }
  4625. /** Return a newly allocated smartlist of all accept or reject tokens in
  4626. * <b>s</b>.
  4627. */
  4628. static smartlist_t *
  4629. find_all_exitpolicy(smartlist_t *s)
  4630. {
  4631. smartlist_t *out = smartlist_new();
  4632. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4633. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  4634. t->tp == K_REJECT || t->tp == K_REJECT6)
  4635. smartlist_add(out,t));
  4636. return out;
  4637. }
  4638. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  4639. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  4640. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  4641. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  4642. *
  4643. * Return 0 on success and -1 on failure.
  4644. */
  4645. static int
  4646. router_get_hash_impl_helper(const char *s, size_t s_len,
  4647. const char *start_str,
  4648. const char *end_str, char end_c,
  4649. const char **start_out, const char **end_out)
  4650. {
  4651. const char *start, *end;
  4652. start = tor_memstr(s, s_len, start_str);
  4653. if (!start) {
  4654. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  4655. return -1;
  4656. }
  4657. if (start != s && *(start-1) != '\n') {
  4658. log_warn(LD_DIR,
  4659. "first occurrence of \"%s\" is not at the start of a line",
  4660. start_str);
  4661. return -1;
  4662. }
  4663. end = tor_memstr(start+strlen(start_str),
  4664. s_len - (start-s) - strlen(start_str), end_str);
  4665. if (!end) {
  4666. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  4667. return -1;
  4668. }
  4669. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  4670. if (!end) {
  4671. log_warn(LD_DIR,"couldn't find EOL");
  4672. return -1;
  4673. }
  4674. ++end;
  4675. *start_out = start;
  4676. *end_out = end;
  4677. return 0;
  4678. }
  4679. /** Compute the digest of the substring of <b>s</b> taken from the first
  4680. * occurrence of <b>start_str</b> through the first instance of c after the
  4681. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  4682. * result in <b>digest</b>; return 0 on success.
  4683. *
  4684. * If no such substring exists, return -1.
  4685. */
  4686. static int
  4687. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  4688. const char *start_str,
  4689. const char *end_str, char end_c,
  4690. digest_algorithm_t alg)
  4691. {
  4692. const char *start=NULL, *end=NULL;
  4693. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4694. &start,&end)<0)
  4695. return -1;
  4696. if (alg == DIGEST_SHA1) {
  4697. if (crypto_digest(digest, start, end-start)) {
  4698. log_warn(LD_BUG,"couldn't compute digest");
  4699. return -1;
  4700. }
  4701. } else {
  4702. if (crypto_digest256(digest, start, end-start, alg)) {
  4703. log_warn(LD_BUG,"couldn't compute digest");
  4704. return -1;
  4705. }
  4706. }
  4707. return 0;
  4708. }
  4709. /** As router_get_hash_impl, but compute all hashes. */
  4710. static int
  4711. router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
  4712. const char *start_str,
  4713. const char *end_str, char end_c)
  4714. {
  4715. const char *start=NULL, *end=NULL;
  4716. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4717. &start,&end)<0)
  4718. return -1;
  4719. if (crypto_common_digests(digests, start, end-start)) {
  4720. log_warn(LD_BUG,"couldn't compute digests");
  4721. return -1;
  4722. }
  4723. return 0;
  4724. }
  4725. /** Assuming that s starts with a microdesc, return the start of the
  4726. * *NEXT* one. Return NULL on "not found." */
  4727. static const char *
  4728. find_start_of_next_microdesc(const char *s, const char *eos)
  4729. {
  4730. int started_with_annotations;
  4731. s = eat_whitespace_eos(s, eos);
  4732. if (!s)
  4733. return NULL;
  4734. #define CHECK_LENGTH() STMT_BEGIN \
  4735. if (s+32 > eos) \
  4736. return NULL; \
  4737. STMT_END
  4738. #define NEXT_LINE() STMT_BEGIN \
  4739. s = memchr(s, '\n', eos-s); \
  4740. if (!s || s+1 >= eos) \
  4741. return NULL; \
  4742. s++; \
  4743. STMT_END
  4744. CHECK_LENGTH();
  4745. started_with_annotations = (*s == '@');
  4746. if (started_with_annotations) {
  4747. /* Start by advancing to the first non-annotation line. */
  4748. while (*s == '@')
  4749. NEXT_LINE();
  4750. }
  4751. CHECK_LENGTH();
  4752. /* Now we should be pointed at an onion-key line. If we are, then skip
  4753. * it. */
  4754. if (!strcmpstart(s, "onion-key"))
  4755. NEXT_LINE();
  4756. /* Okay, now we're pointed at the first line of the microdescriptor which is
  4757. not an annotation or onion-key. The next line that _is_ an annotation or
  4758. onion-key is the start of the next microdescriptor. */
  4759. while (s+32 < eos) {
  4760. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4761. return s;
  4762. NEXT_LINE();
  4763. }
  4764. return NULL;
  4765. #undef CHECK_LENGTH
  4766. #undef NEXT_LINE
  4767. }
  4768. /** Parse as many microdescriptors as are found from the string starting at
  4769. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4770. * annotations we recognize and ignore ones we don't.
  4771. *
  4772. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  4773. * descriptor in the body field of each microdesc_t.
  4774. *
  4775. * Return all newly parsed microdescriptors in a newly allocated
  4776. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  4777. * microdesc digest to it for every microdesc that we found to be badly
  4778. * formed. (This may cause duplicates) */
  4779. smartlist_t *
  4780. microdescs_parse_from_string(const char *s, const char *eos,
  4781. int allow_annotations,
  4782. saved_location_t where,
  4783. smartlist_t *invalid_digests_out)
  4784. {
  4785. smartlist_t *tokens;
  4786. smartlist_t *result;
  4787. microdesc_t *md = NULL;
  4788. memarea_t *area;
  4789. const char *start = s;
  4790. const char *start_of_next_microdesc;
  4791. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4792. const int copy_body = (where != SAVED_IN_CACHE);
  4793. directory_token_t *tok;
  4794. if (!eos)
  4795. eos = s + strlen(s);
  4796. s = eat_whitespace_eos(s, eos);
  4797. area = memarea_new();
  4798. result = smartlist_new();
  4799. tokens = smartlist_new();
  4800. while (s < eos) {
  4801. int okay = 0;
  4802. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4803. if (!start_of_next_microdesc)
  4804. start_of_next_microdesc = eos;
  4805. md = tor_malloc_zero(sizeof(microdesc_t));
  4806. {
  4807. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4808. "onion-key");
  4809. const int no_onion_key = (cp == NULL);
  4810. if (no_onion_key) {
  4811. cp = s; /* So that we have *some* junk to put in the body */
  4812. }
  4813. md->bodylen = start_of_next_microdesc - cp;
  4814. md->saved_location = where;
  4815. if (copy_body)
  4816. md->body = tor_memdup_nulterm(cp, md->bodylen);
  4817. else
  4818. md->body = (char*)cp;
  4819. md->off = cp - start;
  4820. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4821. if (no_onion_key) {
  4822. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  4823. goto next;
  4824. }
  4825. }
  4826. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4827. microdesc_token_table, flags)) {
  4828. log_warn(LD_DIR, "Unparseable microdescriptor");
  4829. goto next;
  4830. }
  4831. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4832. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4833. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4834. goto next;
  4835. }
  4836. }
  4837. tok = find_by_keyword(tokens, K_ONION_KEY);
  4838. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4839. log_warn(LD_DIR,
  4840. "Relay's onion key had invalid exponent.");
  4841. goto next;
  4842. }
  4843. md->onion_pkey = tok->key;
  4844. tok->key = NULL;
  4845. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  4846. curve25519_public_key_t k;
  4847. tor_assert(tok->n_args >= 1);
  4848. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  4849. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  4850. goto next;
  4851. }
  4852. md->onion_curve25519_pkey =
  4853. tor_memdup(&k, sizeof(curve25519_public_key_t));
  4854. }
  4855. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  4856. if (id_lines) {
  4857. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  4858. tor_assert(t->n_args >= 2);
  4859. if (!strcmp(t->args[0], "ed25519")) {
  4860. if (md->ed25519_identity_pkey) {
  4861. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  4862. goto next;
  4863. }
  4864. ed25519_public_key_t k;
  4865. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  4866. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  4867. goto next;
  4868. }
  4869. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  4870. }
  4871. } SMARTLIST_FOREACH_END(t);
  4872. smartlist_free(id_lines);
  4873. }
  4874. {
  4875. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4876. if (a_lines) {
  4877. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4878. smartlist_free(a_lines);
  4879. }
  4880. }
  4881. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4882. int i;
  4883. md->family = smartlist_new();
  4884. for (i=0;i<tok->n_args;++i) {
  4885. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4886. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4887. escaped(tok->args[i]));
  4888. goto next;
  4889. }
  4890. smartlist_add(md->family, tor_strdup(tok->args[i]));
  4891. }
  4892. }
  4893. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4894. md->exit_policy = parse_short_policy(tok->args[0]);
  4895. }
  4896. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4897. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4898. }
  4899. smartlist_add(result, md);
  4900. okay = 1;
  4901. md = NULL;
  4902. next:
  4903. if (! okay && invalid_digests_out) {
  4904. smartlist_add(invalid_digests_out,
  4905. tor_memdup(md->digest, DIGEST256_LEN));
  4906. }
  4907. microdesc_free(md);
  4908. md = NULL;
  4909. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4910. memarea_clear(area);
  4911. smartlist_clear(tokens);
  4912. s = start_of_next_microdesc;
  4913. }
  4914. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4915. memarea_drop_all(area);
  4916. smartlist_free(tokens);
  4917. return result;
  4918. }
  4919. /** Parse the Tor version of the platform string <b>platform</b>,
  4920. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4921. * the router is at least as new as the cutoff, else return 0.
  4922. */
  4923. int
  4924. tor_version_as_new_as(const char *platform, const char *cutoff)
  4925. {
  4926. tor_version_t cutoff_version, router_version;
  4927. char *s, *s2, *start;
  4928. char tmp[128];
  4929. tor_assert(platform);
  4930. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4931. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4932. return 0;
  4933. }
  4934. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4935. return 1;
  4936. start = (char *)eat_whitespace(platform+3);
  4937. if (!*start) return 0;
  4938. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4939. s2 = (char*)eat_whitespace(s);
  4940. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4941. s = (char*)find_whitespace(s2);
  4942. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4943. return 0;
  4944. strlcpy(tmp, start, s-start+1);
  4945. if (tor_version_parse(tmp, &router_version)<0) {
  4946. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4947. return 1; /* be safe and say yes */
  4948. }
  4949. /* Here's why we don't need to do any special handling for svn revisions:
  4950. * - If neither has an svn revision, we're fine.
  4951. * - If the router doesn't have an svn revision, we can't assume that it
  4952. * is "at least" any svn revision, so we need to return 0.
  4953. * - If the target version doesn't have an svn revision, any svn revision
  4954. * (or none at all) is good enough, so return 1.
  4955. * - If both target and router have an svn revision, we compare them.
  4956. */
  4957. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  4958. }
  4959. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  4960. * Return 0 on success, -1 on failure. */
  4961. int
  4962. tor_version_parse(const char *s, tor_version_t *out)
  4963. {
  4964. char *eos=NULL;
  4965. const char *cp=NULL;
  4966. /* Format is:
  4967. * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
  4968. */
  4969. tor_assert(s);
  4970. tor_assert(out);
  4971. memset(out, 0, sizeof(tor_version_t));
  4972. out->status = VER_RELEASE;
  4973. if (!strcasecmpstart(s, "Tor "))
  4974. s += 4;
  4975. cp = s;
  4976. #define NUMBER(m) \
  4977. do { \
  4978. out->m = (int)strtol(cp, &eos, 10); \
  4979. if (!eos || eos == cp) \
  4980. return -1; \
  4981. cp = eos; \
  4982. } while (0)
  4983. #define DOT() \
  4984. do { \
  4985. if (*cp != '.') \
  4986. return -1; \
  4987. ++cp; \
  4988. } while (0)
  4989. NUMBER(major);
  4990. DOT();
  4991. NUMBER(minor);
  4992. if (*cp == 0)
  4993. return 0;
  4994. else if (*cp == '-')
  4995. goto status_tag;
  4996. DOT();
  4997. NUMBER(micro);
  4998. /* Get status */
  4999. if (*cp == 0) {
  5000. return 0;
  5001. } else if (*cp == '.') {
  5002. ++cp;
  5003. } else if (*cp == '-') {
  5004. goto status_tag;
  5005. } else if (0==strncmp(cp, "pre", 3)) {
  5006. out->status = VER_PRE;
  5007. cp += 3;
  5008. } else if (0==strncmp(cp, "rc", 2)) {
  5009. out->status = VER_RC;
  5010. cp += 2;
  5011. } else {
  5012. return -1;
  5013. }
  5014. NUMBER(patchlevel);
  5015. status_tag:
  5016. /* Get status tag. */
  5017. if (*cp == '-' || *cp == '.')
  5018. ++cp;
  5019. eos = (char*) find_whitespace(cp);
  5020. if (eos-cp >= (int)sizeof(out->status_tag))
  5021. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  5022. else {
  5023. memcpy(out->status_tag, cp, eos-cp);
  5024. out->status_tag[eos-cp] = 0;
  5025. }
  5026. cp = eat_whitespace(eos);
  5027. if (!strcmpstart(cp, "(r")) {
  5028. cp += 2;
  5029. out->svn_revision = (int) strtol(cp,&eos,10);
  5030. } else if (!strcmpstart(cp, "(git-")) {
  5031. char *close_paren = strchr(cp, ')');
  5032. int hexlen;
  5033. char digest[DIGEST_LEN];
  5034. if (! close_paren)
  5035. return -1;
  5036. cp += 5;
  5037. if (close_paren-cp > HEX_DIGEST_LEN)
  5038. return -1;
  5039. hexlen = (int)(close_paren-cp);
  5040. memwipe(digest, 0, sizeof(digest));
  5041. if ( hexlen == 0 || (hexlen % 2) == 1)
  5042. return -1;
  5043. if (base16_decode(digest, hexlen/2, cp, hexlen) != hexlen/2)
  5044. return -1;
  5045. memcpy(out->git_tag, digest, hexlen/2);
  5046. out->git_tag_len = hexlen/2;
  5047. }
  5048. return 0;
  5049. #undef NUMBER
  5050. #undef DOT
  5051. }
  5052. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  5053. * b. */
  5054. int
  5055. tor_version_compare(tor_version_t *a, tor_version_t *b)
  5056. {
  5057. int i;
  5058. tor_assert(a);
  5059. tor_assert(b);
  5060. if ((i = a->major - b->major))
  5061. return i;
  5062. else if ((i = a->minor - b->minor))
  5063. return i;
  5064. else if ((i = a->micro - b->micro))
  5065. return i;
  5066. else if ((i = a->status - b->status))
  5067. return i;
  5068. else if ((i = a->patchlevel - b->patchlevel))
  5069. return i;
  5070. else if ((i = strcmp(a->status_tag, b->status_tag)))
  5071. return i;
  5072. else if ((i = a->svn_revision - b->svn_revision))
  5073. return i;
  5074. else if ((i = a->git_tag_len - b->git_tag_len))
  5075. return i;
  5076. else if (a->git_tag_len)
  5077. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  5078. else
  5079. return 0;
  5080. }
  5081. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  5082. */
  5083. int
  5084. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  5085. {
  5086. tor_assert(a);
  5087. tor_assert(b);
  5088. return ((a->major == b->major) &&
  5089. (a->minor == b->minor) &&
  5090. (a->micro == b->micro));
  5091. }
  5092. /** Helper: Given pointers to two strings describing tor versions, return -1
  5093. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  5094. * Used to sort a list of versions. */
  5095. static int
  5096. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  5097. {
  5098. const char *a = *_a, *b = *_b;
  5099. int ca, cb;
  5100. tor_version_t va, vb;
  5101. ca = tor_version_parse(a, &va);
  5102. cb = tor_version_parse(b, &vb);
  5103. /* If they both parse, compare them. */
  5104. if (!ca && !cb)
  5105. return tor_version_compare(&va,&vb);
  5106. /* If one parses, it comes first. */
  5107. if (!ca && cb)
  5108. return -1;
  5109. if (ca && !cb)
  5110. return 1;
  5111. /* If neither parses, compare strings. Also, the directory server admin
  5112. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  5113. return strcmp(a,b);
  5114. }
  5115. /** Sort a list of string-representations of versions in ascending order. */
  5116. void
  5117. sort_version_list(smartlist_t *versions, int remove_duplicates)
  5118. {
  5119. smartlist_sort(versions, compare_tor_version_str_ptr_);
  5120. if (remove_duplicates)
  5121. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  5122. }
  5123. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  5124. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  5125. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  5126. * encrypted introduction points to the newly allocated
  5127. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  5128. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  5129. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  5130. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  5131. * and -1 for failure.
  5132. *
  5133. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  5134. * be strict about time formats.
  5135. */
  5136. int
  5137. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  5138. char *desc_id_out,
  5139. char **intro_points_encrypted_out,
  5140. size_t *intro_points_encrypted_size_out,
  5141. size_t *encoded_size_out,
  5142. const char **next_out, const char *desc,
  5143. int as_hsdir)
  5144. {
  5145. rend_service_descriptor_t *result =
  5146. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  5147. char desc_hash[DIGEST_LEN];
  5148. const char *eos;
  5149. smartlist_t *tokens = smartlist_new();
  5150. directory_token_t *tok;
  5151. char secret_id_part[DIGEST_LEN];
  5152. int i, version, num_ok=1;
  5153. smartlist_t *versions;
  5154. char public_key_hash[DIGEST_LEN];
  5155. char test_desc_id[DIGEST_LEN];
  5156. memarea_t *area = NULL;
  5157. const int strict_time_fmt = as_hsdir;
  5158. tor_assert(desc);
  5159. /* Check if desc starts correctly. */
  5160. if (strncmp(desc, "rendezvous-service-descriptor ",
  5161. strlen("rendezvous-service-descriptor "))) {
  5162. log_info(LD_REND, "Descriptor does not start correctly.");
  5163. goto err;
  5164. }
  5165. /* Compute descriptor hash for later validation. */
  5166. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  5167. "rendezvous-service-descriptor ",
  5168. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  5169. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  5170. goto err;
  5171. }
  5172. /* Determine end of string. */
  5173. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  5174. if (!eos)
  5175. eos = desc + strlen(desc);
  5176. else
  5177. eos = eos + 1;
  5178. /* Check length. */
  5179. if (eos-desc > REND_DESC_MAX_SIZE) {
  5180. /* XXXX+ If we are parsing this descriptor as a server, this
  5181. * should be a protocol warning. */
  5182. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  5183. "maximum rendezvous descriptor size of %d bytes.",
  5184. (int)(eos-desc), REND_DESC_MAX_SIZE);
  5185. goto err;
  5186. }
  5187. /* Tokenize descriptor. */
  5188. area = memarea_new();
  5189. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  5190. log_warn(LD_REND, "Error tokenizing descriptor.");
  5191. goto err;
  5192. }
  5193. /* Set next to next descriptor, if available. */
  5194. *next_out = eos;
  5195. /* Set length of encoded descriptor. */
  5196. *encoded_size_out = eos - desc;
  5197. /* Check min allowed length of token list. */
  5198. if (smartlist_len(tokens) < 7) {
  5199. log_warn(LD_REND, "Impossibly short descriptor.");
  5200. goto err;
  5201. }
  5202. /* Parse base32-encoded descriptor ID. */
  5203. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  5204. tor_assert(tok == smartlist_get(tokens, 0));
  5205. tor_assert(tok->n_args == 1);
  5206. if (!rend_valid_descriptor_id(tok->args[0])) {
  5207. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  5208. goto err;
  5209. }
  5210. if (base32_decode(desc_id_out, DIGEST_LEN,
  5211. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  5212. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  5213. tok->args[0]);
  5214. goto err;
  5215. }
  5216. /* Parse descriptor version. */
  5217. tok = find_by_keyword(tokens, R_VERSION);
  5218. tor_assert(tok->n_args == 1);
  5219. result->version =
  5220. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  5221. if (result->version != 2 || !num_ok) {
  5222. /* If it's <2, it shouldn't be under this format. If the number
  5223. * is greater than 2, we bumped it because we broke backward
  5224. * compatibility. See how version numbers in our other formats
  5225. * work. */
  5226. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  5227. escaped(tok->args[0]));
  5228. goto err;
  5229. }
  5230. /* Parse public key. */
  5231. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  5232. result->pk = tok->key;
  5233. tok->key = NULL; /* Prevent free */
  5234. /* Parse secret ID part. */
  5235. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  5236. tor_assert(tok->n_args == 1);
  5237. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  5238. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  5239. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  5240. goto err;
  5241. }
  5242. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  5243. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  5244. tok->args[0]);
  5245. goto err;
  5246. }
  5247. /* Parse publication time -- up-to-date check is done when storing the
  5248. * descriptor. */
  5249. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  5250. tor_assert(tok->n_args == 1);
  5251. if (parse_iso_time_(tok->args[0], &result->timestamp, strict_time_fmt) < 0) {
  5252. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  5253. goto err;
  5254. }
  5255. /* Parse protocol versions. */
  5256. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  5257. tor_assert(tok->n_args == 1);
  5258. versions = smartlist_new();
  5259. smartlist_split_string(versions, tok->args[0], ",",
  5260. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  5261. for (i = 0; i < smartlist_len(versions); i++) {
  5262. version = (int) tor_parse_long(smartlist_get(versions, i),
  5263. 10, 0, INT_MAX, &num_ok, NULL);
  5264. if (!num_ok) /* It's a string; let's ignore it. */
  5265. continue;
  5266. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  5267. /* Avoid undefined left-shift behaviour. */
  5268. continue;
  5269. result->protocols |= 1 << version;
  5270. }
  5271. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  5272. smartlist_free(versions);
  5273. /* Parse encrypted introduction points. Don't verify. */
  5274. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  5275. if (tok) {
  5276. if (strcmp(tok->object_type, "MESSAGE")) {
  5277. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  5278. "type MESSAGE");
  5279. goto err;
  5280. }
  5281. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  5282. tok->object_size);
  5283. *intro_points_encrypted_size_out = tok->object_size;
  5284. } else {
  5285. *intro_points_encrypted_out = NULL;
  5286. *intro_points_encrypted_size_out = 0;
  5287. }
  5288. /* Parse and verify signature. */
  5289. tok = find_by_keyword(tokens, R_SIGNATURE);
  5290. note_crypto_pk_op(VERIFY_RTR);
  5291. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  5292. "v2 rendezvous service descriptor") < 0)
  5293. goto err;
  5294. /* Verify that descriptor ID belongs to public key and secret ID part. */
  5295. crypto_pk_get_digest(result->pk, public_key_hash);
  5296. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  5297. secret_id_part);
  5298. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  5299. log_warn(LD_REND, "Parsed descriptor ID does not match "
  5300. "computed descriptor ID.");
  5301. goto err;
  5302. }
  5303. goto done;
  5304. err:
  5305. rend_service_descriptor_free(result);
  5306. result = NULL;
  5307. done:
  5308. if (tokens) {
  5309. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5310. smartlist_free(tokens);
  5311. }
  5312. if (area)
  5313. memarea_drop_all(area);
  5314. *parsed_out = result;
  5315. if (result)
  5316. return 0;
  5317. return -1;
  5318. }
  5319. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  5320. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  5321. * write the result to a newly allocated string that is pointed to by
  5322. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  5323. * Return 0 if decryption was successful and -1 otherwise. */
  5324. int
  5325. rend_decrypt_introduction_points(char **ipos_decrypted,
  5326. size_t *ipos_decrypted_size,
  5327. const char *descriptor_cookie,
  5328. const char *ipos_encrypted,
  5329. size_t ipos_encrypted_size)
  5330. {
  5331. tor_assert(ipos_encrypted);
  5332. tor_assert(descriptor_cookie);
  5333. if (ipos_encrypted_size < 2) {
  5334. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5335. "small.");
  5336. return -1;
  5337. }
  5338. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  5339. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  5340. session_key[CIPHER_KEY_LEN], *dec;
  5341. int declen, client_blocks;
  5342. size_t pos = 0, len, client_entries_len;
  5343. crypto_digest_t *digest;
  5344. crypto_cipher_t *cipher;
  5345. client_blocks = (int) ipos_encrypted[1];
  5346. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  5347. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  5348. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  5349. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5350. "small.");
  5351. return -1;
  5352. }
  5353. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  5354. digest = crypto_digest_new();
  5355. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  5356. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  5357. crypto_digest_get_digest(digest, client_id,
  5358. REND_BASIC_AUTH_CLIENT_ID_LEN);
  5359. crypto_digest_free(digest);
  5360. for (pos = 2; pos < 2 + client_entries_len;
  5361. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  5362. if (tor_memeq(ipos_encrypted + pos, client_id,
  5363. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  5364. /* Attempt to decrypt introduction points. */
  5365. cipher = crypto_cipher_new(descriptor_cookie);
  5366. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  5367. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  5368. CIPHER_KEY_LEN) < 0) {
  5369. log_warn(LD_REND, "Could not decrypt session key for client.");
  5370. crypto_cipher_free(cipher);
  5371. return -1;
  5372. }
  5373. crypto_cipher_free(cipher);
  5374. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  5375. dec = tor_malloc(len);
  5376. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  5377. ipos_encrypted + 2 + client_entries_len,
  5378. ipos_encrypted_size - 2 - client_entries_len);
  5379. if (declen < 0) {
  5380. log_warn(LD_REND, "Could not decrypt introduction point string.");
  5381. tor_free(dec);
  5382. return -1;
  5383. }
  5384. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  5385. log_warn(LD_REND, "Decrypted introduction points don't "
  5386. "look like we could parse them.");
  5387. tor_free(dec);
  5388. continue;
  5389. }
  5390. *ipos_decrypted = dec;
  5391. *ipos_decrypted_size = declen;
  5392. return 0;
  5393. }
  5394. }
  5395. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  5396. "check your authorization for this service!");
  5397. return -1;
  5398. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  5399. char *dec;
  5400. int declen;
  5401. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  5402. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5403. "small.");
  5404. return -1;
  5405. }
  5406. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  5407. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  5408. ipos_encrypted_size -
  5409. CIPHER_IV_LEN - 1,
  5410. ipos_encrypted + 1,
  5411. ipos_encrypted_size - 1);
  5412. if (declen < 0) {
  5413. log_warn(LD_REND, "Decrypting introduction points failed!");
  5414. tor_free(dec);
  5415. return -1;
  5416. }
  5417. *ipos_decrypted = dec;
  5418. *ipos_decrypted_size = declen;
  5419. return 0;
  5420. } else {
  5421. log_warn(LD_REND, "Unknown authorization type number: %d",
  5422. ipos_encrypted[0]);
  5423. return -1;
  5424. }
  5425. }
  5426. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  5427. * length <b>intro_points_encoded_size</b> and write the result to the
  5428. * descriptor in <b>parsed</b>; return the number of successfully parsed
  5429. * introduction points or -1 in case of a failure. */
  5430. int
  5431. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  5432. const char *intro_points_encoded,
  5433. size_t intro_points_encoded_size)
  5434. {
  5435. const char *current_ipo, *end_of_intro_points;
  5436. smartlist_t *tokens = NULL;
  5437. directory_token_t *tok;
  5438. rend_intro_point_t *intro;
  5439. extend_info_t *info;
  5440. int result, num_ok=1;
  5441. memarea_t *area = NULL;
  5442. tor_assert(parsed);
  5443. /** Function may only be invoked once. */
  5444. tor_assert(!parsed->intro_nodes);
  5445. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  5446. log_warn(LD_REND, "Empty or zero size introduction point list");
  5447. goto err;
  5448. }
  5449. /* Consider one intro point after the other. */
  5450. current_ipo = intro_points_encoded;
  5451. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  5452. tokens = smartlist_new();
  5453. parsed->intro_nodes = smartlist_new();
  5454. area = memarea_new();
  5455. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  5456. "introduction-point ")) {
  5457. /* Determine end of string. */
  5458. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  5459. "\nintroduction-point ");
  5460. if (!eos)
  5461. eos = end_of_intro_points;
  5462. else
  5463. eos = eos+1;
  5464. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  5465. /* Free tokens and clear token list. */
  5466. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5467. smartlist_clear(tokens);
  5468. memarea_clear(area);
  5469. /* Tokenize string. */
  5470. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  5471. log_warn(LD_REND, "Error tokenizing introduction point");
  5472. goto err;
  5473. }
  5474. /* Advance to next introduction point, if available. */
  5475. current_ipo = eos;
  5476. /* Check minimum allowed length of introduction point. */
  5477. if (smartlist_len(tokens) < 5) {
  5478. log_warn(LD_REND, "Impossibly short introduction point.");
  5479. goto err;
  5480. }
  5481. /* Allocate new intro point and extend info. */
  5482. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  5483. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  5484. /* Parse identifier. */
  5485. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  5486. if (base32_decode(info->identity_digest, DIGEST_LEN,
  5487. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  5488. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  5489. tok->args[0]);
  5490. rend_intro_point_free(intro);
  5491. goto err;
  5492. }
  5493. /* Write identifier to nickname. */
  5494. info->nickname[0] = '$';
  5495. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  5496. info->identity_digest, DIGEST_LEN);
  5497. /* Parse IP address. */
  5498. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  5499. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  5500. log_warn(LD_REND, "Could not parse introduction point address.");
  5501. rend_intro_point_free(intro);
  5502. goto err;
  5503. }
  5504. if (tor_addr_family(&info->addr) != AF_INET) {
  5505. log_warn(LD_REND, "Introduction point address was not ipv4.");
  5506. rend_intro_point_free(intro);
  5507. goto err;
  5508. }
  5509. /* Parse onion port. */
  5510. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  5511. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  5512. &num_ok,NULL);
  5513. if (!info->port || !num_ok) {
  5514. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  5515. escaped(tok->args[0]));
  5516. rend_intro_point_free(intro);
  5517. goto err;
  5518. }
  5519. /* Parse onion key. */
  5520. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  5521. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5522. log_warn(LD_REND,
  5523. "Introduction point's onion key had invalid exponent.");
  5524. rend_intro_point_free(intro);
  5525. goto err;
  5526. }
  5527. info->onion_key = tok->key;
  5528. tok->key = NULL; /* Prevent free */
  5529. /* Parse service key. */
  5530. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  5531. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5532. log_warn(LD_REND,
  5533. "Introduction point key had invalid exponent.");
  5534. rend_intro_point_free(intro);
  5535. goto err;
  5536. }
  5537. intro->intro_key = tok->key;
  5538. tok->key = NULL; /* Prevent free */
  5539. /* Add extend info to list of introduction points. */
  5540. smartlist_add(parsed->intro_nodes, intro);
  5541. }
  5542. result = smartlist_len(parsed->intro_nodes);
  5543. goto done;
  5544. err:
  5545. result = -1;
  5546. done:
  5547. /* Free tokens and clear token list. */
  5548. if (tokens) {
  5549. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5550. smartlist_free(tokens);
  5551. }
  5552. if (area)
  5553. memarea_drop_all(area);
  5554. return result;
  5555. }
  5556. /** Parse the content of a client_key file in <b>ckstr</b> and add
  5557. * rend_authorized_client_t's for each parsed client to
  5558. * <b>parsed_clients</b>. Return the number of parsed clients as result
  5559. * or -1 for failure. */
  5560. int
  5561. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  5562. {
  5563. int result = -1;
  5564. smartlist_t *tokens;
  5565. directory_token_t *tok;
  5566. const char *current_entry = NULL;
  5567. memarea_t *area = NULL;
  5568. char *err_msg = NULL;
  5569. if (!ckstr || strlen(ckstr) == 0)
  5570. return -1;
  5571. tokens = smartlist_new();
  5572. /* Begin parsing with first entry, skipping comments or whitespace at the
  5573. * beginning. */
  5574. area = memarea_new();
  5575. current_entry = eat_whitespace(ckstr);
  5576. while (!strcmpstart(current_entry, "client-name ")) {
  5577. rend_authorized_client_t *parsed_entry;
  5578. /* Determine end of string. */
  5579. const char *eos = strstr(current_entry, "\nclient-name ");
  5580. if (!eos)
  5581. eos = current_entry + strlen(current_entry);
  5582. else
  5583. eos = eos + 1;
  5584. /* Free tokens and clear token list. */
  5585. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5586. smartlist_clear(tokens);
  5587. memarea_clear(area);
  5588. /* Tokenize string. */
  5589. if (tokenize_string(area, current_entry, eos, tokens,
  5590. client_keys_token_table, 0)) {
  5591. log_warn(LD_REND, "Error tokenizing client keys file.");
  5592. goto err;
  5593. }
  5594. /* Advance to next entry, if available. */
  5595. current_entry = eos;
  5596. /* Check minimum allowed length of token list. */
  5597. if (smartlist_len(tokens) < 2) {
  5598. log_warn(LD_REND, "Impossibly short client key entry.");
  5599. goto err;
  5600. }
  5601. /* Parse client name. */
  5602. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  5603. tor_assert(tok == smartlist_get(tokens, 0));
  5604. tor_assert(tok->n_args == 1);
  5605. if (!rend_valid_client_name(tok->args[0])) {
  5606. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  5607. "between 1 and %d, and valid characters are "
  5608. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  5609. goto err;
  5610. }
  5611. /* Check if client name is duplicate. */
  5612. if (strmap_get(parsed_clients, tok->args[0])) {
  5613. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  5614. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  5615. goto err;
  5616. }
  5617. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  5618. parsed_entry->client_name = tor_strdup(tok->args[0]);
  5619. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  5620. /* Parse client key. */
  5621. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  5622. if (tok) {
  5623. parsed_entry->client_key = tok->key;
  5624. tok->key = NULL; /* Prevent free */
  5625. }
  5626. /* Parse descriptor cookie. */
  5627. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  5628. tor_assert(tok->n_args == 1);
  5629. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  5630. NULL, &err_msg) < 0) {
  5631. tor_assert(err_msg);
  5632. log_warn(LD_REND, "%s", err_msg);
  5633. tor_free(err_msg);
  5634. goto err;
  5635. }
  5636. }
  5637. result = strmap_size(parsed_clients);
  5638. goto done;
  5639. err:
  5640. result = -1;
  5641. done:
  5642. /* Free tokens and clear token list. */
  5643. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5644. smartlist_free(tokens);
  5645. if (area)
  5646. memarea_drop_all(area);
  5647. return result;
  5648. }
  5649. /** Called on startup; right now we just handle scanning the unparseable
  5650. * descriptor dumps, but hang anything else we might need to do in the
  5651. * future here as well.
  5652. */
  5653. void
  5654. routerparse_init(void)
  5655. {
  5656. /*
  5657. * Check both if the sandbox is active and whether it's configured; no
  5658. * point in loading all that if we won't be able to use it after the
  5659. * sandbox becomes active.
  5660. */
  5661. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  5662. dump_desc_init();
  5663. }
  5664. }
  5665. /** Clean up all data structures used by routerparse.c at exit */
  5666. void
  5667. routerparse_free_all(void)
  5668. {
  5669. dump_desc_fifo_cleanup();
  5670. }