routerparse.c 192 KB

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