routerparse.c 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255
  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. int i;
  2587. for (i=0; i < tok->n_args; ++i) {
  2588. if (!strcmp(tok->args[i], "Exit"))
  2589. rs->is_exit = 1;
  2590. else if (!strcmp(tok->args[i], "Stable"))
  2591. rs->is_stable = 1;
  2592. else if (!strcmp(tok->args[i], "Fast"))
  2593. rs->is_fast = 1;
  2594. else if (!strcmp(tok->args[i], "Running"))
  2595. rs->is_flagged_running = 1;
  2596. else if (!strcmp(tok->args[i], "Named"))
  2597. rs->is_named = 1;
  2598. else if (!strcmp(tok->args[i], "Valid"))
  2599. rs->is_valid = 1;
  2600. else if (!strcmp(tok->args[i], "Guard"))
  2601. rs->is_possible_guard = 1;
  2602. else if (!strcmp(tok->args[i], "BadExit"))
  2603. rs->is_bad_exit = 1;
  2604. else if (!strcmp(tok->args[i], "Authority"))
  2605. rs->is_authority = 1;
  2606. else if (!strcmp(tok->args[i], "Unnamed") &&
  2607. consensus_method >= 2) {
  2608. /* Unnamed is computed right by consensus method 2 and later. */
  2609. rs->is_unnamed = 1;
  2610. } else if (!strcmp(tok->args[i], "HSDir")) {
  2611. rs->is_hs_dir = 1;
  2612. } else if (!strcmp(tok->args[i], "V2Dir")) {
  2613. rs->is_v2_dir = 1;
  2614. }
  2615. }
  2616. }
  2617. int found_protocol_list = 0;
  2618. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  2619. found_protocol_list = 1;
  2620. rs->protocols_known = 1;
  2621. rs->supports_extend2_cells =
  2622. protocol_list_supports_protocol(tok->args[0], PRT_RELAY, 2);
  2623. }
  2624. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  2625. tor_assert(tok->n_args == 1);
  2626. if (!strcmpstart(tok->args[0], "Tor ") && !found_protocol_list) {
  2627. /* We only do version checks like this in the case where
  2628. * the version is a "Tor" version, and where there is no
  2629. * list of protocol versions that we should be looking at instead. */
  2630. rs->supports_extend2_cells =
  2631. tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
  2632. rs->protocols_known = 1;
  2633. }
  2634. if (vote_rs) {
  2635. vote_rs->version = tor_strdup(tok->args[0]);
  2636. }
  2637. }
  2638. /* handle weighting/bandwidth info */
  2639. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  2640. int i;
  2641. for (i=0; i < tok->n_args; ++i) {
  2642. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  2643. int ok;
  2644. rs->bandwidth_kb =
  2645. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2646. 10, 0, UINT32_MAX,
  2647. &ok, NULL);
  2648. if (!ok) {
  2649. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  2650. goto err;
  2651. }
  2652. rs->has_bandwidth = 1;
  2653. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  2654. int ok;
  2655. vote_rs->measured_bw_kb =
  2656. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2657. 10, 0, UINT32_MAX, &ok, NULL);
  2658. if (!ok) {
  2659. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  2660. escaped(tok->args[i]));
  2661. goto err;
  2662. }
  2663. vote_rs->has_measured_bw = 1;
  2664. vote->has_measured_bws = 1;
  2665. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  2666. rs->bw_is_unmeasured = 1;
  2667. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  2668. if (routerstatus_parse_guardfraction(tok->args[i],
  2669. vote, vote_rs, rs) < 0) {
  2670. goto err;
  2671. }
  2672. }
  2673. }
  2674. }
  2675. /* parse exit policy summaries */
  2676. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  2677. tor_assert(tok->n_args == 1);
  2678. if (strcmpstart(tok->args[0], "accept ") &&
  2679. strcmpstart(tok->args[0], "reject ")) {
  2680. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  2681. escaped(tok->args[0]));
  2682. goto err;
  2683. }
  2684. /* XXX weasel: parse this into ports and represent them somehow smart,
  2685. * maybe not here but somewhere on if we need it for the client.
  2686. * we should still parse it here to check it's valid tho.
  2687. */
  2688. rs->exitsummary = tor_strdup(tok->args[0]);
  2689. rs->has_exitsummary = 1;
  2690. }
  2691. if (vote_rs) {
  2692. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2693. if (t->tp == K_M && t->n_args) {
  2694. vote_microdesc_hash_t *line =
  2695. tor_malloc(sizeof(vote_microdesc_hash_t));
  2696. line->next = vote_rs->microdesc;
  2697. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2698. vote_rs->microdesc = line;
  2699. }
  2700. if (t->tp == K_ID) {
  2701. tor_assert(t->n_args >= 2);
  2702. if (!strcmp(t->args[0], "ed25519")) {
  2703. vote_rs->has_ed25519_listing = 1;
  2704. if (strcmp(t->args[1], "none") &&
  2705. digest256_from_base64((char*)vote_rs->ed25519_id,
  2706. t->args[1])<0) {
  2707. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  2708. goto err;
  2709. }
  2710. }
  2711. }
  2712. if (t->tp == K_PROTO) {
  2713. tor_assert(t->n_args == 1);
  2714. vote_rs->protocols = tor_strdup(t->args[0]);
  2715. }
  2716. } SMARTLIST_FOREACH_END(t);
  2717. } else if (flav == FLAV_MICRODESC) {
  2718. tok = find_opt_by_keyword(tokens, K_M);
  2719. if (tok) {
  2720. tor_assert(tok->n_args);
  2721. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2722. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2723. escaped(tok->args[0]));
  2724. goto err;
  2725. }
  2726. } else {
  2727. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2728. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  2729. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2730. fmt_addr32(rs->addr), rs->or_port);
  2731. }
  2732. }
  2733. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2734. rs->is_named = 0;
  2735. goto done;
  2736. err:
  2737. dump_desc(s_dup, "routerstatus entry");
  2738. if (rs && !vote_rs)
  2739. routerstatus_free(rs);
  2740. rs = NULL;
  2741. done:
  2742. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2743. smartlist_clear(tokens);
  2744. if (area) {
  2745. DUMP_AREA(area, "routerstatus entry");
  2746. memarea_clear(area);
  2747. }
  2748. *s = eos;
  2749. return rs;
  2750. }
  2751. int
  2752. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  2753. {
  2754. const vote_routerstatus_t *a = *_a, *b = *_b;
  2755. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  2756. DIGEST_LEN);
  2757. }
  2758. /** Verify the bandwidth weights of a network status document */
  2759. int
  2760. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  2761. {
  2762. int64_t weight_scale;
  2763. int64_t G=0, M=0, E=0, D=0, T=0;
  2764. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2765. double Gtotal=0, Mtotal=0, Etotal=0;
  2766. const char *casename = NULL;
  2767. int valid = 1;
  2768. (void) consensus_method;
  2769. weight_scale = networkstatus_get_weight_scale_param(ns);
  2770. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2771. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2772. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2773. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2774. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2775. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2776. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2777. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2778. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2779. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2780. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2781. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2782. || Wem<0 || Wee<0 || Wed<0) {
  2783. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2784. return 0;
  2785. }
  2786. // First, sanity check basic summing properties that hold for all cases
  2787. // We use > 1 as the check for these because they are computed as integers.
  2788. // Sometimes there are rounding errors.
  2789. if (fabs(Wmm - weight_scale) > 1) {
  2790. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2791. Wmm, I64_PRINTF_ARG(weight_scale));
  2792. valid = 0;
  2793. }
  2794. if (fabs(Wem - Wee) > 1) {
  2795. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2796. valid = 0;
  2797. }
  2798. if (fabs(Wgm - Wgg) > 1) {
  2799. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2800. valid = 0;
  2801. }
  2802. if (fabs(Weg - Wed) > 1) {
  2803. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2804. valid = 0;
  2805. }
  2806. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2807. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2808. I64_PRINTF_ARG(weight_scale), Wmg);
  2809. valid = 0;
  2810. }
  2811. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2812. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2813. I64_PRINTF_ARG(weight_scale), Wme);
  2814. valid = 0;
  2815. }
  2816. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2817. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2818. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2819. valid = 0;
  2820. }
  2821. Wgg /= weight_scale;
  2822. Wgm /= weight_scale;
  2823. Wgd /= weight_scale;
  2824. Wmg /= weight_scale;
  2825. Wmm /= weight_scale;
  2826. Wme /= weight_scale;
  2827. Wmd /= weight_scale;
  2828. Weg /= weight_scale;
  2829. Wem /= weight_scale;
  2830. Wee /= weight_scale;
  2831. Wed /= weight_scale;
  2832. // Then, gather G, M, E, D, T to determine case
  2833. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2834. int is_exit = 0;
  2835. /* Bug #2203: Don't count bad exits as exits for balancing */
  2836. is_exit = rs->is_exit && !rs->is_bad_exit;
  2837. if (rs->has_bandwidth) {
  2838. T += rs->bandwidth_kb;
  2839. if (is_exit && rs->is_possible_guard) {
  2840. D += rs->bandwidth_kb;
  2841. Gtotal += Wgd*rs->bandwidth_kb;
  2842. Mtotal += Wmd*rs->bandwidth_kb;
  2843. Etotal += Wed*rs->bandwidth_kb;
  2844. } else if (is_exit) {
  2845. E += rs->bandwidth_kb;
  2846. Mtotal += Wme*rs->bandwidth_kb;
  2847. Etotal += Wee*rs->bandwidth_kb;
  2848. } else if (rs->is_possible_guard) {
  2849. G += rs->bandwidth_kb;
  2850. Gtotal += Wgg*rs->bandwidth_kb;
  2851. Mtotal += Wmg*rs->bandwidth_kb;
  2852. } else {
  2853. M += rs->bandwidth_kb;
  2854. Mtotal += Wmm*rs->bandwidth_kb;
  2855. }
  2856. } else {
  2857. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2858. routerstatus_describe(rs));
  2859. }
  2860. } SMARTLIST_FOREACH_END(rs);
  2861. // Finally, check equality conditions depending upon case 1, 2 or 3
  2862. // Full equality cases: 1, 3b
  2863. // Partial equality cases: 2b (E=G), 3a (M=E)
  2864. // Fully unknown: 2a
  2865. if (3*E >= T && 3*G >= T) {
  2866. // Case 1: Neither are scarce
  2867. casename = "Case 1";
  2868. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2869. log_warn(LD_DIR,
  2870. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2871. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2872. " T="I64_FORMAT". "
  2873. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2874. casename, Etotal, Mtotal,
  2875. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2876. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2877. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2878. valid = 0;
  2879. }
  2880. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2881. log_warn(LD_DIR,
  2882. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2883. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2884. " T="I64_FORMAT". "
  2885. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2886. casename, Etotal, Gtotal,
  2887. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2888. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2889. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2890. valid = 0;
  2891. }
  2892. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2893. log_warn(LD_DIR,
  2894. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2895. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2896. " T="I64_FORMAT". "
  2897. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2898. casename, Mtotal, Gtotal,
  2899. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2900. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2901. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2902. valid = 0;
  2903. }
  2904. } else if (3*E < T && 3*G < T) {
  2905. int64_t R = MIN(E, G);
  2906. int64_t S = MAX(E, G);
  2907. /*
  2908. * Case 2: Both Guards and Exits are scarce
  2909. * Balance D between E and G, depending upon
  2910. * D capacity and scarcity. Devote no extra
  2911. * bandwidth to middle nodes.
  2912. */
  2913. if (R+D < S) { // Subcase a
  2914. double Rtotal, Stotal;
  2915. if (E < G) {
  2916. Rtotal = Etotal;
  2917. Stotal = Gtotal;
  2918. } else {
  2919. Rtotal = Gtotal;
  2920. Stotal = Etotal;
  2921. }
  2922. casename = "Case 2a";
  2923. // Rtotal < Stotal
  2924. if (Rtotal > Stotal) {
  2925. log_warn(LD_DIR,
  2926. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2927. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2928. " T="I64_FORMAT". "
  2929. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2930. casename, Rtotal, Stotal,
  2931. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2932. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2933. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2934. valid = 0;
  2935. }
  2936. // Rtotal < T/3
  2937. if (3*Rtotal > T) {
  2938. log_warn(LD_DIR,
  2939. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2940. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2941. " D="I64_FORMAT" T="I64_FORMAT". "
  2942. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2943. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2944. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2945. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2946. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2947. valid = 0;
  2948. }
  2949. // Stotal < T/3
  2950. if (3*Stotal > T) {
  2951. log_warn(LD_DIR,
  2952. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2953. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2954. " D="I64_FORMAT" T="I64_FORMAT". "
  2955. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2956. casename, Stotal*3, I64_PRINTF_ARG(T),
  2957. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2958. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2959. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2960. valid = 0;
  2961. }
  2962. // Mtotal > T/3
  2963. if (3*Mtotal < T) {
  2964. log_warn(LD_DIR,
  2965. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2966. I64_FORMAT". "
  2967. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2968. " T="I64_FORMAT". "
  2969. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2970. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2971. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2972. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2973. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2974. valid = 0;
  2975. }
  2976. } else { // Subcase b: R+D > S
  2977. casename = "Case 2b";
  2978. /* Check the rare-M redirect case. */
  2979. if (D != 0 && 3*M < T) {
  2980. casename = "Case 2b (balanced)";
  2981. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2982. log_warn(LD_DIR,
  2983. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2984. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2985. " T="I64_FORMAT". "
  2986. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2987. casename, Etotal, Mtotal,
  2988. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2989. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2990. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2991. valid = 0;
  2992. }
  2993. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2994. log_warn(LD_DIR,
  2995. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2996. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2997. " T="I64_FORMAT". "
  2998. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2999. casename, Etotal, Gtotal,
  3000. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3001. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3002. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3003. valid = 0;
  3004. }
  3005. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  3006. log_warn(LD_DIR,
  3007. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  3008. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3009. " T="I64_FORMAT". "
  3010. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3011. casename, Mtotal, Gtotal,
  3012. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3013. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3014. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3015. valid = 0;
  3016. }
  3017. } else {
  3018. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  3019. log_warn(LD_DIR,
  3020. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  3021. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3022. " T="I64_FORMAT". "
  3023. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3024. casename, Etotal, Gtotal,
  3025. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3026. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3027. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3028. valid = 0;
  3029. }
  3030. }
  3031. }
  3032. } else { // if (E < T/3 || G < T/3) {
  3033. int64_t S = MIN(E, G);
  3034. int64_t NS = MAX(E, G);
  3035. if (3*(S+D) < T) { // Subcase a:
  3036. double Stotal;
  3037. double NStotal;
  3038. if (G < E) {
  3039. casename = "Case 3a (G scarce)";
  3040. Stotal = Gtotal;
  3041. NStotal = Etotal;
  3042. } else { // if (G >= E) {
  3043. casename = "Case 3a (E scarce)";
  3044. NStotal = Gtotal;
  3045. Stotal = Etotal;
  3046. }
  3047. // Stotal < T/3
  3048. if (3*Stotal > T) {
  3049. log_warn(LD_DIR,
  3050. "Bw Weight Failure for %s: 3*Stotal %f > T "
  3051. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  3052. " D="I64_FORMAT" T="I64_FORMAT". "
  3053. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3054. casename, Stotal*3, I64_PRINTF_ARG(T),
  3055. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3056. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3057. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3058. valid = 0;
  3059. }
  3060. if (NS >= M) {
  3061. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  3062. log_warn(LD_DIR,
  3063. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  3064. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3065. " T="I64_FORMAT". "
  3066. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3067. casename, NStotal, Mtotal,
  3068. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3069. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3070. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3071. valid = 0;
  3072. }
  3073. } else {
  3074. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  3075. if (3*NStotal < T) {
  3076. log_warn(LD_DIR,
  3077. "Bw Weight Failure for %s: 3*NStotal %f < T "
  3078. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  3079. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  3080. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3081. casename, NStotal*3, I64_PRINTF_ARG(T),
  3082. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3083. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3084. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3085. valid = 0;
  3086. }
  3087. }
  3088. } else { // Subcase b: S+D >= T/3
  3089. casename = "Case 3b";
  3090. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  3091. log_warn(LD_DIR,
  3092. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  3093. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3094. " T="I64_FORMAT". "
  3095. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3096. casename, Etotal, Mtotal,
  3097. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3098. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3099. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3100. valid = 0;
  3101. }
  3102. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  3103. log_warn(LD_DIR,
  3104. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  3105. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3106. " T="I64_FORMAT". "
  3107. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3108. casename, Etotal, Gtotal,
  3109. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3110. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3111. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3112. valid = 0;
  3113. }
  3114. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  3115. log_warn(LD_DIR,
  3116. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  3117. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3118. " T="I64_FORMAT". "
  3119. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3120. casename, Mtotal, Gtotal,
  3121. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3122. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3123. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3124. valid = 0;
  3125. }
  3126. }
  3127. }
  3128. if (valid)
  3129. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  3130. casename);
  3131. return valid;
  3132. }
  3133. /** Parse and extract all SR commits from <b>tokens</b> and place them in
  3134. * <b>ns</b>. */
  3135. static void
  3136. extract_shared_random_commits(networkstatus_t *ns, smartlist_t *tokens)
  3137. {
  3138. smartlist_t *chunks = NULL;
  3139. tor_assert(ns);
  3140. tor_assert(tokens);
  3141. /* Commits are only present in a vote. */
  3142. tor_assert(ns->type == NS_TYPE_VOTE);
  3143. ns->sr_info.commits = smartlist_new();
  3144. smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
  3145. /* It's normal that a vote might contain no commits even if it participates
  3146. * in the SR protocol. Don't treat it as an error. */
  3147. if (commits == NULL) {
  3148. goto end;
  3149. }
  3150. /* Parse the commit. We do NO validation of number of arguments or ordering
  3151. * for forward compatibility, it's the parse commit job to inform us if it's
  3152. * supported or not. */
  3153. chunks = smartlist_new();
  3154. SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
  3155. /* Extract all arguments and put them in the chunks list. */
  3156. for (int i = 0; i < tok->n_args; i++) {
  3157. smartlist_add(chunks, tok->args[i]);
  3158. }
  3159. sr_commit_t *commit = sr_parse_commit(chunks);
  3160. smartlist_clear(chunks);
  3161. if (commit == NULL) {
  3162. /* Get voter identity so we can warn that this dirauth vote contains
  3163. * commit we can't parse. */
  3164. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  3165. tor_assert(voter);
  3166. log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
  3167. escaped(tok->object_body),
  3168. hex_str(voter->identity_digest,
  3169. sizeof(voter->identity_digest)));
  3170. /* Commitment couldn't be parsed. Continue onto the next commit because
  3171. * this one could be unsupported for instance. */
  3172. continue;
  3173. }
  3174. /* Add newly created commit object to the vote. */
  3175. smartlist_add(ns->sr_info.commits, commit);
  3176. } SMARTLIST_FOREACH_END(tok);
  3177. end:
  3178. smartlist_free(chunks);
  3179. smartlist_free(commits);
  3180. }
  3181. /** Check if a shared random value of type <b>srv_type</b> is in
  3182. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  3183. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  3184. * it's the responsibility of the caller to free it. */
  3185. static int
  3186. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  3187. sr_srv_t **srv_out)
  3188. {
  3189. int ret = -1;
  3190. directory_token_t *tok;
  3191. sr_srv_t *srv = NULL;
  3192. smartlist_t *chunks;
  3193. tor_assert(tokens);
  3194. chunks = smartlist_new();
  3195. tok = find_opt_by_keyword(tokens, srv_type);
  3196. if (!tok) {
  3197. /* That's fine, no SRV is allowed. */
  3198. ret = 0;
  3199. goto end;
  3200. }
  3201. for (int i = 0; i < tok->n_args; i++) {
  3202. smartlist_add(chunks, tok->args[i]);
  3203. }
  3204. srv = sr_parse_srv(chunks);
  3205. if (srv == NULL) {
  3206. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  3207. goto end;
  3208. }
  3209. /* All is good. */
  3210. *srv_out = srv;
  3211. ret = 0;
  3212. end:
  3213. smartlist_free(chunks);
  3214. return ret;
  3215. }
  3216. /** Extract any shared random values found in <b>tokens</b> and place them in
  3217. * the networkstatus <b>ns</b>. */
  3218. static void
  3219. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  3220. {
  3221. const char *voter_identity;
  3222. networkstatus_voter_info_t *voter;
  3223. tor_assert(ns);
  3224. tor_assert(tokens);
  3225. /* Can be only one of them else code flow. */
  3226. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  3227. if (ns->type == NS_TYPE_VOTE) {
  3228. voter = smartlist_get(ns->voters, 0);
  3229. tor_assert(voter);
  3230. voter_identity = hex_str(voter->identity_digest,
  3231. sizeof(voter->identity_digest));
  3232. } else {
  3233. /* Consensus has multiple voters so no specific voter. */
  3234. voter_identity = "consensus";
  3235. }
  3236. /* We extract both and on error, everything is stopped because it means
  3237. * the votes is malformed for the shared random value(s). */
  3238. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  3239. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  3240. voter_identity);
  3241. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  3242. }
  3243. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  3244. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  3245. voter_identity);
  3246. }
  3247. }
  3248. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  3249. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  3250. networkstatus_t *
  3251. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  3252. networkstatus_type_t ns_type)
  3253. {
  3254. smartlist_t *tokens = smartlist_new();
  3255. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  3256. networkstatus_voter_info_t *voter = NULL;
  3257. networkstatus_t *ns = NULL;
  3258. common_digests_t ns_digests;
  3259. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  3260. directory_token_t *tok;
  3261. struct in_addr in;
  3262. int i, inorder, n_signatures = 0;
  3263. memarea_t *area = NULL, *rs_area = NULL;
  3264. consensus_flavor_t flav = FLAV_NS;
  3265. char *last_kwd=NULL;
  3266. tor_assert(s);
  3267. if (eos_out)
  3268. *eos_out = NULL;
  3269. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  3270. log_warn(LD_DIR, "Unable to compute digest of network-status");
  3271. goto err;
  3272. }
  3273. area = memarea_new();
  3274. end_of_header = find_start_of_next_routerstatus(s);
  3275. if (tokenize_string(area, s, end_of_header, tokens,
  3276. (ns_type == NS_TYPE_CONSENSUS) ?
  3277. networkstatus_consensus_token_table :
  3278. networkstatus_token_table, 0)) {
  3279. log_warn(LD_DIR, "Error tokenizing network-status header");
  3280. goto err;
  3281. }
  3282. ns = tor_malloc_zero(sizeof(networkstatus_t));
  3283. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  3284. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  3285. tor_assert(tok);
  3286. if (tok->n_args > 1) {
  3287. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  3288. if (flavor < 0) {
  3289. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  3290. escaped(tok->args[1]));
  3291. goto err;
  3292. }
  3293. ns->flavor = flav = flavor;
  3294. }
  3295. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  3296. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  3297. goto err;
  3298. }
  3299. if (ns_type != NS_TYPE_CONSENSUS) {
  3300. const char *end_of_cert = NULL;
  3301. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  3302. goto err;
  3303. ++cert;
  3304. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  3305. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  3306. goto err;
  3307. }
  3308. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  3309. tor_assert(tok->n_args);
  3310. if (!strcmp(tok->args[0], "vote")) {
  3311. ns->type = NS_TYPE_VOTE;
  3312. } else if (!strcmp(tok->args[0], "consensus")) {
  3313. ns->type = NS_TYPE_CONSENSUS;
  3314. } else if (!strcmp(tok->args[0], "opinion")) {
  3315. ns->type = NS_TYPE_OPINION;
  3316. } else {
  3317. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  3318. escaped(tok->args[0]));
  3319. goto err;
  3320. }
  3321. if (ns_type != ns->type) {
  3322. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  3323. goto err;
  3324. }
  3325. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  3326. tok = find_by_keyword(tokens, K_PUBLISHED);
  3327. if (parse_iso_time(tok->args[0], &ns->published))
  3328. goto err;
  3329. ns->supported_methods = smartlist_new();
  3330. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  3331. if (tok) {
  3332. for (i=0; i < tok->n_args; ++i)
  3333. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  3334. } else {
  3335. smartlist_add(ns->supported_methods, tor_strdup("1"));
  3336. }
  3337. } else {
  3338. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  3339. if (tok) {
  3340. int num_ok;
  3341. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  3342. &num_ok, NULL);
  3343. if (!num_ok)
  3344. goto err;
  3345. } else {
  3346. ns->consensus_method = 1;
  3347. }
  3348. }
  3349. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
  3350. ns->recommended_client_protocols = tor_strdup(tok->args[0]);
  3351. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
  3352. ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
  3353. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
  3354. ns->required_client_protocols = tor_strdup(tok->args[0]);
  3355. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
  3356. ns->required_relay_protocols = tor_strdup(tok->args[0]);
  3357. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3358. if (parse_iso_time(tok->args[0], &ns->valid_after))
  3359. goto err;
  3360. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3361. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  3362. goto err;
  3363. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3364. if (parse_iso_time(tok->args[0], &ns->valid_until))
  3365. goto err;
  3366. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  3367. tor_assert(tok->n_args >= 2);
  3368. {
  3369. int ok;
  3370. ns->vote_seconds =
  3371. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  3372. if (!ok)
  3373. goto err;
  3374. ns->dist_seconds =
  3375. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  3376. if (!ok)
  3377. goto err;
  3378. }
  3379. if (ns->valid_after +
  3380. (get_options()->TestingTorNetwork ?
  3381. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  3382. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  3383. goto err;
  3384. }
  3385. if (ns->valid_after +
  3386. (get_options()->TestingTorNetwork ?
  3387. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  3388. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  3389. goto err;
  3390. }
  3391. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  3392. log_warn(LD_DIR, "Vote seconds is too short");
  3393. goto err;
  3394. }
  3395. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  3396. log_warn(LD_DIR, "Dist seconds is too short");
  3397. goto err;
  3398. }
  3399. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  3400. ns->client_versions = tor_strdup(tok->args[0]);
  3401. }
  3402. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  3403. ns->server_versions = tor_strdup(tok->args[0]);
  3404. }
  3405. {
  3406. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  3407. ns->package_lines = smartlist_new();
  3408. if (package_lst) {
  3409. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  3410. smartlist_add(ns->package_lines, tor_strdup(t->args[0])));
  3411. }
  3412. smartlist_free(package_lst);
  3413. }
  3414. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  3415. ns->known_flags = smartlist_new();
  3416. inorder = 1;
  3417. for (i = 0; i < tok->n_args; ++i) {
  3418. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  3419. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  3420. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3421. inorder = 0;
  3422. }
  3423. }
  3424. if (!inorder) {
  3425. log_warn(LD_DIR, "known-flags not in order");
  3426. goto err;
  3427. }
  3428. if (ns->type != NS_TYPE_CONSENSUS &&
  3429. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  3430. /* If we allowed more than 64 flags in votes, then parsing them would make
  3431. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  3432. * bit-shift. This is only for votes and opinions: consensus users don't
  3433. * care about flags they don't recognize, and so don't build a bitfield
  3434. * for them. */
  3435. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  3436. goto err;
  3437. }
  3438. tok = find_opt_by_keyword(tokens, K_PARAMS);
  3439. if (tok) {
  3440. int any_dups = 0;
  3441. inorder = 1;
  3442. ns->net_params = smartlist_new();
  3443. for (i = 0; i < tok->n_args; ++i) {
  3444. int ok=0;
  3445. char *eq = strchr(tok->args[i], '=');
  3446. size_t eq_pos;
  3447. if (!eq) {
  3448. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3449. goto err;
  3450. }
  3451. eq_pos = eq-tok->args[i];
  3452. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3453. if (!ok) {
  3454. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3455. goto err;
  3456. }
  3457. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  3458. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3459. inorder = 0;
  3460. }
  3461. if (last_kwd && eq_pos == strlen(last_kwd) &&
  3462. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  3463. log_warn(LD_DIR, "Duplicate value for %s parameter",
  3464. escaped(tok->args[i]));
  3465. any_dups = 1;
  3466. }
  3467. tor_free(last_kwd);
  3468. last_kwd = tor_strndup(tok->args[i], eq_pos);
  3469. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  3470. }
  3471. if (!inorder) {
  3472. log_warn(LD_DIR, "params not in order");
  3473. goto err;
  3474. }
  3475. if (any_dups) {
  3476. log_warn(LD_DIR, "Duplicate in parameters");
  3477. goto err;
  3478. }
  3479. }
  3480. ns->voters = smartlist_new();
  3481. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3482. tok = _tok;
  3483. if (tok->tp == K_DIR_SOURCE) {
  3484. tor_assert(tok->n_args >= 6);
  3485. if (voter)
  3486. smartlist_add(ns->voters, voter);
  3487. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  3488. voter->sigs = smartlist_new();
  3489. if (ns->type != NS_TYPE_CONSENSUS)
  3490. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  3491. voter->nickname = tor_strdup(tok->args[0]);
  3492. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  3493. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  3494. tok->args[1], HEX_DIGEST_LEN)
  3495. != sizeof(voter->identity_digest)) {
  3496. log_warn(LD_DIR, "Error decoding identity digest %s in "
  3497. "network-status document.", escaped(tok->args[1]));
  3498. goto err;
  3499. }
  3500. if (ns->type != NS_TYPE_CONSENSUS &&
  3501. tor_memneq(ns->cert->cache_info.identity_digest,
  3502. voter->identity_digest, DIGEST_LEN)) {
  3503. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  3504. goto err;
  3505. }
  3506. if (ns->type != NS_TYPE_CONSENSUS) {
  3507. if (authority_cert_is_blacklisted(ns->cert)) {
  3508. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  3509. "signing key %s",
  3510. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  3511. goto err;
  3512. }
  3513. }
  3514. voter->address = tor_strdup(tok->args[2]);
  3515. if (!tor_inet_aton(tok->args[3], &in)) {
  3516. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  3517. escaped(tok->args[3]));
  3518. goto err;
  3519. }
  3520. voter->addr = ntohl(in.s_addr);
  3521. int ok;
  3522. voter->dir_port = (uint16_t)
  3523. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  3524. if (!ok)
  3525. goto err;
  3526. voter->or_port = (uint16_t)
  3527. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  3528. if (!ok)
  3529. goto err;
  3530. } else if (tok->tp == K_CONTACT) {
  3531. if (!voter || voter->contact) {
  3532. log_warn(LD_DIR, "contact element is out of place.");
  3533. goto err;
  3534. }
  3535. voter->contact = tor_strdup(tok->args[0]);
  3536. } else if (tok->tp == K_VOTE_DIGEST) {
  3537. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  3538. tor_assert(tok->n_args >= 1);
  3539. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  3540. log_warn(LD_DIR, "vote-digest element is out of place.");
  3541. goto err;
  3542. }
  3543. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  3544. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  3545. tok->args[0], HEX_DIGEST_LEN)
  3546. != sizeof(voter->vote_digest)) {
  3547. log_warn(LD_DIR, "Error decoding vote digest %s in "
  3548. "network-status consensus.", escaped(tok->args[0]));
  3549. goto err;
  3550. }
  3551. }
  3552. } SMARTLIST_FOREACH_END(_tok);
  3553. if (voter) {
  3554. smartlist_add(ns->voters, voter);
  3555. voter = NULL;
  3556. }
  3557. if (smartlist_len(ns->voters) == 0) {
  3558. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  3559. goto err;
  3560. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  3561. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  3562. goto err;
  3563. }
  3564. if (ns->type != NS_TYPE_CONSENSUS &&
  3565. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  3566. int bad = 1;
  3567. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  3568. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  3569. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  3570. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  3571. bad = 1;
  3572. else
  3573. bad = 0;
  3574. }
  3575. if (bad) {
  3576. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  3577. escaped(tok->args[0]));
  3578. }
  3579. }
  3580. /* If this is a vote document, check if information about the shared
  3581. randomness protocol is included, and extract it. */
  3582. if (ns->type == NS_TYPE_VOTE) {
  3583. /* Does this authority participates in the SR protocol? */
  3584. tok = find_opt_by_keyword(tokens, K_SR_FLAG);
  3585. if (tok) {
  3586. ns->sr_info.participate = 1;
  3587. /* Get the SR commitments and reveals from the vote. */
  3588. extract_shared_random_commits(ns, tokens);
  3589. }
  3590. }
  3591. /* For both a vote and consensus, extract the shared random values. */
  3592. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  3593. extract_shared_random_srvs(ns, tokens);
  3594. }
  3595. /* Parse routerstatus lines. */
  3596. rs_tokens = smartlist_new();
  3597. rs_area = memarea_new();
  3598. s = end_of_header;
  3599. ns->routerstatus_list = smartlist_new();
  3600. while (!strcmpstart(s, "r ")) {
  3601. if (ns->type != NS_TYPE_CONSENSUS) {
  3602. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3603. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  3604. rs, 0, 0))
  3605. smartlist_add(ns->routerstatus_list, rs);
  3606. else {
  3607. tor_free(rs->version);
  3608. tor_free(rs);
  3609. }
  3610. } else {
  3611. routerstatus_t *rs;
  3612. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  3613. NULL, NULL,
  3614. ns->consensus_method,
  3615. flav))) {
  3616. /* Use exponential-backoff scheduling when downloading microdescs */
  3617. rs->dl_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
  3618. smartlist_add(ns->routerstatus_list, rs);
  3619. }
  3620. }
  3621. }
  3622. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  3623. routerstatus_t *rs1, *rs2;
  3624. if (ns->type != NS_TYPE_CONSENSUS) {
  3625. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  3626. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  3627. rs1 = &a->status; rs2 = &b->status;
  3628. } else {
  3629. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  3630. rs2 = smartlist_get(ns->routerstatus_list, i);
  3631. }
  3632. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  3633. >= 0) {
  3634. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  3635. goto err;
  3636. }
  3637. }
  3638. if (ns_type != NS_TYPE_CONSENSUS) {
  3639. digest256map_t *ed_id_map = digest256map_new();
  3640. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  3641. vrs) {
  3642. if (! vrs->has_ed25519_listing ||
  3643. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  3644. continue;
  3645. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  3646. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  3647. "unique");
  3648. digest256map_free(ed_id_map, NULL);
  3649. goto err;
  3650. }
  3651. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  3652. } SMARTLIST_FOREACH_END(vrs);
  3653. digest256map_free(ed_id_map, NULL);
  3654. }
  3655. /* Parse footer; check signature. */
  3656. footer_tokens = smartlist_new();
  3657. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  3658. ++end_of_footer;
  3659. else
  3660. end_of_footer = s + strlen(s);
  3661. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  3662. networkstatus_vote_footer_token_table, 0)) {
  3663. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  3664. goto err;
  3665. }
  3666. {
  3667. int found_sig = 0;
  3668. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3669. tok = _tok;
  3670. if (tok->tp == K_DIRECTORY_SIGNATURE)
  3671. found_sig = 1;
  3672. else if (found_sig) {
  3673. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  3674. goto err;
  3675. }
  3676. } SMARTLIST_FOREACH_END(_tok);
  3677. }
  3678. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  3679. if (tok != smartlist_get(footer_tokens, 0)) {
  3680. log_warn(LD_DIR, "Misplaced directory-footer token");
  3681. goto err;
  3682. }
  3683. }
  3684. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  3685. if (tok) {
  3686. ns->weight_params = smartlist_new();
  3687. for (i = 0; i < tok->n_args; ++i) {
  3688. int ok=0;
  3689. char *eq = strchr(tok->args[i], '=');
  3690. if (!eq) {
  3691. log_warn(LD_DIR, "Bad element '%s' in weight params",
  3692. escaped(tok->args[i]));
  3693. goto err;
  3694. }
  3695. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3696. if (!ok) {
  3697. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3698. goto err;
  3699. }
  3700. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  3701. }
  3702. }
  3703. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3704. char declared_identity[DIGEST_LEN];
  3705. networkstatus_voter_info_t *v;
  3706. document_signature_t *sig;
  3707. const char *id_hexdigest = NULL;
  3708. const char *sk_hexdigest = NULL;
  3709. digest_algorithm_t alg = DIGEST_SHA1;
  3710. tok = _tok;
  3711. if (tok->tp != K_DIRECTORY_SIGNATURE)
  3712. continue;
  3713. tor_assert(tok->n_args >= 2);
  3714. if (tok->n_args == 2) {
  3715. id_hexdigest = tok->args[0];
  3716. sk_hexdigest = tok->args[1];
  3717. } else {
  3718. const char *algname = tok->args[0];
  3719. int a;
  3720. id_hexdigest = tok->args[1];
  3721. sk_hexdigest = tok->args[2];
  3722. a = crypto_digest_algorithm_parse_name(algname);
  3723. if (a<0) {
  3724. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  3725. escaped(algname));
  3726. continue;
  3727. }
  3728. alg = a;
  3729. }
  3730. if (!tok->object_type ||
  3731. strcmp(tok->object_type, "SIGNATURE") ||
  3732. tok->object_size < 128 || tok->object_size > 512) {
  3733. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3734. goto err;
  3735. }
  3736. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3737. base16_decode(declared_identity, sizeof(declared_identity),
  3738. id_hexdigest, HEX_DIGEST_LEN)
  3739. != sizeof(declared_identity)) {
  3740. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3741. "network-status document.", escaped(id_hexdigest));
  3742. goto err;
  3743. }
  3744. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3745. log_warn(LD_DIR, "ID on signature on network-status document does "
  3746. "not match any declared directory source.");
  3747. goto err;
  3748. }
  3749. sig = tor_malloc_zero(sizeof(document_signature_t));
  3750. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3751. sig->alg = alg;
  3752. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3753. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3754. sk_hexdigest, HEX_DIGEST_LEN)
  3755. != sizeof(sig->signing_key_digest)) {
  3756. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3757. "network-status document.", escaped(sk_hexdigest));
  3758. tor_free(sig);
  3759. goto err;
  3760. }
  3761. if (ns->type != NS_TYPE_CONSENSUS) {
  3762. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3763. DIGEST_LEN)) {
  3764. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3765. "network-status vote.");
  3766. tor_free(sig);
  3767. goto err;
  3768. }
  3769. }
  3770. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3771. /* We already parsed a vote with this algorithm from this voter. Use the
  3772. first one. */
  3773. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3774. "that contains two signatures from the same voter with the same "
  3775. "algorithm. Ignoring the second signature.");
  3776. tor_free(sig);
  3777. continue;
  3778. }
  3779. if (ns->type != NS_TYPE_CONSENSUS) {
  3780. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3781. tok, ns->cert->signing_key, 0,
  3782. "network-status document")) {
  3783. tor_free(sig);
  3784. goto err;
  3785. }
  3786. sig->good_signature = 1;
  3787. } else {
  3788. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3789. tor_free(sig);
  3790. goto err;
  3791. }
  3792. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3793. sig->signature_len = (int) tok->object_size;
  3794. }
  3795. smartlist_add(v->sigs, sig);
  3796. ++n_signatures;
  3797. } SMARTLIST_FOREACH_END(_tok);
  3798. if (! n_signatures) {
  3799. log_warn(LD_DIR, "No signatures on networkstatus document.");
  3800. goto err;
  3801. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3802. log_warn(LD_DIR, "Received more than one signature on a "
  3803. "network-status vote.");
  3804. goto err;
  3805. }
  3806. if (eos_out)
  3807. *eos_out = end_of_footer;
  3808. goto done;
  3809. err:
  3810. dump_desc(s_dup, "v3 networkstatus");
  3811. networkstatus_vote_free(ns);
  3812. ns = NULL;
  3813. done:
  3814. if (tokens) {
  3815. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3816. smartlist_free(tokens);
  3817. }
  3818. if (voter) {
  3819. if (voter->sigs) {
  3820. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3821. document_signature_free(sig));
  3822. smartlist_free(voter->sigs);
  3823. }
  3824. tor_free(voter->nickname);
  3825. tor_free(voter->address);
  3826. tor_free(voter->contact);
  3827. tor_free(voter);
  3828. }
  3829. if (rs_tokens) {
  3830. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3831. smartlist_free(rs_tokens);
  3832. }
  3833. if (footer_tokens) {
  3834. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3835. smartlist_free(footer_tokens);
  3836. }
  3837. if (area) {
  3838. DUMP_AREA(area, "v3 networkstatus");
  3839. memarea_drop_all(area);
  3840. }
  3841. if (rs_area)
  3842. memarea_drop_all(rs_area);
  3843. tor_free(last_kwd);
  3844. return ns;
  3845. }
  3846. /** Return the common_digests_t that holds the digests of the
  3847. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3848. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  3849. * neeeded. */
  3850. static common_digests_t *
  3851. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3852. {
  3853. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  3854. if (!d) {
  3855. d = tor_malloc_zero(sizeof(common_digests_t));
  3856. strmap_set(sigs->digests, flavor_name, d);
  3857. }
  3858. return d;
  3859. }
  3860. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3861. * networkstatus according to the detached signatures document <b>sigs</b>,
  3862. * allocating a new common_digests_t as neeeded. */
  3863. static smartlist_t *
  3864. detached_get_signatures(ns_detached_signatures_t *sigs,
  3865. const char *flavor_name)
  3866. {
  3867. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3868. if (!sl) {
  3869. sl = smartlist_new();
  3870. strmap_set(sigs->signatures, flavor_name, sl);
  3871. }
  3872. return sl;
  3873. }
  3874. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3875. * <b>eos</b> and return the result. Return -1 on failure. */
  3876. ns_detached_signatures_t *
  3877. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3878. {
  3879. /* XXXX there is too much duplicate shared between this function and
  3880. * networkstatus_parse_vote_from_string(). */
  3881. directory_token_t *tok;
  3882. memarea_t *area = NULL;
  3883. common_digests_t *digests;
  3884. smartlist_t *tokens = smartlist_new();
  3885. ns_detached_signatures_t *sigs =
  3886. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3887. sigs->digests = strmap_new();
  3888. sigs->signatures = strmap_new();
  3889. if (!eos)
  3890. eos = s + strlen(s);
  3891. area = memarea_new();
  3892. if (tokenize_string(area,s, eos, tokens,
  3893. networkstatus_detached_signature_token_table, 0)) {
  3894. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3895. goto err;
  3896. }
  3897. /* Grab all the digest-like tokens. */
  3898. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3899. const char *algname;
  3900. digest_algorithm_t alg;
  3901. const char *flavor;
  3902. const char *hexdigest;
  3903. size_t expected_length, digest_length;
  3904. tok = _tok;
  3905. if (tok->tp == K_CONSENSUS_DIGEST) {
  3906. algname = "sha1";
  3907. alg = DIGEST_SHA1;
  3908. flavor = "ns";
  3909. hexdigest = tok->args[0];
  3910. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3911. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3912. if (a<0) {
  3913. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3914. continue;
  3915. }
  3916. alg = (digest_algorithm_t) a;
  3917. flavor = tok->args[0];
  3918. algname = tok->args[1];
  3919. hexdigest = tok->args[2];
  3920. } else {
  3921. continue;
  3922. }
  3923. digest_length = crypto_digest_algorithm_get_length(alg);
  3924. expected_length = digest_length * 2; /* hex encoding */
  3925. if (strlen(hexdigest) != expected_length) {
  3926. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3927. "networkstatus signatures");
  3928. goto err;
  3929. }
  3930. digests = detached_get_digests(sigs, flavor);
  3931. tor_assert(digests);
  3932. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  3933. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3934. "signatures document", flavor, algname);
  3935. continue;
  3936. }
  3937. if (base16_decode(digests->d[alg], digest_length,
  3938. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  3939. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3940. "networkstatus signatures");
  3941. goto err;
  3942. }
  3943. } SMARTLIST_FOREACH_END(_tok);
  3944. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3945. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3946. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3947. goto err;
  3948. }
  3949. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3950. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3951. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3952. goto err;
  3953. }
  3954. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3955. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3956. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3957. goto err;
  3958. }
  3959. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3960. const char *id_hexdigest;
  3961. const char *sk_hexdigest;
  3962. const char *algname;
  3963. const char *flavor;
  3964. digest_algorithm_t alg;
  3965. char id_digest[DIGEST_LEN];
  3966. char sk_digest[DIGEST_LEN];
  3967. smartlist_t *siglist;
  3968. document_signature_t *sig;
  3969. int is_duplicate;
  3970. tok = _tok;
  3971. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3972. tor_assert(tok->n_args >= 2);
  3973. flavor = "ns";
  3974. algname = "sha1";
  3975. id_hexdigest = tok->args[0];
  3976. sk_hexdigest = tok->args[1];
  3977. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3978. tor_assert(tok->n_args >= 4);
  3979. flavor = tok->args[0];
  3980. algname = tok->args[1];
  3981. id_hexdigest = tok->args[2];
  3982. sk_hexdigest = tok->args[3];
  3983. } else {
  3984. continue;
  3985. }
  3986. {
  3987. int a = crypto_digest_algorithm_parse_name(algname);
  3988. if (a<0) {
  3989. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3990. continue;
  3991. }
  3992. alg = (digest_algorithm_t) a;
  3993. }
  3994. if (!tok->object_type ||
  3995. strcmp(tok->object_type, "SIGNATURE") ||
  3996. tok->object_size < 128 || tok->object_size > 512) {
  3997. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3998. goto err;
  3999. }
  4000. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  4001. base16_decode(id_digest, sizeof(id_digest),
  4002. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  4003. log_warn(LD_DIR, "Error decoding declared identity %s in "
  4004. "network-status vote.", escaped(id_hexdigest));
  4005. goto err;
  4006. }
  4007. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  4008. base16_decode(sk_digest, sizeof(sk_digest),
  4009. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  4010. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  4011. "network-status vote.", escaped(sk_hexdigest));
  4012. goto err;
  4013. }
  4014. siglist = detached_get_signatures(sigs, flavor);
  4015. is_duplicate = 0;
  4016. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  4017. if (dsig->alg == alg &&
  4018. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  4019. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  4020. is_duplicate = 1;
  4021. }
  4022. });
  4023. if (is_duplicate) {
  4024. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  4025. "found.");
  4026. continue;
  4027. }
  4028. sig = tor_malloc_zero(sizeof(document_signature_t));
  4029. sig->alg = alg;
  4030. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  4031. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  4032. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  4033. tor_free(sig);
  4034. goto err;
  4035. }
  4036. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  4037. sig->signature_len = (int) tok->object_size;
  4038. smartlist_add(siglist, sig);
  4039. } SMARTLIST_FOREACH_END(_tok);
  4040. goto done;
  4041. err:
  4042. ns_detached_signatures_free(sigs);
  4043. sigs = NULL;
  4044. done:
  4045. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4046. smartlist_free(tokens);
  4047. if (area) {
  4048. DUMP_AREA(area, "detached signatures");
  4049. memarea_drop_all(area);
  4050. }
  4051. return sigs;
  4052. }
  4053. /** Parse the addr policy in the string <b>s</b> and return it. If
  4054. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  4055. * ADDR_POLICY_REJECT) for items that specify no action.
  4056. *
  4057. * Returns NULL on policy errors.
  4058. *
  4059. * Set *<b>malformed_list</b> to true if the entire policy list should be
  4060. * discarded. Otherwise, set it to false, and only this item should be ignored
  4061. * on error - the rest of the policy list can continue to be processed and
  4062. * used.
  4063. *
  4064. * The addr_policy_t returned by this function can have its address set to
  4065. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  4066. * of AF_INET and AF_INET6 items.
  4067. */
  4068. MOCK_IMPL(addr_policy_t *,
  4069. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  4070. int *malformed_list))
  4071. {
  4072. directory_token_t *tok = NULL;
  4073. const char *cp, *eos;
  4074. /* Longest possible policy is
  4075. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  4076. * which contains a max-length IPv6 address, plus 26 characters.
  4077. * But note that there can be an arbitrary amount of space between the
  4078. * accept and the address:mask/port element.
  4079. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  4080. * IPv6 address. But making the buffer shorter might cause valid long lines,
  4081. * which parsed in previous versions, to fail to parse in new versions.
  4082. * (These lines would have to have excessive amounts of whitespace.) */
  4083. char line[TOR_ADDR_BUF_LEN*2 + 32];
  4084. addr_policy_t *r;
  4085. memarea_t *area = NULL;
  4086. tor_assert(malformed_list);
  4087. *malformed_list = 0;
  4088. s = eat_whitespace(s);
  4089. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  4090. * and ":" (port separator) are ambiguous */
  4091. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  4092. if (tor_snprintf(line, sizeof(line), "%s %s",
  4093. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  4094. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  4095. return NULL;
  4096. }
  4097. cp = line;
  4098. tor_strlower(line);
  4099. } else { /* assume an already well-formed address policy line */
  4100. cp = s;
  4101. }
  4102. eos = cp + strlen(cp);
  4103. area = memarea_new();
  4104. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  4105. if (tok->tp == ERR_) {
  4106. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  4107. goto err;
  4108. }
  4109. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  4110. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  4111. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  4112. goto err;
  4113. }
  4114. /* Use the extended interpretation of accept/reject *,
  4115. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  4116. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  4117. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  4118. if (!r) {
  4119. goto err;
  4120. }
  4121. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  4122. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  4123. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  4124. * either an IPv4 or IPv6 address. */
  4125. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4126. tor_addr_family(&r->addr) != AF_INET6) {
  4127. /* This is a non-fatal error, just ignore this one entry. */
  4128. *malformed_list = 0;
  4129. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  4130. "exit policy. Ignoring, but continuing to parse rules. (Use "
  4131. "accept/reject with IPv4 addresses.)",
  4132. tok->n_args == 1 ? tok->args[0] : "");
  4133. addr_policy_free(r);
  4134. r = NULL;
  4135. goto done;
  4136. }
  4137. goto done;
  4138. err:
  4139. *malformed_list = 1;
  4140. r = NULL;
  4141. done:
  4142. token_clear(tok);
  4143. if (area) {
  4144. DUMP_AREA(area, "policy item");
  4145. memarea_drop_all(area);
  4146. }
  4147. return r;
  4148. }
  4149. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  4150. * <b>router</b>. Return 0 on success, -1 on failure. */
  4151. static int
  4152. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  4153. {
  4154. addr_policy_t *newe;
  4155. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  4156. newe = router_parse_addr_policy(tok, 0);
  4157. if (!newe)
  4158. return -1;
  4159. if (! router->exit_policy)
  4160. router->exit_policy = smartlist_new();
  4161. /* Ensure that in descriptors, accept/reject fields are followed by
  4162. * IPv4 addresses, and accept6/reject6 fields are followed by
  4163. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  4164. * accept/reject followed by IPv6. */
  4165. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4166. tor_addr_family(&newe->addr) == AF_INET)
  4167. ||
  4168. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  4169. tor_addr_family(&newe->addr) == AF_INET6)) {
  4170. /* There's nothing the user can do about other relays' descriptors,
  4171. * so we don't provide usage advice here. */
  4172. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  4173. "policy '%s'. Discarding entire router descriptor.",
  4174. tok->n_args == 1 ? tok->args[0] : "");
  4175. addr_policy_free(newe);
  4176. return -1;
  4177. }
  4178. smartlist_add(router->exit_policy, newe);
  4179. return 0;
  4180. }
  4181. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  4182. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  4183. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  4184. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  4185. * policies */
  4186. static addr_policy_t *
  4187. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  4188. {
  4189. addr_policy_t newe;
  4190. char *arg;
  4191. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  4192. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  4193. if (tok->n_args != 1)
  4194. return NULL;
  4195. arg = tok->args[0];
  4196. if (!strcmpstart(arg,"private"))
  4197. return router_parse_addr_policy_private(tok);
  4198. memset(&newe, 0, sizeof(newe));
  4199. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4200. newe.policy_type = ADDR_POLICY_REJECT;
  4201. else
  4202. newe.policy_type = ADDR_POLICY_ACCEPT;
  4203. /* accept6/reject6 * produces an IPv6 wildcard address only.
  4204. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  4205. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  4206. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  4207. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  4208. }
  4209. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  4210. &newe.prt_min, &newe.prt_max) < 0) {
  4211. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  4212. return NULL;
  4213. }
  4214. return addr_policy_get_canonical_entry(&newe);
  4215. }
  4216. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  4217. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  4218. * router descriptors until earlier versions are obsolete.
  4219. *
  4220. * accept/reject and accept6/reject6 private all produce rules for both
  4221. * IPv4 and IPv6 addresses.
  4222. */
  4223. static addr_policy_t *
  4224. router_parse_addr_policy_private(directory_token_t *tok)
  4225. {
  4226. const char *arg;
  4227. uint16_t port_min, port_max;
  4228. addr_policy_t result;
  4229. arg = tok->args[0];
  4230. if (strcmpstart(arg, "private"))
  4231. return NULL;
  4232. arg += strlen("private");
  4233. arg = (char*) eat_whitespace(arg);
  4234. if (!arg || *arg != ':')
  4235. return NULL;
  4236. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  4237. return NULL;
  4238. memset(&result, 0, sizeof(result));
  4239. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4240. result.policy_type = ADDR_POLICY_REJECT;
  4241. else
  4242. result.policy_type = ADDR_POLICY_ACCEPT;
  4243. result.is_private = 1;
  4244. result.prt_min = port_min;
  4245. result.prt_max = port_max;
  4246. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  4247. log_warn(LD_GENERAL,
  4248. "'%s' expands into rules which apply to all private IPv4 and "
  4249. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  4250. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  4251. }
  4252. return addr_policy_get_canonical_entry(&result);
  4253. }
  4254. /** Log and exit if <b>t</b> is malformed */
  4255. void
  4256. assert_addr_policy_ok(smartlist_t *lst)
  4257. {
  4258. if (!lst) return;
  4259. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  4260. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  4261. t->policy_type == ADDR_POLICY_ACCEPT);
  4262. tor_assert(t->prt_min <= t->prt_max);
  4263. });
  4264. }
  4265. /*
  4266. * Low-level tokenizer for router descriptors and directories.
  4267. */
  4268. /** Free all resources allocated for <b>tok</b> */
  4269. static void
  4270. token_clear(directory_token_t *tok)
  4271. {
  4272. if (tok->key)
  4273. crypto_pk_free(tok->key);
  4274. }
  4275. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  4276. #define ALLOC(sz) memarea_alloc(area,sz)
  4277. #define STRDUP(str) memarea_strdup(area,str)
  4278. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  4279. #define RET_ERR(msg) \
  4280. STMT_BEGIN \
  4281. if (tok) token_clear(tok); \
  4282. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  4283. tok->tp = ERR_; \
  4284. tok->error = STRDUP(msg); \
  4285. goto done_tokenizing; \
  4286. STMT_END
  4287. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  4288. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  4289. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  4290. * conform to the syntax we wanted.
  4291. **/
  4292. static inline directory_token_t *
  4293. token_check_object(memarea_t *area, const char *kwd,
  4294. directory_token_t *tok, obj_syntax o_syn)
  4295. {
  4296. char ebuf[128];
  4297. switch (o_syn) {
  4298. case NO_OBJ:
  4299. /* No object is allowed for this token. */
  4300. if (tok->object_body) {
  4301. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  4302. RET_ERR(ebuf);
  4303. }
  4304. if (tok->key) {
  4305. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  4306. RET_ERR(ebuf);
  4307. }
  4308. break;
  4309. case NEED_OBJ:
  4310. /* There must be a (non-key) object. */
  4311. if (!tok->object_body) {
  4312. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  4313. RET_ERR(ebuf);
  4314. }
  4315. break;
  4316. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  4317. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  4318. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  4319. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  4320. kwd, crypto_pk_num_bits(tok->key));
  4321. RET_ERR(ebuf);
  4322. }
  4323. /* fall through */
  4324. case NEED_KEY: /* There must be some kind of key. */
  4325. if (!tok->key) {
  4326. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  4327. RET_ERR(ebuf);
  4328. }
  4329. if (o_syn != NEED_SKEY_1024) {
  4330. if (crypto_pk_key_is_private(tok->key)) {
  4331. tor_snprintf(ebuf, sizeof(ebuf),
  4332. "Private key given for %s, which wants a public key", kwd);
  4333. RET_ERR(ebuf);
  4334. }
  4335. } else { /* o_syn == NEED_SKEY_1024 */
  4336. if (!crypto_pk_key_is_private(tok->key)) {
  4337. tor_snprintf(ebuf, sizeof(ebuf),
  4338. "Public key given for %s, which wants a private key", kwd);
  4339. RET_ERR(ebuf);
  4340. }
  4341. }
  4342. break;
  4343. case OBJ_OK:
  4344. /* Anything goes with this token. */
  4345. break;
  4346. }
  4347. done_tokenizing:
  4348. return tok;
  4349. }
  4350. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  4351. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  4352. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  4353. * all storage in <b>area</b>. Return the number of arguments parsed, or
  4354. * return -1 if there was an insanely high number of arguments. */
  4355. static inline int
  4356. get_token_arguments(memarea_t *area, directory_token_t *tok,
  4357. const char *s, const char *eol)
  4358. {
  4359. /** Largest number of arguments we'll accept to any token, ever. */
  4360. #define MAX_ARGS 512
  4361. char *mem = memarea_strndup(area, s, eol-s);
  4362. char *cp = mem;
  4363. int j = 0;
  4364. char *args[MAX_ARGS];
  4365. while (*cp) {
  4366. if (j == MAX_ARGS)
  4367. return -1;
  4368. args[j++] = cp;
  4369. cp = (char*)find_whitespace(cp);
  4370. if (!cp || !*cp)
  4371. break; /* End of the line. */
  4372. *cp++ = '\0';
  4373. cp = (char*)eat_whitespace(cp);
  4374. }
  4375. tok->n_args = j;
  4376. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  4377. return j;
  4378. #undef MAX_ARGS
  4379. }
  4380. /** Helper function: read the next token from *s, advance *s to the end of the
  4381. * token, and return the parsed token. Parse *<b>s</b> according to the list
  4382. * of tokens in <b>table</b>.
  4383. */
  4384. static directory_token_t *
  4385. get_next_token(memarea_t *area,
  4386. const char **s, const char *eos, token_rule_t *table)
  4387. {
  4388. /** Reject any object at least this big; it is probably an overflow, an
  4389. * attack, a bug, or some other nonsense. */
  4390. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  4391. /** Reject any line at least this big; it is probably an overflow, an
  4392. * attack, a bug, or some other nonsense. */
  4393. #define MAX_LINE_LENGTH (128*1024)
  4394. const char *next, *eol, *obstart;
  4395. size_t obname_len;
  4396. int i;
  4397. directory_token_t *tok;
  4398. obj_syntax o_syn = NO_OBJ;
  4399. char ebuf[128];
  4400. const char *kwd = "";
  4401. tor_assert(area);
  4402. tok = ALLOC_ZERO(sizeof(directory_token_t));
  4403. tok->tp = ERR_;
  4404. /* Set *s to first token, eol to end-of-line, next to after first token */
  4405. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  4406. tor_assert(eos >= *s);
  4407. eol = memchr(*s, '\n', eos-*s);
  4408. if (!eol)
  4409. eol = eos;
  4410. if (eol - *s > MAX_LINE_LENGTH) {
  4411. RET_ERR("Line far too long");
  4412. }
  4413. next = find_whitespace_eos(*s, eol);
  4414. if (!strcmp_len(*s, "opt", next-*s)) {
  4415. /* Skip past an "opt" at the start of the line. */
  4416. *s = eat_whitespace_eos_no_nl(next, eol);
  4417. next = find_whitespace_eos(*s, eol);
  4418. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  4419. RET_ERR("Unexpected EOF");
  4420. }
  4421. /* Search the table for the appropriate entry. (I tried a binary search
  4422. * instead, but it wasn't any faster.) */
  4423. for (i = 0; table[i].t ; ++i) {
  4424. if (!strcmp_len(*s, table[i].t, next-*s)) {
  4425. /* We've found the keyword. */
  4426. kwd = table[i].t;
  4427. tok->tp = table[i].v;
  4428. o_syn = table[i].os;
  4429. *s = eat_whitespace_eos_no_nl(next, eol);
  4430. /* We go ahead whether there are arguments or not, so that tok->args is
  4431. * always set if we want arguments. */
  4432. if (table[i].concat_args) {
  4433. /* The keyword takes the line as a single argument */
  4434. tok->args = ALLOC(sizeof(char*));
  4435. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  4436. tok->n_args = 1;
  4437. } else {
  4438. /* This keyword takes multiple arguments. */
  4439. if (get_token_arguments(area, tok, *s, eol)<0) {
  4440. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  4441. RET_ERR(ebuf);
  4442. }
  4443. *s = eol;
  4444. }
  4445. if (tok->n_args < table[i].min_args) {
  4446. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  4447. RET_ERR(ebuf);
  4448. } else if (tok->n_args > table[i].max_args) {
  4449. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  4450. RET_ERR(ebuf);
  4451. }
  4452. break;
  4453. }
  4454. }
  4455. if (tok->tp == ERR_) {
  4456. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  4457. if (**s == '@')
  4458. tok->tp = A_UNKNOWN_;
  4459. else
  4460. tok->tp = K_OPT;
  4461. tok->args = ALLOC(sizeof(char*));
  4462. tok->args[0] = STRNDUP(*s, eol-*s);
  4463. tok->n_args = 1;
  4464. o_syn = OBJ_OK;
  4465. }
  4466. /* Check whether there's an object present */
  4467. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  4468. tor_assert(eos >= *s);
  4469. eol = memchr(*s, '\n', eos-*s);
  4470. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  4471. goto check_object;
  4472. obstart = *s; /* Set obstart to start of object spec */
  4473. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  4474. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  4475. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  4476. RET_ERR("Malformed object: bad begin line");
  4477. }
  4478. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  4479. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  4480. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  4481. /* Go to the end of the object */
  4482. next = tor_memstr(*s, eos-*s, "-----END ");
  4483. if (!next) {
  4484. RET_ERR("Malformed object: missing object end line");
  4485. }
  4486. tor_assert(eos >= next);
  4487. eol = memchr(next, '\n', eos-next);
  4488. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  4489. eol = eos;
  4490. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  4491. if ((size_t)(eol-next) != 9+obname_len+5 ||
  4492. strcmp_len(next+9, tok->object_type, obname_len) ||
  4493. strcmp_len(eol-5, "-----", 5)) {
  4494. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  4495. tok->object_type);
  4496. ebuf[sizeof(ebuf)-1] = '\0';
  4497. RET_ERR(ebuf);
  4498. }
  4499. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  4500. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  4501. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  4502. tok->key = crypto_pk_new();
  4503. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  4504. RET_ERR("Couldn't parse public key.");
  4505. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  4506. tok->key = crypto_pk_new();
  4507. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  4508. RET_ERR("Couldn't parse private key.");
  4509. } else { /* If it's something else, try to base64-decode it */
  4510. int r;
  4511. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  4512. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  4513. if (r<0)
  4514. RET_ERR("Malformed object: bad base64-encoded data");
  4515. tok->object_size = r;
  4516. }
  4517. *s = eol;
  4518. check_object:
  4519. tok = token_check_object(area, kwd, tok, o_syn);
  4520. done_tokenizing:
  4521. return tok;
  4522. #undef RET_ERR
  4523. #undef ALLOC
  4524. #undef ALLOC_ZERO
  4525. #undef STRDUP
  4526. #undef STRNDUP
  4527. }
  4528. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  4529. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  4530. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  4531. * entire string.
  4532. */
  4533. static int
  4534. tokenize_string(memarea_t *area,
  4535. const char *start, const char *end, smartlist_t *out,
  4536. token_rule_t *table, int flags)
  4537. {
  4538. const char **s;
  4539. directory_token_t *tok = NULL;
  4540. int counts[NIL_];
  4541. int i;
  4542. int first_nonannotation;
  4543. int prev_len = smartlist_len(out);
  4544. tor_assert(area);
  4545. s = &start;
  4546. if (!end) {
  4547. end = start+strlen(start);
  4548. } else {
  4549. /* it's only meaningful to check for nuls if we got an end-of-string ptr */
  4550. if (memchr(start, '\0', end-start)) {
  4551. log_warn(LD_DIR, "parse error: internal NUL character.");
  4552. return -1;
  4553. }
  4554. }
  4555. for (i = 0; i < NIL_; ++i)
  4556. counts[i] = 0;
  4557. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  4558. while (*s < end && (!tok || tok->tp != EOF_)) {
  4559. tok = get_next_token(area, s, end, table);
  4560. if (tok->tp == ERR_) {
  4561. log_warn(LD_DIR, "parse error: %s", tok->error);
  4562. token_clear(tok);
  4563. return -1;
  4564. }
  4565. ++counts[tok->tp];
  4566. smartlist_add(out, tok);
  4567. *s = eat_whitespace_eos(*s, end);
  4568. }
  4569. if (flags & TS_NOCHECK)
  4570. return 0;
  4571. if ((flags & TS_ANNOTATIONS_OK)) {
  4572. first_nonannotation = -1;
  4573. for (i = 0; i < smartlist_len(out); ++i) {
  4574. tok = smartlist_get(out, i);
  4575. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  4576. first_nonannotation = i;
  4577. break;
  4578. }
  4579. }
  4580. if (first_nonannotation < 0) {
  4581. log_warn(LD_DIR, "parse error: item contains only annotations");
  4582. return -1;
  4583. }
  4584. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  4585. tok = smartlist_get(out, i);
  4586. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4587. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  4588. return -1;
  4589. }
  4590. }
  4591. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  4592. if (first_nonannotation != prev_len) {
  4593. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  4594. return -1;
  4595. }
  4596. }
  4597. } else {
  4598. for (i=0; i < smartlist_len(out); ++i) {
  4599. tok = smartlist_get(out, i);
  4600. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4601. log_warn(LD_DIR, "parse error: no annotations allowed.");
  4602. return -1;
  4603. }
  4604. }
  4605. first_nonannotation = 0;
  4606. }
  4607. for (i = 0; table[i].t; ++i) {
  4608. if (counts[table[i].v] < table[i].min_cnt) {
  4609. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  4610. return -1;
  4611. }
  4612. if (counts[table[i].v] > table[i].max_cnt) {
  4613. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  4614. return -1;
  4615. }
  4616. if (table[i].pos & AT_START) {
  4617. if (smartlist_len(out) < 1 ||
  4618. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  4619. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  4620. return -1;
  4621. }
  4622. }
  4623. if (table[i].pos & AT_END) {
  4624. if (smartlist_len(out) < 1 ||
  4625. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  4626. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  4627. return -1;
  4628. }
  4629. }
  4630. }
  4631. return 0;
  4632. }
  4633. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  4634. * NULL if no such keyword is found.
  4635. */
  4636. static directory_token_t *
  4637. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  4638. {
  4639. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  4640. return NULL;
  4641. }
  4642. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  4643. * with an assert if no such keyword is found.
  4644. */
  4645. static directory_token_t *
  4646. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  4647. const char *keyword_as_string)
  4648. {
  4649. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  4650. if (PREDICT_UNLIKELY(!tok)) {
  4651. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  4652. "been validated. Internal error.", keyword_as_string, (int)keyword);
  4653. tor_assert(tok);
  4654. }
  4655. return tok;
  4656. }
  4657. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  4658. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  4659. * in the same order in which they occur in <b>s</b>. Otherwise return
  4660. * NULL. */
  4661. static smartlist_t *
  4662. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  4663. {
  4664. smartlist_t *out = NULL;
  4665. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4666. if (t->tp == k) {
  4667. if (!out)
  4668. out = smartlist_new();
  4669. smartlist_add(out, t);
  4670. });
  4671. return out;
  4672. }
  4673. /** Return a newly allocated smartlist of all accept or reject tokens in
  4674. * <b>s</b>.
  4675. */
  4676. static smartlist_t *
  4677. find_all_exitpolicy(smartlist_t *s)
  4678. {
  4679. smartlist_t *out = smartlist_new();
  4680. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4681. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  4682. t->tp == K_REJECT || t->tp == K_REJECT6)
  4683. smartlist_add(out,t));
  4684. return out;
  4685. }
  4686. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  4687. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  4688. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  4689. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  4690. *
  4691. * Return 0 on success and -1 on failure.
  4692. */
  4693. static int
  4694. router_get_hash_impl_helper(const char *s, size_t s_len,
  4695. const char *start_str,
  4696. const char *end_str, char end_c,
  4697. const char **start_out, const char **end_out)
  4698. {
  4699. const char *start, *end;
  4700. start = tor_memstr(s, s_len, start_str);
  4701. if (!start) {
  4702. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  4703. return -1;
  4704. }
  4705. if (start != s && *(start-1) != '\n') {
  4706. log_warn(LD_DIR,
  4707. "first occurrence of \"%s\" is not at the start of a line",
  4708. start_str);
  4709. return -1;
  4710. }
  4711. end = tor_memstr(start+strlen(start_str),
  4712. s_len - (start-s) - strlen(start_str), end_str);
  4713. if (!end) {
  4714. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  4715. return -1;
  4716. }
  4717. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  4718. if (!end) {
  4719. log_warn(LD_DIR,"couldn't find EOL");
  4720. return -1;
  4721. }
  4722. ++end;
  4723. *start_out = start;
  4724. *end_out = end;
  4725. return 0;
  4726. }
  4727. /** Compute the digest of the substring of <b>s</b> taken from the first
  4728. * occurrence of <b>start_str</b> through the first instance of c after the
  4729. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  4730. * result in <b>digest</b>; return 0 on success.
  4731. *
  4732. * If no such substring exists, return -1.
  4733. */
  4734. static int
  4735. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  4736. const char *start_str,
  4737. const char *end_str, char end_c,
  4738. digest_algorithm_t alg)
  4739. {
  4740. const char *start=NULL, *end=NULL;
  4741. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4742. &start,&end)<0)
  4743. return -1;
  4744. if (alg == DIGEST_SHA1) {
  4745. if (crypto_digest(digest, start, end-start)) {
  4746. log_warn(LD_BUG,"couldn't compute digest");
  4747. return -1;
  4748. }
  4749. } else {
  4750. if (crypto_digest256(digest, start, end-start, alg)) {
  4751. log_warn(LD_BUG,"couldn't compute digest");
  4752. return -1;
  4753. }
  4754. }
  4755. return 0;
  4756. }
  4757. /** As router_get_hash_impl, but compute all hashes. */
  4758. static int
  4759. router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
  4760. const char *start_str,
  4761. const char *end_str, char end_c)
  4762. {
  4763. const char *start=NULL, *end=NULL;
  4764. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4765. &start,&end)<0)
  4766. return -1;
  4767. if (crypto_common_digests(digests, start, end-start)) {
  4768. log_warn(LD_BUG,"couldn't compute digests");
  4769. return -1;
  4770. }
  4771. return 0;
  4772. }
  4773. /** Assuming that s starts with a microdesc, return the start of the
  4774. * *NEXT* one. Return NULL on "not found." */
  4775. static const char *
  4776. find_start_of_next_microdesc(const char *s, const char *eos)
  4777. {
  4778. int started_with_annotations;
  4779. s = eat_whitespace_eos(s, eos);
  4780. if (!s)
  4781. return NULL;
  4782. #define CHECK_LENGTH() STMT_BEGIN \
  4783. if (s+32 > eos) \
  4784. return NULL; \
  4785. STMT_END
  4786. #define NEXT_LINE() STMT_BEGIN \
  4787. s = memchr(s, '\n', eos-s); \
  4788. if (!s || s+1 >= eos) \
  4789. return NULL; \
  4790. s++; \
  4791. STMT_END
  4792. CHECK_LENGTH();
  4793. started_with_annotations = (*s == '@');
  4794. if (started_with_annotations) {
  4795. /* Start by advancing to the first non-annotation line. */
  4796. while (*s == '@')
  4797. NEXT_LINE();
  4798. }
  4799. CHECK_LENGTH();
  4800. /* Now we should be pointed at an onion-key line. If we are, then skip
  4801. * it. */
  4802. if (!strcmpstart(s, "onion-key"))
  4803. NEXT_LINE();
  4804. /* Okay, now we're pointed at the first line of the microdescriptor which is
  4805. not an annotation or onion-key. The next line that _is_ an annotation or
  4806. onion-key is the start of the next microdescriptor. */
  4807. while (s+32 < eos) {
  4808. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4809. return s;
  4810. NEXT_LINE();
  4811. }
  4812. return NULL;
  4813. #undef CHECK_LENGTH
  4814. #undef NEXT_LINE
  4815. }
  4816. /** Parse as many microdescriptors as are found from the string starting at
  4817. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4818. * annotations we recognize and ignore ones we don't.
  4819. *
  4820. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  4821. * descriptor in the body field of each microdesc_t.
  4822. *
  4823. * Return all newly parsed microdescriptors in a newly allocated
  4824. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  4825. * microdesc digest to it for every microdesc that we found to be badly
  4826. * formed. (This may cause duplicates) */
  4827. smartlist_t *
  4828. microdescs_parse_from_string(const char *s, const char *eos,
  4829. int allow_annotations,
  4830. saved_location_t where,
  4831. smartlist_t *invalid_digests_out)
  4832. {
  4833. smartlist_t *tokens;
  4834. smartlist_t *result;
  4835. microdesc_t *md = NULL;
  4836. memarea_t *area;
  4837. const char *start = s;
  4838. const char *start_of_next_microdesc;
  4839. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4840. const int copy_body = (where != SAVED_IN_CACHE);
  4841. directory_token_t *tok;
  4842. if (!eos)
  4843. eos = s + strlen(s);
  4844. s = eat_whitespace_eos(s, eos);
  4845. area = memarea_new();
  4846. result = smartlist_new();
  4847. tokens = smartlist_new();
  4848. while (s < eos) {
  4849. int okay = 0;
  4850. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4851. if (!start_of_next_microdesc)
  4852. start_of_next_microdesc = eos;
  4853. md = tor_malloc_zero(sizeof(microdesc_t));
  4854. {
  4855. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4856. "onion-key");
  4857. const int no_onion_key = (cp == NULL);
  4858. if (no_onion_key) {
  4859. cp = s; /* So that we have *some* junk to put in the body */
  4860. }
  4861. md->bodylen = start_of_next_microdesc - cp;
  4862. md->saved_location = where;
  4863. if (copy_body)
  4864. md->body = tor_memdup_nulterm(cp, md->bodylen);
  4865. else
  4866. md->body = (char*)cp;
  4867. md->off = cp - start;
  4868. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4869. if (no_onion_key) {
  4870. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  4871. goto next;
  4872. }
  4873. }
  4874. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4875. microdesc_token_table, flags)) {
  4876. log_warn(LD_DIR, "Unparseable microdescriptor");
  4877. goto next;
  4878. }
  4879. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4880. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4881. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4882. goto next;
  4883. }
  4884. }
  4885. tok = find_by_keyword(tokens, K_ONION_KEY);
  4886. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4887. log_warn(LD_DIR,
  4888. "Relay's onion key had invalid exponent.");
  4889. goto next;
  4890. }
  4891. md->onion_pkey = tok->key;
  4892. tok->key = NULL;
  4893. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  4894. curve25519_public_key_t k;
  4895. tor_assert(tok->n_args >= 1);
  4896. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  4897. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  4898. goto next;
  4899. }
  4900. md->onion_curve25519_pkey =
  4901. tor_memdup(&k, sizeof(curve25519_public_key_t));
  4902. }
  4903. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  4904. if (id_lines) {
  4905. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  4906. tor_assert(t->n_args >= 2);
  4907. if (!strcmp(t->args[0], "ed25519")) {
  4908. if (md->ed25519_identity_pkey) {
  4909. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  4910. goto next;
  4911. }
  4912. ed25519_public_key_t k;
  4913. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  4914. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  4915. goto next;
  4916. }
  4917. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  4918. }
  4919. } SMARTLIST_FOREACH_END(t);
  4920. smartlist_free(id_lines);
  4921. }
  4922. {
  4923. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4924. if (a_lines) {
  4925. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4926. smartlist_free(a_lines);
  4927. }
  4928. }
  4929. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4930. int i;
  4931. md->family = smartlist_new();
  4932. for (i=0;i<tok->n_args;++i) {
  4933. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4934. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4935. escaped(tok->args[i]));
  4936. goto next;
  4937. }
  4938. smartlist_add(md->family, tor_strdup(tok->args[i]));
  4939. }
  4940. }
  4941. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4942. md->exit_policy = parse_short_policy(tok->args[0]);
  4943. }
  4944. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4945. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4946. }
  4947. smartlist_add(result, md);
  4948. okay = 1;
  4949. md = NULL;
  4950. next:
  4951. if (! okay && invalid_digests_out) {
  4952. smartlist_add(invalid_digests_out,
  4953. tor_memdup(md->digest, DIGEST256_LEN));
  4954. }
  4955. microdesc_free(md);
  4956. md = NULL;
  4957. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4958. memarea_clear(area);
  4959. smartlist_clear(tokens);
  4960. s = start_of_next_microdesc;
  4961. }
  4962. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4963. memarea_drop_all(area);
  4964. smartlist_free(tokens);
  4965. return result;
  4966. }
  4967. /** Parse the Tor version of the platform string <b>platform</b>,
  4968. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4969. * the router is at least as new as the cutoff, else return 0.
  4970. */
  4971. int
  4972. tor_version_as_new_as(const char *platform, const char *cutoff)
  4973. {
  4974. tor_version_t cutoff_version, router_version;
  4975. char *s, *s2, *start;
  4976. char tmp[128];
  4977. tor_assert(platform);
  4978. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4979. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4980. return 0;
  4981. }
  4982. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4983. return 1;
  4984. start = (char *)eat_whitespace(platform+3);
  4985. if (!*start) return 0;
  4986. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4987. s2 = (char*)eat_whitespace(s);
  4988. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4989. s = (char*)find_whitespace(s2);
  4990. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4991. return 0;
  4992. strlcpy(tmp, start, s-start+1);
  4993. if (tor_version_parse(tmp, &router_version)<0) {
  4994. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4995. return 1; /* be safe and say yes */
  4996. }
  4997. /* Here's why we don't need to do any special handling for svn revisions:
  4998. * - If neither has an svn revision, we're fine.
  4999. * - If the router doesn't have an svn revision, we can't assume that it
  5000. * is "at least" any svn revision, so we need to return 0.
  5001. * - If the target version doesn't have an svn revision, any svn revision
  5002. * (or none at all) is good enough, so return 1.
  5003. * - If both target and router have an svn revision, we compare them.
  5004. */
  5005. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  5006. }
  5007. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  5008. * Return 0 on success, -1 on failure. */
  5009. int
  5010. tor_version_parse(const char *s, tor_version_t *out)
  5011. {
  5012. char *eos=NULL;
  5013. const char *cp=NULL;
  5014. /* Format is:
  5015. * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
  5016. */
  5017. tor_assert(s);
  5018. tor_assert(out);
  5019. memset(out, 0, sizeof(tor_version_t));
  5020. out->status = VER_RELEASE;
  5021. if (!strcasecmpstart(s, "Tor "))
  5022. s += 4;
  5023. cp = s;
  5024. #define NUMBER(m) \
  5025. do { \
  5026. out->m = (int)strtol(cp, &eos, 10); \
  5027. if (!eos || eos == cp) \
  5028. return -1; \
  5029. cp = eos; \
  5030. } while (0)
  5031. #define DOT() \
  5032. do { \
  5033. if (*cp != '.') \
  5034. return -1; \
  5035. ++cp; \
  5036. } while (0)
  5037. NUMBER(major);
  5038. DOT();
  5039. NUMBER(minor);
  5040. if (*cp == 0)
  5041. return 0;
  5042. else if (*cp == '-')
  5043. goto status_tag;
  5044. DOT();
  5045. NUMBER(micro);
  5046. /* Get status */
  5047. if (*cp == 0) {
  5048. return 0;
  5049. } else if (*cp == '.') {
  5050. ++cp;
  5051. } else if (*cp == '-') {
  5052. goto status_tag;
  5053. } else if (0==strncmp(cp, "pre", 3)) {
  5054. out->status = VER_PRE;
  5055. cp += 3;
  5056. } else if (0==strncmp(cp, "rc", 2)) {
  5057. out->status = VER_RC;
  5058. cp += 2;
  5059. } else {
  5060. return -1;
  5061. }
  5062. NUMBER(patchlevel);
  5063. status_tag:
  5064. /* Get status tag. */
  5065. if (*cp == '-' || *cp == '.')
  5066. ++cp;
  5067. eos = (char*) find_whitespace(cp);
  5068. if (eos-cp >= (int)sizeof(out->status_tag))
  5069. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  5070. else {
  5071. memcpy(out->status_tag, cp, eos-cp);
  5072. out->status_tag[eos-cp] = 0;
  5073. }
  5074. cp = eat_whitespace(eos);
  5075. if (!strcmpstart(cp, "(r")) {
  5076. cp += 2;
  5077. out->svn_revision = (int) strtol(cp,&eos,10);
  5078. } else if (!strcmpstart(cp, "(git-")) {
  5079. char *close_paren = strchr(cp, ')');
  5080. int hexlen;
  5081. char digest[DIGEST_LEN];
  5082. if (! close_paren)
  5083. return -1;
  5084. cp += 5;
  5085. if (close_paren-cp > HEX_DIGEST_LEN)
  5086. return -1;
  5087. hexlen = (int)(close_paren-cp);
  5088. memwipe(digest, 0, sizeof(digest));
  5089. if ( hexlen == 0 || (hexlen % 2) == 1)
  5090. return -1;
  5091. if (base16_decode(digest, hexlen/2, cp, hexlen) != hexlen/2)
  5092. return -1;
  5093. memcpy(out->git_tag, digest, hexlen/2);
  5094. out->git_tag_len = hexlen/2;
  5095. }
  5096. return 0;
  5097. #undef NUMBER
  5098. #undef DOT
  5099. }
  5100. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  5101. * b. */
  5102. int
  5103. tor_version_compare(tor_version_t *a, tor_version_t *b)
  5104. {
  5105. int i;
  5106. tor_assert(a);
  5107. tor_assert(b);
  5108. if ((i = a->major - b->major))
  5109. return i;
  5110. else if ((i = a->minor - b->minor))
  5111. return i;
  5112. else if ((i = a->micro - b->micro))
  5113. return i;
  5114. else if ((i = a->status - b->status))
  5115. return i;
  5116. else if ((i = a->patchlevel - b->patchlevel))
  5117. return i;
  5118. else if ((i = strcmp(a->status_tag, b->status_tag)))
  5119. return i;
  5120. else if ((i = a->svn_revision - b->svn_revision))
  5121. return i;
  5122. else if ((i = a->git_tag_len - b->git_tag_len))
  5123. return i;
  5124. else if (a->git_tag_len)
  5125. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  5126. else
  5127. return 0;
  5128. }
  5129. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  5130. */
  5131. int
  5132. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  5133. {
  5134. tor_assert(a);
  5135. tor_assert(b);
  5136. return ((a->major == b->major) &&
  5137. (a->minor == b->minor) &&
  5138. (a->micro == b->micro));
  5139. }
  5140. /** Helper: Given pointers to two strings describing tor versions, return -1
  5141. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  5142. * Used to sort a list of versions. */
  5143. static int
  5144. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  5145. {
  5146. const char *a = *_a, *b = *_b;
  5147. int ca, cb;
  5148. tor_version_t va, vb;
  5149. ca = tor_version_parse(a, &va);
  5150. cb = tor_version_parse(b, &vb);
  5151. /* If they both parse, compare them. */
  5152. if (!ca && !cb)
  5153. return tor_version_compare(&va,&vb);
  5154. /* If one parses, it comes first. */
  5155. if (!ca && cb)
  5156. return -1;
  5157. if (ca && !cb)
  5158. return 1;
  5159. /* If neither parses, compare strings. Also, the directory server admin
  5160. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  5161. return strcmp(a,b);
  5162. }
  5163. /** Sort a list of string-representations of versions in ascending order. */
  5164. void
  5165. sort_version_list(smartlist_t *versions, int remove_duplicates)
  5166. {
  5167. smartlist_sort(versions, compare_tor_version_str_ptr_);
  5168. if (remove_duplicates)
  5169. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  5170. }
  5171. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  5172. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  5173. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  5174. * encrypted introduction points to the newly allocated
  5175. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  5176. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  5177. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  5178. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  5179. * and -1 for failure.
  5180. *
  5181. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  5182. * be strict about time formats.
  5183. */
  5184. int
  5185. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  5186. char *desc_id_out,
  5187. char **intro_points_encrypted_out,
  5188. size_t *intro_points_encrypted_size_out,
  5189. size_t *encoded_size_out,
  5190. const char **next_out, const char *desc,
  5191. int as_hsdir)
  5192. {
  5193. rend_service_descriptor_t *result =
  5194. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  5195. char desc_hash[DIGEST_LEN];
  5196. const char *eos;
  5197. smartlist_t *tokens = smartlist_new();
  5198. directory_token_t *tok;
  5199. char secret_id_part[DIGEST_LEN];
  5200. int i, version, num_ok=1;
  5201. smartlist_t *versions;
  5202. char public_key_hash[DIGEST_LEN];
  5203. char test_desc_id[DIGEST_LEN];
  5204. memarea_t *area = NULL;
  5205. const int strict_time_fmt = as_hsdir;
  5206. tor_assert(desc);
  5207. /* Check if desc starts correctly. */
  5208. if (strncmp(desc, "rendezvous-service-descriptor ",
  5209. strlen("rendezvous-service-descriptor "))) {
  5210. log_info(LD_REND, "Descriptor does not start correctly.");
  5211. goto err;
  5212. }
  5213. /* Compute descriptor hash for later validation. */
  5214. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  5215. "rendezvous-service-descriptor ",
  5216. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  5217. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  5218. goto err;
  5219. }
  5220. /* Determine end of string. */
  5221. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  5222. if (!eos)
  5223. eos = desc + strlen(desc);
  5224. else
  5225. eos = eos + 1;
  5226. /* Check length. */
  5227. if (eos-desc > REND_DESC_MAX_SIZE) {
  5228. /* XXXX+ If we are parsing this descriptor as a server, this
  5229. * should be a protocol warning. */
  5230. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  5231. "maximum rendezvous descriptor size of %d bytes.",
  5232. (int)(eos-desc), REND_DESC_MAX_SIZE);
  5233. goto err;
  5234. }
  5235. /* Tokenize descriptor. */
  5236. area = memarea_new();
  5237. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  5238. log_warn(LD_REND, "Error tokenizing descriptor.");
  5239. goto err;
  5240. }
  5241. /* Set next to next descriptor, if available. */
  5242. *next_out = eos;
  5243. /* Set length of encoded descriptor. */
  5244. *encoded_size_out = eos - desc;
  5245. /* Check min allowed length of token list. */
  5246. if (smartlist_len(tokens) < 7) {
  5247. log_warn(LD_REND, "Impossibly short descriptor.");
  5248. goto err;
  5249. }
  5250. /* Parse base32-encoded descriptor ID. */
  5251. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  5252. tor_assert(tok == smartlist_get(tokens, 0));
  5253. tor_assert(tok->n_args == 1);
  5254. if (!rend_valid_descriptor_id(tok->args[0])) {
  5255. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  5256. goto err;
  5257. }
  5258. if (base32_decode(desc_id_out, DIGEST_LEN,
  5259. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  5260. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  5261. tok->args[0]);
  5262. goto err;
  5263. }
  5264. /* Parse descriptor version. */
  5265. tok = find_by_keyword(tokens, R_VERSION);
  5266. tor_assert(tok->n_args == 1);
  5267. result->version =
  5268. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  5269. if (result->version != 2 || !num_ok) {
  5270. /* If it's <2, it shouldn't be under this format. If the number
  5271. * is greater than 2, we bumped it because we broke backward
  5272. * compatibility. See how version numbers in our other formats
  5273. * work. */
  5274. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  5275. escaped(tok->args[0]));
  5276. goto err;
  5277. }
  5278. /* Parse public key. */
  5279. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  5280. result->pk = tok->key;
  5281. tok->key = NULL; /* Prevent free */
  5282. /* Parse secret ID part. */
  5283. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  5284. tor_assert(tok->n_args == 1);
  5285. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  5286. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  5287. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  5288. goto err;
  5289. }
  5290. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  5291. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  5292. tok->args[0]);
  5293. goto err;
  5294. }
  5295. /* Parse publication time -- up-to-date check is done when storing the
  5296. * descriptor. */
  5297. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  5298. tor_assert(tok->n_args == 1);
  5299. if (parse_iso_time_(tok->args[0], &result->timestamp, strict_time_fmt) < 0) {
  5300. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  5301. goto err;
  5302. }
  5303. /* Parse protocol versions. */
  5304. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  5305. tor_assert(tok->n_args == 1);
  5306. versions = smartlist_new();
  5307. smartlist_split_string(versions, tok->args[0], ",",
  5308. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  5309. for (i = 0; i < smartlist_len(versions); i++) {
  5310. version = (int) tor_parse_long(smartlist_get(versions, i),
  5311. 10, 0, INT_MAX, &num_ok, NULL);
  5312. if (!num_ok) /* It's a string; let's ignore it. */
  5313. continue;
  5314. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  5315. /* Avoid undefined left-shift behaviour. */
  5316. continue;
  5317. result->protocols |= 1 << version;
  5318. }
  5319. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  5320. smartlist_free(versions);
  5321. /* Parse encrypted introduction points. Don't verify. */
  5322. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  5323. if (tok) {
  5324. if (strcmp(tok->object_type, "MESSAGE")) {
  5325. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  5326. "type MESSAGE");
  5327. goto err;
  5328. }
  5329. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  5330. tok->object_size);
  5331. *intro_points_encrypted_size_out = tok->object_size;
  5332. } else {
  5333. *intro_points_encrypted_out = NULL;
  5334. *intro_points_encrypted_size_out = 0;
  5335. }
  5336. /* Parse and verify signature. */
  5337. tok = find_by_keyword(tokens, R_SIGNATURE);
  5338. note_crypto_pk_op(VERIFY_RTR);
  5339. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  5340. "v2 rendezvous service descriptor") < 0)
  5341. goto err;
  5342. /* Verify that descriptor ID belongs to public key and secret ID part. */
  5343. crypto_pk_get_digest(result->pk, public_key_hash);
  5344. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  5345. secret_id_part);
  5346. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  5347. log_warn(LD_REND, "Parsed descriptor ID does not match "
  5348. "computed descriptor ID.");
  5349. goto err;
  5350. }
  5351. goto done;
  5352. err:
  5353. rend_service_descriptor_free(result);
  5354. result = NULL;
  5355. done:
  5356. if (tokens) {
  5357. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5358. smartlist_free(tokens);
  5359. }
  5360. if (area)
  5361. memarea_drop_all(area);
  5362. *parsed_out = result;
  5363. if (result)
  5364. return 0;
  5365. return -1;
  5366. }
  5367. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  5368. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  5369. * write the result to a newly allocated string that is pointed to by
  5370. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  5371. * Return 0 if decryption was successful and -1 otherwise. */
  5372. int
  5373. rend_decrypt_introduction_points(char **ipos_decrypted,
  5374. size_t *ipos_decrypted_size,
  5375. const char *descriptor_cookie,
  5376. const char *ipos_encrypted,
  5377. size_t ipos_encrypted_size)
  5378. {
  5379. tor_assert(ipos_encrypted);
  5380. tor_assert(descriptor_cookie);
  5381. if (ipos_encrypted_size < 2) {
  5382. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5383. "small.");
  5384. return -1;
  5385. }
  5386. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  5387. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  5388. session_key[CIPHER_KEY_LEN], *dec;
  5389. int declen, client_blocks;
  5390. size_t pos = 0, len, client_entries_len;
  5391. crypto_digest_t *digest;
  5392. crypto_cipher_t *cipher;
  5393. client_blocks = (int) ipos_encrypted[1];
  5394. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  5395. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  5396. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  5397. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5398. "small.");
  5399. return -1;
  5400. }
  5401. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  5402. digest = crypto_digest_new();
  5403. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  5404. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  5405. crypto_digest_get_digest(digest, client_id,
  5406. REND_BASIC_AUTH_CLIENT_ID_LEN);
  5407. crypto_digest_free(digest);
  5408. for (pos = 2; pos < 2 + client_entries_len;
  5409. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  5410. if (tor_memeq(ipos_encrypted + pos, client_id,
  5411. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  5412. /* Attempt to decrypt introduction points. */
  5413. cipher = crypto_cipher_new(descriptor_cookie);
  5414. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  5415. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  5416. CIPHER_KEY_LEN) < 0) {
  5417. log_warn(LD_REND, "Could not decrypt session key for client.");
  5418. crypto_cipher_free(cipher);
  5419. return -1;
  5420. }
  5421. crypto_cipher_free(cipher);
  5422. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  5423. dec = tor_malloc(len);
  5424. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  5425. ipos_encrypted + 2 + client_entries_len,
  5426. ipos_encrypted_size - 2 - client_entries_len);
  5427. if (declen < 0) {
  5428. log_warn(LD_REND, "Could not decrypt introduction point string.");
  5429. tor_free(dec);
  5430. return -1;
  5431. }
  5432. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  5433. log_warn(LD_REND, "Decrypted introduction points don't "
  5434. "look like we could parse them.");
  5435. tor_free(dec);
  5436. continue;
  5437. }
  5438. *ipos_decrypted = dec;
  5439. *ipos_decrypted_size = declen;
  5440. return 0;
  5441. }
  5442. }
  5443. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  5444. "check your authorization for this service!");
  5445. return -1;
  5446. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  5447. char *dec;
  5448. int declen;
  5449. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  5450. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5451. "small.");
  5452. return -1;
  5453. }
  5454. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  5455. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  5456. ipos_encrypted_size -
  5457. CIPHER_IV_LEN - 1,
  5458. ipos_encrypted + 1,
  5459. ipos_encrypted_size - 1);
  5460. if (declen < 0) {
  5461. log_warn(LD_REND, "Decrypting introduction points failed!");
  5462. tor_free(dec);
  5463. return -1;
  5464. }
  5465. *ipos_decrypted = dec;
  5466. *ipos_decrypted_size = declen;
  5467. return 0;
  5468. } else {
  5469. log_warn(LD_REND, "Unknown authorization type number: %d",
  5470. ipos_encrypted[0]);
  5471. return -1;
  5472. }
  5473. }
  5474. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  5475. * length <b>intro_points_encoded_size</b> and write the result to the
  5476. * descriptor in <b>parsed</b>; return the number of successfully parsed
  5477. * introduction points or -1 in case of a failure. */
  5478. int
  5479. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  5480. const char *intro_points_encoded,
  5481. size_t intro_points_encoded_size)
  5482. {
  5483. const char *current_ipo, *end_of_intro_points;
  5484. smartlist_t *tokens = NULL;
  5485. directory_token_t *tok;
  5486. rend_intro_point_t *intro;
  5487. extend_info_t *info;
  5488. int result, num_ok=1;
  5489. memarea_t *area = NULL;
  5490. tor_assert(parsed);
  5491. /** Function may only be invoked once. */
  5492. tor_assert(!parsed->intro_nodes);
  5493. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  5494. log_warn(LD_REND, "Empty or zero size introduction point list");
  5495. goto err;
  5496. }
  5497. /* Consider one intro point after the other. */
  5498. current_ipo = intro_points_encoded;
  5499. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  5500. tokens = smartlist_new();
  5501. parsed->intro_nodes = smartlist_new();
  5502. area = memarea_new();
  5503. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  5504. "introduction-point ")) {
  5505. /* Determine end of string. */
  5506. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  5507. "\nintroduction-point ");
  5508. if (!eos)
  5509. eos = end_of_intro_points;
  5510. else
  5511. eos = eos+1;
  5512. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  5513. /* Free tokens and clear token list. */
  5514. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5515. smartlist_clear(tokens);
  5516. memarea_clear(area);
  5517. /* Tokenize string. */
  5518. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  5519. log_warn(LD_REND, "Error tokenizing introduction point");
  5520. goto err;
  5521. }
  5522. /* Advance to next introduction point, if available. */
  5523. current_ipo = eos;
  5524. /* Check minimum allowed length of introduction point. */
  5525. if (smartlist_len(tokens) < 5) {
  5526. log_warn(LD_REND, "Impossibly short introduction point.");
  5527. goto err;
  5528. }
  5529. /* Allocate new intro point and extend info. */
  5530. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  5531. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  5532. /* Parse identifier. */
  5533. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  5534. if (base32_decode(info->identity_digest, DIGEST_LEN,
  5535. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  5536. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  5537. tok->args[0]);
  5538. rend_intro_point_free(intro);
  5539. goto err;
  5540. }
  5541. /* Write identifier to nickname. */
  5542. info->nickname[0] = '$';
  5543. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  5544. info->identity_digest, DIGEST_LEN);
  5545. /* Parse IP address. */
  5546. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  5547. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  5548. log_warn(LD_REND, "Could not parse introduction point address.");
  5549. rend_intro_point_free(intro);
  5550. goto err;
  5551. }
  5552. if (tor_addr_family(&info->addr) != AF_INET) {
  5553. log_warn(LD_REND, "Introduction point address was not ipv4.");
  5554. rend_intro_point_free(intro);
  5555. goto err;
  5556. }
  5557. /* Parse onion port. */
  5558. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  5559. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  5560. &num_ok,NULL);
  5561. if (!info->port || !num_ok) {
  5562. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  5563. escaped(tok->args[0]));
  5564. rend_intro_point_free(intro);
  5565. goto err;
  5566. }
  5567. /* Parse onion key. */
  5568. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  5569. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5570. log_warn(LD_REND,
  5571. "Introduction point's onion key had invalid exponent.");
  5572. rend_intro_point_free(intro);
  5573. goto err;
  5574. }
  5575. info->onion_key = tok->key;
  5576. tok->key = NULL; /* Prevent free */
  5577. /* Parse service key. */
  5578. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  5579. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5580. log_warn(LD_REND,
  5581. "Introduction point key had invalid exponent.");
  5582. rend_intro_point_free(intro);
  5583. goto err;
  5584. }
  5585. intro->intro_key = tok->key;
  5586. tok->key = NULL; /* Prevent free */
  5587. /* Add extend info to list of introduction points. */
  5588. smartlist_add(parsed->intro_nodes, intro);
  5589. }
  5590. result = smartlist_len(parsed->intro_nodes);
  5591. goto done;
  5592. err:
  5593. result = -1;
  5594. done:
  5595. /* Free tokens and clear token list. */
  5596. if (tokens) {
  5597. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5598. smartlist_free(tokens);
  5599. }
  5600. if (area)
  5601. memarea_drop_all(area);
  5602. return result;
  5603. }
  5604. /** Parse the content of a client_key file in <b>ckstr</b> and add
  5605. * rend_authorized_client_t's for each parsed client to
  5606. * <b>parsed_clients</b>. Return the number of parsed clients as result
  5607. * or -1 for failure. */
  5608. int
  5609. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  5610. {
  5611. int result = -1;
  5612. smartlist_t *tokens;
  5613. directory_token_t *tok;
  5614. const char *current_entry = NULL;
  5615. memarea_t *area = NULL;
  5616. char *err_msg = NULL;
  5617. if (!ckstr || strlen(ckstr) == 0)
  5618. return -1;
  5619. tokens = smartlist_new();
  5620. /* Begin parsing with first entry, skipping comments or whitespace at the
  5621. * beginning. */
  5622. area = memarea_new();
  5623. current_entry = eat_whitespace(ckstr);
  5624. while (!strcmpstart(current_entry, "client-name ")) {
  5625. rend_authorized_client_t *parsed_entry;
  5626. /* Determine end of string. */
  5627. const char *eos = strstr(current_entry, "\nclient-name ");
  5628. if (!eos)
  5629. eos = current_entry + strlen(current_entry);
  5630. else
  5631. eos = eos + 1;
  5632. /* Free tokens and clear token list. */
  5633. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5634. smartlist_clear(tokens);
  5635. memarea_clear(area);
  5636. /* Tokenize string. */
  5637. if (tokenize_string(area, current_entry, eos, tokens,
  5638. client_keys_token_table, 0)) {
  5639. log_warn(LD_REND, "Error tokenizing client keys file.");
  5640. goto err;
  5641. }
  5642. /* Advance to next entry, if available. */
  5643. current_entry = eos;
  5644. /* Check minimum allowed length of token list. */
  5645. if (smartlist_len(tokens) < 2) {
  5646. log_warn(LD_REND, "Impossibly short client key entry.");
  5647. goto err;
  5648. }
  5649. /* Parse client name. */
  5650. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  5651. tor_assert(tok == smartlist_get(tokens, 0));
  5652. tor_assert(tok->n_args == 1);
  5653. if (!rend_valid_client_name(tok->args[0])) {
  5654. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  5655. "between 1 and %d, and valid characters are "
  5656. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  5657. goto err;
  5658. }
  5659. /* Check if client name is duplicate. */
  5660. if (strmap_get(parsed_clients, tok->args[0])) {
  5661. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  5662. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  5663. goto err;
  5664. }
  5665. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  5666. parsed_entry->client_name = tor_strdup(tok->args[0]);
  5667. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  5668. /* Parse client key. */
  5669. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  5670. if (tok) {
  5671. parsed_entry->client_key = tok->key;
  5672. tok->key = NULL; /* Prevent free */
  5673. }
  5674. /* Parse descriptor cookie. */
  5675. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  5676. tor_assert(tok->n_args == 1);
  5677. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  5678. NULL, &err_msg) < 0) {
  5679. tor_assert(err_msg);
  5680. log_warn(LD_REND, "%s", err_msg);
  5681. tor_free(err_msg);
  5682. goto err;
  5683. }
  5684. }
  5685. result = strmap_size(parsed_clients);
  5686. goto done;
  5687. err:
  5688. result = -1;
  5689. done:
  5690. /* Free tokens and clear token list. */
  5691. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5692. smartlist_free(tokens);
  5693. if (area)
  5694. memarea_drop_all(area);
  5695. return result;
  5696. }
  5697. /** Called on startup; right now we just handle scanning the unparseable
  5698. * descriptor dumps, but hang anything else we might need to do in the
  5699. * future here as well.
  5700. */
  5701. void
  5702. routerparse_init(void)
  5703. {
  5704. /*
  5705. * Check both if the sandbox is active and whether it's configured; no
  5706. * point in loading all that if we won't be able to use it after the
  5707. * sandbox becomes active.
  5708. */
  5709. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  5710. dump_desc_init();
  5711. }
  5712. }
  5713. /** Clean up all data structures used by routerparse.c at exit */
  5714. void
  5715. routerparse_free_all(void)
  5716. {
  5717. dump_desc_fifo_cleanup();
  5718. }