routerparse.c 197 KB

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