routerparse.c 197 KB

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