routerparse.c 215 KB

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