routerparse.c 196 KB

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