routerparse.c 196 KB

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