routerparse.c 213 KB

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