routerparse.c 197 KB

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