routerparse.c 187 KB

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