routerparse.c 187 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457
  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. router->signing_key_cert = cert; /* makes sure it gets freed. */
  1273. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1274. ! cert->signing_key_included) {
  1275. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1276. goto err;
  1277. }
  1278. if (master_key_tok) {
  1279. /* This token is optional, but if it's present, it must match
  1280. * the signature in the signing cert, or supplant it. */
  1281. tor_assert(master_key_tok->n_args >= 1);
  1282. ed25519_public_key_t pkey;
  1283. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  1284. log_warn(LD_DIR, "Can't parse ed25519 master key");
  1285. goto err;
  1286. }
  1287. if (fast_memneq(&cert->signing_key.pubkey,
  1288. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  1289. log_warn(LD_DIR, "Ed25519 master key does not match "
  1290. "key in certificate");
  1291. goto err;
  1292. }
  1293. }
  1294. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  1295. cc_ntor_tok->object_size);
  1296. if (!ntor_cc_cert) {
  1297. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  1298. goto err;
  1299. }
  1300. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  1301. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  1302. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  1303. goto err;
  1304. }
  1305. ed25519_public_key_t ntor_cc_pk;
  1306. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  1307. router->onion_curve25519_pkey,
  1308. ntor_cc_sign_bit)<0) {
  1309. log_warn(LD_DIR, "Error converting onion key to ed25519");
  1310. goto err;
  1311. }
  1312. if (router_get_hash_impl_helper(s, end-s, "router ",
  1313. "\nrouter-sig-ed25519",
  1314. ' ', &signed_start, &signed_end) < 0) {
  1315. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  1316. goto err;
  1317. }
  1318. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1319. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1320. strlen(ED_DESC_SIGNATURE_PREFIX));
  1321. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1322. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1323. crypto_digest_free(d);
  1324. ed25519_checkable_t check[3];
  1325. int check_ok[3];
  1326. if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
  1327. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1328. goto err;
  1329. }
  1330. if (tor_cert_get_checkable_sig(&check[1],
  1331. ntor_cc_cert, &ntor_cc_pk) < 0) {
  1332. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  1333. goto err;
  1334. }
  1335. if (ed25519_signature_from_base64(&check[2].signature,
  1336. ed_sig_tok->args[0])<0) {
  1337. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1338. goto err;
  1339. }
  1340. check[2].pubkey = &cert->signed_key;
  1341. check[2].msg = d256;
  1342. check[2].len = DIGEST256_LEN;
  1343. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  1344. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1345. goto err;
  1346. }
  1347. if (check_tap_onion_key_crosscert(
  1348. (const uint8_t*)cc_tap_tok->object_body,
  1349. (int)cc_tap_tok->object_size,
  1350. router->onion_pkey,
  1351. &cert->signing_key,
  1352. (const uint8_t*)router->cache_info.identity_digest)<0) {
  1353. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  1354. goto err;
  1355. }
  1356. /* We check this before adding it to the routerlist. */
  1357. if (cert->valid_until < ntor_cc_cert->valid_until)
  1358. router->cert_expiration_time = cert->valid_until;
  1359. else
  1360. router->cert_expiration_time = ntor_cc_cert->valid_until;
  1361. }
  1362. }
  1363. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1364. /* If there's a fingerprint line, it must match the identity digest. */
  1365. char d[DIGEST_LEN];
  1366. tor_assert(tok->n_args == 1);
  1367. tor_strstrip(tok->args[0], " ");
  1368. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1369. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1370. escaped(tok->args[0]));
  1371. goto err;
  1372. }
  1373. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1374. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1375. tok->args[0]);
  1376. goto err;
  1377. }
  1378. }
  1379. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1380. router->platform = tor_strdup(tok->args[0]);
  1381. }
  1382. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1383. router->contact_info = tor_strdup(tok->args[0]);
  1384. }
  1385. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1386. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1387. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1388. "older Tors.");
  1389. goto err;
  1390. }
  1391. {
  1392. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1393. if (or_addresses) {
  1394. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1395. &router->ipv6_orport);
  1396. smartlist_free(or_addresses);
  1397. }
  1398. }
  1399. exit_policy_tokens = find_all_exitpolicy(tokens);
  1400. if (!smartlist_len(exit_policy_tokens)) {
  1401. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1402. goto err;
  1403. }
  1404. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1405. if (router_add_exit_policy(router,t)<0) {
  1406. log_warn(LD_DIR,"Error in exit policy");
  1407. goto err;
  1408. });
  1409. policy_expand_private(&router->exit_policy);
  1410. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1411. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1412. if (! router->ipv6_exit_policy) {
  1413. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1414. goto err;
  1415. }
  1416. }
  1417. if (policy_is_reject_star(router->exit_policy, AF_INET) &&
  1418. (!router->ipv6_exit_policy ||
  1419. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1420. router->policy_is_reject_star = 1;
  1421. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1422. int i;
  1423. router->declared_family = smartlist_new();
  1424. for (i=0;i<tok->n_args;++i) {
  1425. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1426. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1427. escaped(tok->args[i]));
  1428. goto err;
  1429. }
  1430. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1431. }
  1432. }
  1433. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1434. router->caches_extra_info = 1;
  1435. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1436. router->allow_single_hop_exits = 1;
  1437. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1438. tor_assert(tok->n_args >= 1);
  1439. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1440. base16_decode(router->cache_info.extra_info_digest,
  1441. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1442. } else {
  1443. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1444. }
  1445. if (tok->n_args >= 2) {
  1446. if (digest256_from_base64(router->extra_info_digest256, tok->args[1])
  1447. < 0) {
  1448. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  1449. escaped(tok->args[1]));
  1450. }
  1451. }
  1452. }
  1453. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1454. router->wants_to_be_hs_dir = 1;
  1455. }
  1456. /* This router accepts tunnelled directory requests via begindir if it has
  1457. * an open dirport or it included "tunnelled-dir-server". */
  1458. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1459. router->supports_tunnelled_dir_requests = 1;
  1460. }
  1461. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1462. note_crypto_pk_op(VERIFY_RTR);
  1463. #ifdef COUNT_DISTINCT_DIGESTS
  1464. if (!verified_digests)
  1465. verified_digests = digestmap_new();
  1466. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1467. #endif
  1468. if (!router->or_port) {
  1469. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1470. goto err;
  1471. }
  1472. /* We've checked everything that's covered by the hash. */
  1473. can_dl_again = 1;
  1474. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1475. "router descriptor") < 0)
  1476. goto err;
  1477. if (!router->platform) {
  1478. router->platform = tor_strdup("<unknown>");
  1479. }
  1480. goto done;
  1481. err:
  1482. dump_desc(s_dup, "router descriptor");
  1483. routerinfo_free(router);
  1484. router = NULL;
  1485. done:
  1486. tor_cert_free(ntor_cc_cert);
  1487. if (tokens) {
  1488. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1489. smartlist_free(tokens);
  1490. }
  1491. smartlist_free(exit_policy_tokens);
  1492. if (area) {
  1493. DUMP_AREA(area, "routerinfo");
  1494. memarea_drop_all(area);
  1495. }
  1496. if (can_dl_again_out)
  1497. *can_dl_again_out = can_dl_again;
  1498. return router;
  1499. }
  1500. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1501. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1502. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1503. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1504. * as a map from router identity to routerinfo_t when looking up signing keys.
  1505. *
  1506. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1507. * if it's okay to try to download an extrainfo with this same digest again,
  1508. * and 0 if it isn't. (It might not be okay to download it again if part of
  1509. * the part covered by the digest is invalid.)
  1510. */
  1511. extrainfo_t *
  1512. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1513. int cache_copy, struct digest_ri_map_t *routermap,
  1514. int *can_dl_again_out)
  1515. {
  1516. extrainfo_t *extrainfo = NULL;
  1517. char digest[128];
  1518. smartlist_t *tokens = NULL;
  1519. directory_token_t *tok;
  1520. crypto_pk_t *key = NULL;
  1521. routerinfo_t *router = NULL;
  1522. memarea_t *area = NULL;
  1523. const char *s_dup = s;
  1524. /* Do not set this to '1' until we have parsed everything that we intend to
  1525. * parse that's covered by the hash. */
  1526. int can_dl_again = 0;
  1527. if (!end) {
  1528. end = s + strlen(s);
  1529. }
  1530. /* point 'end' to a point immediately after the final newline. */
  1531. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1532. --end;
  1533. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1534. log_warn(LD_DIR, "Couldn't compute router hash.");
  1535. goto err;
  1536. }
  1537. tokens = smartlist_new();
  1538. area = memarea_new();
  1539. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1540. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1541. goto err;
  1542. }
  1543. if (smartlist_len(tokens) < 2) {
  1544. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1545. goto err;
  1546. }
  1547. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  1548. tok = smartlist_get(tokens,0);
  1549. if (tok->tp != K_EXTRA_INFO) {
  1550. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1551. goto err;
  1552. }
  1553. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1554. extrainfo->cache_info.is_extrainfo = 1;
  1555. if (cache_copy)
  1556. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  1557. extrainfo->cache_info.signed_descriptor_len = end-s;
  1558. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1559. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  1560. tor_assert(tok->n_args >= 2);
  1561. if (!is_legal_nickname(tok->args[0])) {
  1562. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1563. goto err;
  1564. }
  1565. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1566. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1567. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1568. tok->args[1], HEX_DIGEST_LEN)) {
  1569. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1570. escaped(tok->args[1]));
  1571. goto err;
  1572. }
  1573. tok = find_by_keyword(tokens, K_PUBLISHED);
  1574. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1575. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1576. escaped(tok->args[0]));
  1577. goto err;
  1578. }
  1579. {
  1580. directory_token_t *ed_sig_tok, *ed_cert_tok;
  1581. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1582. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1583. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  1584. if (n_ed_toks != 0 && n_ed_toks != 2) {
  1585. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1586. "cross-certification support");
  1587. goto err;
  1588. }
  1589. if (ed_sig_tok) {
  1590. tor_assert(ed_cert_tok);
  1591. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1592. if (ed_cert_token_pos != 1) {
  1593. /* Accept this in position 0 XXXX */
  1594. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1595. goto err;
  1596. }
  1597. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1598. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1599. goto err;
  1600. }
  1601. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1602. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1603. goto err;
  1604. }
  1605. uint8_t d256[DIGEST256_LEN];
  1606. const char *signed_start, *signed_end;
  1607. tor_cert_t *cert = tor_cert_parse(
  1608. (const uint8_t*)ed_cert_tok->object_body,
  1609. ed_cert_tok->object_size);
  1610. if (! cert) {
  1611. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1612. goto err;
  1613. }
  1614. extrainfo->signing_key_cert = cert; /* makes sure it gets freed. */
  1615. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1616. ! cert->signing_key_included) {
  1617. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1618. goto err;
  1619. }
  1620. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1621. "\nrouter-sig-ed25519",
  1622. ' ', &signed_start, &signed_end) < 0) {
  1623. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1624. goto err;
  1625. }
  1626. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1627. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1628. strlen(ED_DESC_SIGNATURE_PREFIX));
  1629. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1630. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1631. crypto_digest_free(d);
  1632. ed25519_checkable_t check[2];
  1633. int check_ok[2];
  1634. if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
  1635. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1636. goto err;
  1637. }
  1638. if (ed25519_signature_from_base64(&check[1].signature,
  1639. ed_sig_tok->args[0])<0) {
  1640. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1641. goto err;
  1642. }
  1643. check[1].pubkey = &cert->signed_key;
  1644. check[1].msg = d256;
  1645. check[1].len = DIGEST256_LEN;
  1646. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1647. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1648. goto err;
  1649. }
  1650. /* We don't check the certificate expiration time: checking that it
  1651. * matches the cert in the router descriptor is adequate. */
  1652. }
  1653. }
  1654. /* We've checked everything that's covered by the hash. */
  1655. can_dl_again = 1;
  1656. if (routermap &&
  1657. (router = digestmap_get((digestmap_t*)routermap,
  1658. extrainfo->cache_info.identity_digest))) {
  1659. key = router->identity_pkey;
  1660. }
  1661. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1662. if (strcmp(tok->object_type, "SIGNATURE") ||
  1663. tok->object_size < 128 || tok->object_size > 512) {
  1664. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1665. goto err;
  1666. }
  1667. if (key) {
  1668. note_crypto_pk_op(VERIFY_RTR);
  1669. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1670. "extra-info") < 0)
  1671. goto err;
  1672. if (router)
  1673. extrainfo->cache_info.send_unencrypted =
  1674. router->cache_info.send_unencrypted;
  1675. } else {
  1676. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1677. tok->object_size);
  1678. extrainfo->pending_sig_len = tok->object_size;
  1679. }
  1680. goto done;
  1681. err:
  1682. dump_desc(s_dup, "extra-info descriptor");
  1683. extrainfo_free(extrainfo);
  1684. extrainfo = NULL;
  1685. done:
  1686. if (tokens) {
  1687. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1688. smartlist_free(tokens);
  1689. }
  1690. if (area) {
  1691. DUMP_AREA(area, "extrainfo");
  1692. memarea_drop_all(area);
  1693. }
  1694. if (can_dl_again_out)
  1695. *can_dl_again_out = can_dl_again;
  1696. return extrainfo;
  1697. }
  1698. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1699. * the first character after the certificate. */
  1700. authority_cert_t *
  1701. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1702. {
  1703. /** Reject any certificate at least this big; it is probably an overflow, an
  1704. * attack, a bug, or some other nonsense. */
  1705. #define MAX_CERT_SIZE (128*1024)
  1706. authority_cert_t *cert = NULL, *old_cert;
  1707. smartlist_t *tokens = NULL;
  1708. char digest[DIGEST_LEN];
  1709. directory_token_t *tok;
  1710. char fp_declared[DIGEST_LEN];
  1711. char *eos;
  1712. size_t len;
  1713. int found;
  1714. memarea_t *area = NULL;
  1715. const char *s_dup = s;
  1716. s = eat_whitespace(s);
  1717. eos = strstr(s, "\ndir-key-certification");
  1718. if (! eos) {
  1719. log_warn(LD_DIR, "No signature found on key certificate");
  1720. return NULL;
  1721. }
  1722. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1723. if (! eos) {
  1724. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1725. return NULL;
  1726. }
  1727. eos = strchr(eos+2, '\n');
  1728. tor_assert(eos);
  1729. ++eos;
  1730. len = eos - s;
  1731. if (len > MAX_CERT_SIZE) {
  1732. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  1733. "rejecting", (unsigned long)len);
  1734. return NULL;
  1735. }
  1736. tokens = smartlist_new();
  1737. area = memarea_new();
  1738. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1739. log_warn(LD_DIR, "Error tokenizing key certificate");
  1740. goto err;
  1741. }
  1742. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  1743. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  1744. goto err;
  1745. tok = smartlist_get(tokens, 0);
  1746. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1747. log_warn(LD_DIR,
  1748. "Key certificate does not begin with a recognized version (3).");
  1749. goto err;
  1750. }
  1751. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1752. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1753. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1754. tor_assert(tok->key);
  1755. cert->signing_key = tok->key;
  1756. tok->key = NULL;
  1757. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1758. goto err;
  1759. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1760. tor_assert(tok->key);
  1761. cert->identity_key = tok->key;
  1762. tok->key = NULL;
  1763. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1764. tor_assert(tok->n_args);
  1765. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1766. strlen(tok->args[0]))) {
  1767. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1768. escaped(tok->args[0]));
  1769. goto err;
  1770. }
  1771. if (crypto_pk_get_digest(cert->identity_key,
  1772. cert->cache_info.identity_digest))
  1773. goto err;
  1774. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1775. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1776. "fingerprint");
  1777. goto err;
  1778. }
  1779. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1780. if (tok) {
  1781. struct in_addr in;
  1782. char *address = NULL;
  1783. tor_assert(tok->n_args);
  1784. /* XXX024 use some tor_addr parse function below instead. -RD */
  1785. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  1786. &cert->dir_port) < 0 ||
  1787. tor_inet_aton(address, &in) == 0) {
  1788. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1789. tor_free(address);
  1790. goto err;
  1791. }
  1792. cert->addr = ntohl(in.s_addr);
  1793. tor_free(address);
  1794. }
  1795. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1796. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1797. goto err;
  1798. }
  1799. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1800. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1801. goto err;
  1802. }
  1803. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1804. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1805. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1806. goto err;
  1807. }
  1808. /* If we already have this cert, don't bother checking the signature. */
  1809. old_cert = authority_cert_get_by_digests(
  1810. cert->cache_info.identity_digest,
  1811. cert->signing_key_digest);
  1812. found = 0;
  1813. if (old_cert) {
  1814. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1815. * buy us much. */
  1816. if (old_cert->cache_info.signed_descriptor_len == len &&
  1817. old_cert->cache_info.signed_descriptor_body &&
  1818. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1819. log_debug(LD_DIR, "We already checked the signature on this "
  1820. "certificate; no need to do so again.");
  1821. found = 1;
  1822. }
  1823. }
  1824. if (!found) {
  1825. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  1826. "key certificate")) {
  1827. goto err;
  1828. }
  1829. tok = find_by_keyword(tokens, K_DIR_KEY_CROSSCERT);
  1830. if (check_signature_token(cert->cache_info.identity_digest,
  1831. DIGEST_LEN,
  1832. tok,
  1833. cert->signing_key,
  1834. CST_NO_CHECK_OBJTYPE,
  1835. "key cross-certification")) {
  1836. goto err;
  1837. }
  1838. }
  1839. cert->cache_info.signed_descriptor_len = len;
  1840. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1841. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1842. cert->cache_info.signed_descriptor_body[len] = 0;
  1843. cert->cache_info.saved_location = SAVED_NOWHERE;
  1844. if (end_of_string) {
  1845. *end_of_string = eat_whitespace(eos);
  1846. }
  1847. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1848. smartlist_free(tokens);
  1849. if (area) {
  1850. DUMP_AREA(area, "authority cert");
  1851. memarea_drop_all(area);
  1852. }
  1853. return cert;
  1854. err:
  1855. dump_desc(s_dup, "authority cert");
  1856. authority_cert_free(cert);
  1857. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1858. smartlist_free(tokens);
  1859. if (area) {
  1860. DUMP_AREA(area, "authority cert");
  1861. memarea_drop_all(area);
  1862. }
  1863. return NULL;
  1864. }
  1865. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1866. * object (starting with "r " at the start of a line). If none is found,
  1867. * return the start of the directory footer, or the next directory signature.
  1868. * If none is found, return the end of the string. */
  1869. static inline const char *
  1870. find_start_of_next_routerstatus(const char *s)
  1871. {
  1872. const char *eos, *footer, *sig;
  1873. if ((eos = strstr(s, "\nr ")))
  1874. ++eos;
  1875. else
  1876. eos = s + strlen(s);
  1877. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  1878. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  1879. if (footer && sig)
  1880. return MIN(footer, sig) + 1;
  1881. else if (footer)
  1882. return footer+1;
  1883. else if (sig)
  1884. return sig+1;
  1885. else
  1886. return eos;
  1887. }
  1888. /** Parse the GuardFraction string from a consensus or vote.
  1889. *
  1890. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  1891. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  1892. * the same semantic as in routerstatus_parse_entry_from_string(). */
  1893. STATIC int
  1894. routerstatus_parse_guardfraction(const char *guardfraction_str,
  1895. networkstatus_t *vote,
  1896. vote_routerstatus_t *vote_rs,
  1897. routerstatus_t *rs)
  1898. {
  1899. int ok;
  1900. const char *end_of_header = NULL;
  1901. int is_consensus = !vote_rs;
  1902. uint32_t guardfraction;
  1903. tor_assert(bool_eq(vote, vote_rs));
  1904. /* If this info comes from a consensus, but we should't apply
  1905. guardfraction, just exit. */
  1906. if (is_consensus && !should_apply_guardfraction(NULL)) {
  1907. return 0;
  1908. }
  1909. end_of_header = strchr(guardfraction_str, '=');
  1910. if (!end_of_header) {
  1911. return -1;
  1912. }
  1913. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  1914. 10, 0, 100, &ok, NULL);
  1915. if (!ok) {
  1916. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  1917. return -1;
  1918. }
  1919. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  1920. is_consensus ? "consensus" : "vote",
  1921. guardfraction_str, rs->nickname);
  1922. if (!is_consensus) { /* We are parsing a vote */
  1923. vote_rs->status.guardfraction_percentage = guardfraction;
  1924. vote_rs->status.has_guardfraction = 1;
  1925. } else {
  1926. /* We are parsing a consensus. Only apply guardfraction to guards. */
  1927. if (rs->is_possible_guard) {
  1928. rs->guardfraction_percentage = guardfraction;
  1929. rs->has_guardfraction = 1;
  1930. } else {
  1931. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  1932. "This is not supposed to happen. Not applying. ", rs->nickname);
  1933. }
  1934. }
  1935. return 0;
  1936. }
  1937. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1938. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1939. * object in the string, and advance *<b>s</b> to just after the end of the
  1940. * router status. Return NULL and advance *<b>s</b> on error.
  1941. *
  1942. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1943. * routerstatus but use <b>vote_rs</b> instead.
  1944. *
  1945. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1946. * consensus, and we should parse it according to the method used to
  1947. * make that consensus.
  1948. *
  1949. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  1950. **/
  1951. static routerstatus_t *
  1952. routerstatus_parse_entry_from_string(memarea_t *area,
  1953. const char **s, smartlist_t *tokens,
  1954. networkstatus_t *vote,
  1955. vote_routerstatus_t *vote_rs,
  1956. int consensus_method,
  1957. consensus_flavor_t flav)
  1958. {
  1959. const char *eos, *s_dup = *s;
  1960. routerstatus_t *rs = NULL;
  1961. directory_token_t *tok;
  1962. char timebuf[ISO_TIME_LEN+1];
  1963. struct in_addr in;
  1964. int offset = 0;
  1965. tor_assert(tokens);
  1966. tor_assert(bool_eq(vote, vote_rs));
  1967. if (!consensus_method)
  1968. flav = FLAV_NS;
  1969. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  1970. eos = find_start_of_next_routerstatus(*s);
  1971. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1972. log_warn(LD_DIR, "Error tokenizing router status");
  1973. goto err;
  1974. }
  1975. if (smartlist_len(tokens) < 1) {
  1976. log_warn(LD_DIR, "Impossibly short router status");
  1977. goto err;
  1978. }
  1979. tok = find_by_keyword(tokens, K_R);
  1980. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  1981. if (flav == FLAV_NS) {
  1982. if (tok->n_args < 8) {
  1983. log_warn(LD_DIR, "Too few arguments to r");
  1984. goto err;
  1985. }
  1986. } else if (flav == FLAV_MICRODESC) {
  1987. offset = -1; /* There is no identity digest */
  1988. }
  1989. if (vote_rs) {
  1990. rs = &vote_rs->status;
  1991. } else {
  1992. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1993. }
  1994. if (!is_legal_nickname(tok->args[0])) {
  1995. log_warn(LD_DIR,
  1996. "Invalid nickname %s in router status; skipping.",
  1997. escaped(tok->args[0]));
  1998. goto err;
  1999. }
  2000. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  2001. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  2002. log_warn(LD_DIR, "Error decoding identity digest %s",
  2003. escaped(tok->args[1]));
  2004. goto err;
  2005. }
  2006. if (flav == FLAV_NS) {
  2007. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  2008. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  2009. escaped(tok->args[2]));
  2010. goto err;
  2011. }
  2012. }
  2013. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  2014. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  2015. parse_iso_time(timebuf, &rs->published_on)<0) {
  2016. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  2017. tok->args[3+offset], tok->args[4+offset],
  2018. offset, (int)flav);
  2019. goto err;
  2020. }
  2021. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  2022. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  2023. escaped(tok->args[5+offset]));
  2024. goto err;
  2025. }
  2026. rs->addr = ntohl(in.s_addr);
  2027. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  2028. 10,0,65535,NULL,NULL);
  2029. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  2030. 10,0,65535,NULL,NULL);
  2031. {
  2032. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  2033. if (a_lines) {
  2034. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  2035. smartlist_free(a_lines);
  2036. }
  2037. }
  2038. tok = find_opt_by_keyword(tokens, K_S);
  2039. if (tok && vote) {
  2040. int i;
  2041. vote_rs->flags = 0;
  2042. for (i=0; i < tok->n_args; ++i) {
  2043. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  2044. if (p >= 0) {
  2045. vote_rs->flags |= (U64_LITERAL(1)<<p);
  2046. } else {
  2047. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  2048. escaped(tok->args[i]));
  2049. goto err;
  2050. }
  2051. }
  2052. } else if (tok) {
  2053. int i;
  2054. for (i=0; i < tok->n_args; ++i) {
  2055. if (!strcmp(tok->args[i], "Exit"))
  2056. rs->is_exit = 1;
  2057. else if (!strcmp(tok->args[i], "Stable"))
  2058. rs->is_stable = 1;
  2059. else if (!strcmp(tok->args[i], "Fast"))
  2060. rs->is_fast = 1;
  2061. else if (!strcmp(tok->args[i], "Running"))
  2062. rs->is_flagged_running = 1;
  2063. else if (!strcmp(tok->args[i], "Named"))
  2064. rs->is_named = 1;
  2065. else if (!strcmp(tok->args[i], "Valid"))
  2066. rs->is_valid = 1;
  2067. else if (!strcmp(tok->args[i], "Guard"))
  2068. rs->is_possible_guard = 1;
  2069. else if (!strcmp(tok->args[i], "BadExit"))
  2070. rs->is_bad_exit = 1;
  2071. else if (!strcmp(tok->args[i], "Authority"))
  2072. rs->is_authority = 1;
  2073. else if (!strcmp(tok->args[i], "Unnamed") &&
  2074. consensus_method >= 2) {
  2075. /* Unnamed is computed right by consensus method 2 and later. */
  2076. rs->is_unnamed = 1;
  2077. } else if (!strcmp(tok->args[i], "HSDir")) {
  2078. rs->is_hs_dir = 1;
  2079. } else if (!strcmp(tok->args[i], "V2Dir")) {
  2080. rs->is_v2_dir = 1;
  2081. }
  2082. }
  2083. }
  2084. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  2085. tor_assert(tok->n_args == 1);
  2086. rs->version_known = 1;
  2087. if (strcmpstart(tok->args[0], "Tor ")) {
  2088. } else {
  2089. rs->version_supports_extend2_cells =
  2090. tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
  2091. }
  2092. if (vote_rs) {
  2093. vote_rs->version = tor_strdup(tok->args[0]);
  2094. }
  2095. }
  2096. /* handle weighting/bandwidth info */
  2097. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  2098. int i;
  2099. for (i=0; i < tok->n_args; ++i) {
  2100. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  2101. int ok;
  2102. rs->bandwidth_kb =
  2103. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2104. 10, 0, UINT32_MAX,
  2105. &ok, NULL);
  2106. if (!ok) {
  2107. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  2108. goto err;
  2109. }
  2110. rs->has_bandwidth = 1;
  2111. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  2112. int ok;
  2113. vote_rs->measured_bw_kb =
  2114. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2115. 10, 0, UINT32_MAX, &ok, NULL);
  2116. if (!ok) {
  2117. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  2118. escaped(tok->args[i]));
  2119. goto err;
  2120. }
  2121. vote_rs->has_measured_bw = 1;
  2122. vote->has_measured_bws = 1;
  2123. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  2124. rs->bw_is_unmeasured = 1;
  2125. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  2126. if (routerstatus_parse_guardfraction(tok->args[i],
  2127. vote, vote_rs, rs) < 0) {
  2128. goto err;
  2129. }
  2130. }
  2131. }
  2132. }
  2133. /* parse exit policy summaries */
  2134. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  2135. tor_assert(tok->n_args == 1);
  2136. if (strcmpstart(tok->args[0], "accept ") &&
  2137. strcmpstart(tok->args[0], "reject ")) {
  2138. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  2139. escaped(tok->args[0]));
  2140. goto err;
  2141. }
  2142. /* XXX weasel: parse this into ports and represent them somehow smart,
  2143. * maybe not here but somewhere on if we need it for the client.
  2144. * we should still parse it here to check it's valid tho.
  2145. */
  2146. rs->exitsummary = tor_strdup(tok->args[0]);
  2147. rs->has_exitsummary = 1;
  2148. }
  2149. if (vote_rs) {
  2150. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2151. if (t->tp == K_M && t->n_args) {
  2152. vote_microdesc_hash_t *line =
  2153. tor_malloc(sizeof(vote_microdesc_hash_t));
  2154. line->next = vote_rs->microdesc;
  2155. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2156. vote_rs->microdesc = line;
  2157. }
  2158. if (t->tp == K_ID) {
  2159. tor_assert(t->n_args >= 2);
  2160. if (!strcmp(t->args[0], "ed25519")) {
  2161. vote_rs->has_ed25519_listing = 1;
  2162. if (strcmp(t->args[1], "none") &&
  2163. digest256_from_base64((char*)vote_rs->ed25519_id,
  2164. t->args[1])<0) {
  2165. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  2166. goto err;
  2167. }
  2168. }
  2169. }
  2170. } SMARTLIST_FOREACH_END(t);
  2171. } else if (flav == FLAV_MICRODESC) {
  2172. tok = find_opt_by_keyword(tokens, K_M);
  2173. if (tok) {
  2174. tor_assert(tok->n_args);
  2175. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2176. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2177. escaped(tok->args[0]));
  2178. goto err;
  2179. }
  2180. } else {
  2181. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2182. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  2183. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2184. fmt_addr32(rs->addr), rs->or_port);
  2185. }
  2186. }
  2187. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2188. rs->is_named = 0;
  2189. goto done;
  2190. err:
  2191. dump_desc(s_dup, "routerstatus entry");
  2192. if (rs && !vote_rs)
  2193. routerstatus_free(rs);
  2194. rs = NULL;
  2195. done:
  2196. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2197. smartlist_clear(tokens);
  2198. if (area) {
  2199. DUMP_AREA(area, "routerstatus entry");
  2200. memarea_clear(area);
  2201. }
  2202. *s = eos;
  2203. return rs;
  2204. }
  2205. int
  2206. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  2207. {
  2208. const vote_routerstatus_t *a = *_a, *b = *_b;
  2209. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  2210. DIGEST_LEN);
  2211. }
  2212. /** Verify the bandwidth weights of a network status document */
  2213. int
  2214. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  2215. {
  2216. int64_t weight_scale;
  2217. int64_t G=0, M=0, E=0, D=0, T=0;
  2218. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2219. double Gtotal=0, Mtotal=0, Etotal=0;
  2220. const char *casename = NULL;
  2221. int valid = 1;
  2222. (void) consensus_method;
  2223. weight_scale = networkstatus_get_weight_scale_param(ns);
  2224. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2225. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2226. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2227. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2228. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2229. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2230. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2231. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2232. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2233. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2234. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2235. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2236. || Wem<0 || Wee<0 || Wed<0) {
  2237. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2238. return 0;
  2239. }
  2240. // First, sanity check basic summing properties that hold for all cases
  2241. // We use > 1 as the check for these because they are computed as integers.
  2242. // Sometimes there are rounding errors.
  2243. if (fabs(Wmm - weight_scale) > 1) {
  2244. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2245. Wmm, I64_PRINTF_ARG(weight_scale));
  2246. valid = 0;
  2247. }
  2248. if (fabs(Wem - Wee) > 1) {
  2249. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2250. valid = 0;
  2251. }
  2252. if (fabs(Wgm - Wgg) > 1) {
  2253. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2254. valid = 0;
  2255. }
  2256. if (fabs(Weg - Wed) > 1) {
  2257. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2258. valid = 0;
  2259. }
  2260. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2261. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2262. I64_PRINTF_ARG(weight_scale), Wmg);
  2263. valid = 0;
  2264. }
  2265. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2266. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2267. I64_PRINTF_ARG(weight_scale), Wme);
  2268. valid = 0;
  2269. }
  2270. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2271. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2272. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2273. valid = 0;
  2274. }
  2275. Wgg /= weight_scale;
  2276. Wgm /= weight_scale;
  2277. Wgd /= weight_scale;
  2278. Wmg /= weight_scale;
  2279. Wmm /= weight_scale;
  2280. Wme /= weight_scale;
  2281. Wmd /= weight_scale;
  2282. Weg /= weight_scale;
  2283. Wem /= weight_scale;
  2284. Wee /= weight_scale;
  2285. Wed /= weight_scale;
  2286. // Then, gather G, M, E, D, T to determine case
  2287. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2288. int is_exit = 0;
  2289. /* Bug #2203: Don't count bad exits as exits for balancing */
  2290. is_exit = rs->is_exit && !rs->is_bad_exit;
  2291. if (rs->has_bandwidth) {
  2292. T += rs->bandwidth_kb;
  2293. if (is_exit && rs->is_possible_guard) {
  2294. D += rs->bandwidth_kb;
  2295. Gtotal += Wgd*rs->bandwidth_kb;
  2296. Mtotal += Wmd*rs->bandwidth_kb;
  2297. Etotal += Wed*rs->bandwidth_kb;
  2298. } else if (is_exit) {
  2299. E += rs->bandwidth_kb;
  2300. Mtotal += Wme*rs->bandwidth_kb;
  2301. Etotal += Wee*rs->bandwidth_kb;
  2302. } else if (rs->is_possible_guard) {
  2303. G += rs->bandwidth_kb;
  2304. Gtotal += Wgg*rs->bandwidth_kb;
  2305. Mtotal += Wmg*rs->bandwidth_kb;
  2306. } else {
  2307. M += rs->bandwidth_kb;
  2308. Mtotal += Wmm*rs->bandwidth_kb;
  2309. }
  2310. } else {
  2311. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2312. routerstatus_describe(rs));
  2313. }
  2314. } SMARTLIST_FOREACH_END(rs);
  2315. // Finally, check equality conditions depending upon case 1, 2 or 3
  2316. // Full equality cases: 1, 3b
  2317. // Partial equality cases: 2b (E=G), 3a (M=E)
  2318. // Fully unknown: 2a
  2319. if (3*E >= T && 3*G >= T) {
  2320. // Case 1: Neither are scarce
  2321. casename = "Case 1";
  2322. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2323. log_warn(LD_DIR,
  2324. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2325. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2326. " T="I64_FORMAT". "
  2327. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2328. casename, Etotal, Mtotal,
  2329. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2330. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2331. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2332. valid = 0;
  2333. }
  2334. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2335. log_warn(LD_DIR,
  2336. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2337. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2338. " T="I64_FORMAT". "
  2339. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2340. casename, Etotal, Gtotal,
  2341. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2342. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2343. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2344. valid = 0;
  2345. }
  2346. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2347. log_warn(LD_DIR,
  2348. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2349. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2350. " T="I64_FORMAT". "
  2351. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2352. casename, Mtotal, Gtotal,
  2353. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2354. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2355. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2356. valid = 0;
  2357. }
  2358. } else if (3*E < T && 3*G < T) {
  2359. int64_t R = MIN(E, G);
  2360. int64_t S = MAX(E, G);
  2361. /*
  2362. * Case 2: Both Guards and Exits are scarce
  2363. * Balance D between E and G, depending upon
  2364. * D capacity and scarcity. Devote no extra
  2365. * bandwidth to middle nodes.
  2366. */
  2367. if (R+D < S) { // Subcase a
  2368. double Rtotal, Stotal;
  2369. if (E < G) {
  2370. Rtotal = Etotal;
  2371. Stotal = Gtotal;
  2372. } else {
  2373. Rtotal = Gtotal;
  2374. Stotal = Etotal;
  2375. }
  2376. casename = "Case 2a";
  2377. // Rtotal < Stotal
  2378. if (Rtotal > Stotal) {
  2379. log_warn(LD_DIR,
  2380. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2381. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2382. " T="I64_FORMAT". "
  2383. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2384. casename, Rtotal, Stotal,
  2385. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2386. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2387. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2388. valid = 0;
  2389. }
  2390. // Rtotal < T/3
  2391. if (3*Rtotal > T) {
  2392. log_warn(LD_DIR,
  2393. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2394. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2395. " D="I64_FORMAT" T="I64_FORMAT". "
  2396. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2397. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2398. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2399. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2400. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2401. valid = 0;
  2402. }
  2403. // Stotal < T/3
  2404. if (3*Stotal > T) {
  2405. log_warn(LD_DIR,
  2406. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2407. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2408. " D="I64_FORMAT" T="I64_FORMAT". "
  2409. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2410. casename, Stotal*3, I64_PRINTF_ARG(T),
  2411. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2412. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2413. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2414. valid = 0;
  2415. }
  2416. // Mtotal > T/3
  2417. if (3*Mtotal < T) {
  2418. log_warn(LD_DIR,
  2419. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2420. I64_FORMAT". "
  2421. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2422. " T="I64_FORMAT". "
  2423. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2424. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2425. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2426. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2427. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2428. valid = 0;
  2429. }
  2430. } else { // Subcase b: R+D > S
  2431. casename = "Case 2b";
  2432. /* Check the rare-M redirect case. */
  2433. if (D != 0 && 3*M < T) {
  2434. casename = "Case 2b (balanced)";
  2435. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2436. log_warn(LD_DIR,
  2437. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2438. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2439. " T="I64_FORMAT". "
  2440. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2441. casename, Etotal, Mtotal,
  2442. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2443. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2444. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2445. valid = 0;
  2446. }
  2447. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2448. log_warn(LD_DIR,
  2449. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2450. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2451. " T="I64_FORMAT". "
  2452. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2453. casename, Etotal, Gtotal,
  2454. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2455. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2456. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2457. valid = 0;
  2458. }
  2459. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2460. log_warn(LD_DIR,
  2461. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2462. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2463. " T="I64_FORMAT". "
  2464. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2465. casename, Mtotal, Gtotal,
  2466. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2467. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2468. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2469. valid = 0;
  2470. }
  2471. } else {
  2472. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2473. log_warn(LD_DIR,
  2474. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2475. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2476. " T="I64_FORMAT". "
  2477. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2478. casename, Etotal, Gtotal,
  2479. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2480. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2481. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2482. valid = 0;
  2483. }
  2484. }
  2485. }
  2486. } else { // if (E < T/3 || G < T/3) {
  2487. int64_t S = MIN(E, G);
  2488. int64_t NS = MAX(E, G);
  2489. if (3*(S+D) < T) { // Subcase a:
  2490. double Stotal;
  2491. double NStotal;
  2492. if (G < E) {
  2493. casename = "Case 3a (G scarce)";
  2494. Stotal = Gtotal;
  2495. NStotal = Etotal;
  2496. } else { // if (G >= E) {
  2497. casename = "Case 3a (E scarce)";
  2498. NStotal = Gtotal;
  2499. Stotal = Etotal;
  2500. }
  2501. // Stotal < T/3
  2502. if (3*Stotal > T) {
  2503. log_warn(LD_DIR,
  2504. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2505. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2506. " D="I64_FORMAT" T="I64_FORMAT". "
  2507. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2508. casename, Stotal*3, I64_PRINTF_ARG(T),
  2509. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2510. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2511. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2512. valid = 0;
  2513. }
  2514. if (NS >= M) {
  2515. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  2516. log_warn(LD_DIR,
  2517. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  2518. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2519. " T="I64_FORMAT". "
  2520. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2521. casename, NStotal, Mtotal,
  2522. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2523. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2524. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2525. valid = 0;
  2526. }
  2527. } else {
  2528. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  2529. if (3*NStotal < T) {
  2530. log_warn(LD_DIR,
  2531. "Bw Weight Failure for %s: 3*NStotal %f < T "
  2532. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  2533. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  2534. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2535. casename, NStotal*3, I64_PRINTF_ARG(T),
  2536. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2537. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2538. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2539. valid = 0;
  2540. }
  2541. }
  2542. } else { // Subcase b: S+D >= T/3
  2543. casename = "Case 3b";
  2544. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2545. log_warn(LD_DIR,
  2546. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2547. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2548. " T="I64_FORMAT". "
  2549. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2550. casename, Etotal, Mtotal,
  2551. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2552. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2553. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2554. valid = 0;
  2555. }
  2556. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2557. log_warn(LD_DIR,
  2558. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2559. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2560. " T="I64_FORMAT". "
  2561. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2562. casename, Etotal, Gtotal,
  2563. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2564. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2565. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2566. valid = 0;
  2567. }
  2568. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2569. log_warn(LD_DIR,
  2570. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2571. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2572. " T="I64_FORMAT". "
  2573. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2574. casename, Mtotal, Gtotal,
  2575. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2576. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2577. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2578. valid = 0;
  2579. }
  2580. }
  2581. }
  2582. if (valid)
  2583. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2584. casename);
  2585. return valid;
  2586. }
  2587. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  2588. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  2589. networkstatus_t *
  2590. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  2591. networkstatus_type_t ns_type)
  2592. {
  2593. smartlist_t *tokens = smartlist_new();
  2594. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  2595. networkstatus_voter_info_t *voter = NULL;
  2596. networkstatus_t *ns = NULL;
  2597. common_digests_t ns_digests;
  2598. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  2599. directory_token_t *tok;
  2600. int ok;
  2601. struct in_addr in;
  2602. int i, inorder, n_signatures = 0;
  2603. memarea_t *area = NULL, *rs_area = NULL;
  2604. consensus_flavor_t flav = FLAV_NS;
  2605. char *last_kwd=NULL;
  2606. tor_assert(s);
  2607. if (eos_out)
  2608. *eos_out = NULL;
  2609. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  2610. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2611. goto err;
  2612. }
  2613. area = memarea_new();
  2614. end_of_header = find_start_of_next_routerstatus(s);
  2615. if (tokenize_string(area, s, end_of_header, tokens,
  2616. (ns_type == NS_TYPE_CONSENSUS) ?
  2617. networkstatus_consensus_token_table :
  2618. networkstatus_token_table, 0)) {
  2619. log_warn(LD_DIR, "Error tokenizing network-status header");
  2620. goto err;
  2621. }
  2622. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2623. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  2624. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2625. tor_assert(tok);
  2626. if (tok->n_args > 1) {
  2627. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  2628. if (flavor < 0) {
  2629. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  2630. escaped(tok->args[1]));
  2631. goto err;
  2632. }
  2633. ns->flavor = flav = flavor;
  2634. }
  2635. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  2636. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  2637. goto err;
  2638. }
  2639. if (ns_type != NS_TYPE_CONSENSUS) {
  2640. const char *end_of_cert = NULL;
  2641. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2642. goto err;
  2643. ++cert;
  2644. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2645. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2646. goto err;
  2647. }
  2648. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2649. tor_assert(tok->n_args);
  2650. if (!strcmp(tok->args[0], "vote")) {
  2651. ns->type = NS_TYPE_VOTE;
  2652. } else if (!strcmp(tok->args[0], "consensus")) {
  2653. ns->type = NS_TYPE_CONSENSUS;
  2654. } else if (!strcmp(tok->args[0], "opinion")) {
  2655. ns->type = NS_TYPE_OPINION;
  2656. } else {
  2657. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2658. escaped(tok->args[0]));
  2659. goto err;
  2660. }
  2661. if (ns_type != ns->type) {
  2662. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2663. goto err;
  2664. }
  2665. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2666. tok = find_by_keyword(tokens, K_PUBLISHED);
  2667. if (parse_iso_time(tok->args[0], &ns->published))
  2668. goto err;
  2669. ns->supported_methods = smartlist_new();
  2670. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2671. if (tok) {
  2672. for (i=0; i < tok->n_args; ++i)
  2673. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2674. } else {
  2675. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2676. }
  2677. } else {
  2678. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2679. if (tok) {
  2680. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2681. &ok, NULL);
  2682. if (!ok)
  2683. goto err;
  2684. } else {
  2685. ns->consensus_method = 1;
  2686. }
  2687. }
  2688. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2689. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2690. goto err;
  2691. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2692. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2693. goto err;
  2694. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2695. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2696. goto err;
  2697. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2698. tor_assert(tok->n_args >= 2);
  2699. ns->vote_seconds =
  2700. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2701. if (!ok)
  2702. goto err;
  2703. ns->dist_seconds =
  2704. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2705. if (!ok)
  2706. goto err;
  2707. if (ns->valid_after +
  2708. (get_options()->TestingTorNetwork ?
  2709. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  2710. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2711. goto err;
  2712. }
  2713. if (ns->valid_after +
  2714. (get_options()->TestingTorNetwork ?
  2715. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  2716. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2717. goto err;
  2718. }
  2719. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2720. log_warn(LD_DIR, "Vote seconds is too short");
  2721. goto err;
  2722. }
  2723. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2724. log_warn(LD_DIR, "Dist seconds is too short");
  2725. goto err;
  2726. }
  2727. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2728. ns->client_versions = tor_strdup(tok->args[0]);
  2729. }
  2730. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2731. ns->server_versions = tor_strdup(tok->args[0]);
  2732. }
  2733. {
  2734. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  2735. ns->package_lines = smartlist_new();
  2736. if (package_lst) {
  2737. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  2738. smartlist_add(ns->package_lines, tor_strdup(t->args[0])));
  2739. }
  2740. smartlist_free(package_lst);
  2741. }
  2742. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2743. ns->known_flags = smartlist_new();
  2744. inorder = 1;
  2745. for (i = 0; i < tok->n_args; ++i) {
  2746. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2747. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2748. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2749. inorder = 0;
  2750. }
  2751. }
  2752. if (!inorder) {
  2753. log_warn(LD_DIR, "known-flags not in order");
  2754. goto err;
  2755. }
  2756. if (ns->type != NS_TYPE_CONSENSUS &&
  2757. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  2758. /* If we allowed more than 64 flags in votes, then parsing them would make
  2759. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  2760. * bit-shift. This is only for votes and opinions: consensus users don't
  2761. * care about flags they don't recognize, and so don't build a bitfield
  2762. * for them. */
  2763. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  2764. goto err;
  2765. }
  2766. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2767. if (tok) {
  2768. int any_dups = 0;
  2769. inorder = 1;
  2770. ns->net_params = smartlist_new();
  2771. for (i = 0; i < tok->n_args; ++i) {
  2772. int ok=0;
  2773. char *eq = strchr(tok->args[i], '=');
  2774. size_t eq_pos;
  2775. if (!eq) {
  2776. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2777. goto err;
  2778. }
  2779. eq_pos = eq-tok->args[i];
  2780. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2781. if (!ok) {
  2782. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2783. goto err;
  2784. }
  2785. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2786. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2787. inorder = 0;
  2788. }
  2789. if (last_kwd && eq_pos == strlen(last_kwd) &&
  2790. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  2791. log_warn(LD_DIR, "Duplicate value for %s parameter",
  2792. escaped(tok->args[i]));
  2793. any_dups = 1;
  2794. }
  2795. tor_free(last_kwd);
  2796. last_kwd = tor_strndup(tok->args[i], eq_pos);
  2797. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  2798. }
  2799. if (!inorder) {
  2800. log_warn(LD_DIR, "params not in order");
  2801. goto err;
  2802. }
  2803. if (any_dups) {
  2804. log_warn(LD_DIR, "Duplicate in parameters");
  2805. goto err;
  2806. }
  2807. }
  2808. ns->voters = smartlist_new();
  2809. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2810. tok = _tok;
  2811. if (tok->tp == K_DIR_SOURCE) {
  2812. tor_assert(tok->n_args >= 6);
  2813. if (voter)
  2814. smartlist_add(ns->voters, voter);
  2815. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2816. voter->sigs = smartlist_new();
  2817. if (ns->type != NS_TYPE_CONSENSUS)
  2818. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  2819. voter->nickname = tor_strdup(tok->args[0]);
  2820. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2821. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2822. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2823. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2824. "network-status document.", escaped(tok->args[1]));
  2825. goto err;
  2826. }
  2827. if (ns->type != NS_TYPE_CONSENSUS &&
  2828. tor_memneq(ns->cert->cache_info.identity_digest,
  2829. voter->identity_digest, DIGEST_LEN)) {
  2830. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2831. goto err;
  2832. }
  2833. if (ns->type != NS_TYPE_CONSENSUS) {
  2834. if (authority_cert_is_blacklisted(ns->cert)) {
  2835. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  2836. "signing key %s",
  2837. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  2838. goto err;
  2839. }
  2840. }
  2841. voter->address = tor_strdup(tok->args[2]);
  2842. if (!tor_inet_aton(tok->args[3], &in)) {
  2843. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2844. escaped(tok->args[3]));
  2845. goto err;
  2846. }
  2847. voter->addr = ntohl(in.s_addr);
  2848. voter->dir_port = (uint16_t)
  2849. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2850. if (!ok)
  2851. goto err;
  2852. voter->or_port = (uint16_t)
  2853. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2854. if (!ok)
  2855. goto err;
  2856. } else if (tok->tp == K_CONTACT) {
  2857. if (!voter || voter->contact) {
  2858. log_warn(LD_DIR, "contact element is out of place.");
  2859. goto err;
  2860. }
  2861. voter->contact = tor_strdup(tok->args[0]);
  2862. } else if (tok->tp == K_VOTE_DIGEST) {
  2863. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2864. tor_assert(tok->n_args >= 1);
  2865. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2866. log_warn(LD_DIR, "vote-digest element is out of place.");
  2867. goto err;
  2868. }
  2869. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2870. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2871. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2872. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2873. "network-status consensus.", escaped(tok->args[0]));
  2874. goto err;
  2875. }
  2876. }
  2877. } SMARTLIST_FOREACH_END(_tok);
  2878. if (voter) {
  2879. smartlist_add(ns->voters, voter);
  2880. voter = NULL;
  2881. }
  2882. if (smartlist_len(ns->voters) == 0) {
  2883. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  2884. goto err;
  2885. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2886. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2887. goto err;
  2888. }
  2889. if (ns->type != NS_TYPE_CONSENSUS &&
  2890. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2891. int bad = 1;
  2892. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2893. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2894. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2895. tok->args[0], HEX_DIGEST_LEN)<0)
  2896. bad = 1;
  2897. else
  2898. bad = 0;
  2899. }
  2900. if (bad) {
  2901. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2902. escaped(tok->args[0]));
  2903. }
  2904. }
  2905. /* Parse routerstatus lines. */
  2906. rs_tokens = smartlist_new();
  2907. rs_area = memarea_new();
  2908. s = end_of_header;
  2909. ns->routerstatus_list = smartlist_new();
  2910. while (!strcmpstart(s, "r ")) {
  2911. if (ns->type != NS_TYPE_CONSENSUS) {
  2912. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2913. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2914. rs, 0, 0))
  2915. smartlist_add(ns->routerstatus_list, rs);
  2916. else {
  2917. tor_free(rs->version);
  2918. tor_free(rs);
  2919. }
  2920. } else {
  2921. routerstatus_t *rs;
  2922. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2923. NULL, NULL,
  2924. ns->consensus_method,
  2925. flav)))
  2926. smartlist_add(ns->routerstatus_list, rs);
  2927. }
  2928. }
  2929. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2930. routerstatus_t *rs1, *rs2;
  2931. if (ns->type != NS_TYPE_CONSENSUS) {
  2932. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2933. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2934. rs1 = &a->status; rs2 = &b->status;
  2935. } else {
  2936. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2937. rs2 = smartlist_get(ns->routerstatus_list, i);
  2938. }
  2939. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2940. >= 0) {
  2941. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  2942. goto err;
  2943. }
  2944. }
  2945. if (ns_type != NS_TYPE_CONSENSUS) {
  2946. digest256map_t *ed_id_map = digest256map_new();
  2947. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  2948. vrs) {
  2949. if (! vrs->has_ed25519_listing ||
  2950. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  2951. continue;
  2952. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  2953. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  2954. "unique");
  2955. digest256map_free(ed_id_map, NULL);
  2956. goto err;
  2957. }
  2958. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  2959. } SMARTLIST_FOREACH_END(vrs);
  2960. digest256map_free(ed_id_map, NULL);
  2961. }
  2962. /* Parse footer; check signature. */
  2963. footer_tokens = smartlist_new();
  2964. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2965. ++end_of_footer;
  2966. else
  2967. end_of_footer = s + strlen(s);
  2968. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2969. networkstatus_vote_footer_token_table, 0)) {
  2970. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2971. goto err;
  2972. }
  2973. {
  2974. int found_sig = 0;
  2975. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2976. tok = _tok;
  2977. if (tok->tp == K_DIRECTORY_SIGNATURE)
  2978. found_sig = 1;
  2979. else if (found_sig) {
  2980. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  2981. goto err;
  2982. }
  2983. } SMARTLIST_FOREACH_END(_tok);
  2984. }
  2985. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  2986. if (tok != smartlist_get(footer_tokens, 0)) {
  2987. log_warn(LD_DIR, "Misplaced directory-footer token");
  2988. goto err;
  2989. }
  2990. }
  2991. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  2992. if (tok) {
  2993. ns->weight_params = smartlist_new();
  2994. for (i = 0; i < tok->n_args; ++i) {
  2995. int ok=0;
  2996. char *eq = strchr(tok->args[i], '=');
  2997. if (!eq) {
  2998. log_warn(LD_DIR, "Bad element '%s' in weight params",
  2999. escaped(tok->args[i]));
  3000. goto err;
  3001. }
  3002. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3003. if (!ok) {
  3004. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3005. goto err;
  3006. }
  3007. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  3008. }
  3009. }
  3010. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3011. char declared_identity[DIGEST_LEN];
  3012. networkstatus_voter_info_t *v;
  3013. document_signature_t *sig;
  3014. const char *id_hexdigest = NULL;
  3015. const char *sk_hexdigest = NULL;
  3016. digest_algorithm_t alg = DIGEST_SHA1;
  3017. tok = _tok;
  3018. if (tok->tp != K_DIRECTORY_SIGNATURE)
  3019. continue;
  3020. tor_assert(tok->n_args >= 2);
  3021. if (tok->n_args == 2) {
  3022. id_hexdigest = tok->args[0];
  3023. sk_hexdigest = tok->args[1];
  3024. } else {
  3025. const char *algname = tok->args[0];
  3026. int a;
  3027. id_hexdigest = tok->args[1];
  3028. sk_hexdigest = tok->args[2];
  3029. a = crypto_digest_algorithm_parse_name(algname);
  3030. if (a<0) {
  3031. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  3032. escaped(algname));
  3033. continue;
  3034. }
  3035. alg = a;
  3036. }
  3037. if (!tok->object_type ||
  3038. strcmp(tok->object_type, "SIGNATURE") ||
  3039. tok->object_size < 128 || tok->object_size > 512) {
  3040. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3041. goto err;
  3042. }
  3043. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3044. base16_decode(declared_identity, sizeof(declared_identity),
  3045. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  3046. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3047. "network-status document.", escaped(id_hexdigest));
  3048. goto err;
  3049. }
  3050. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3051. log_warn(LD_DIR, "ID on signature on network-status document does "
  3052. "not match any declared directory source.");
  3053. goto err;
  3054. }
  3055. sig = tor_malloc_zero(sizeof(document_signature_t));
  3056. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3057. sig->alg = alg;
  3058. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3059. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3060. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  3061. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3062. "network-status document.", escaped(sk_hexdigest));
  3063. tor_free(sig);
  3064. goto err;
  3065. }
  3066. if (ns->type != NS_TYPE_CONSENSUS) {
  3067. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3068. DIGEST_LEN)) {
  3069. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3070. "network-status vote.");
  3071. tor_free(sig);
  3072. goto err;
  3073. }
  3074. }
  3075. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3076. /* We already parsed a vote with this algorithm from this voter. Use the
  3077. first one. */
  3078. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3079. "that contains two signatures from the same voter with the same "
  3080. "algorithm. Ignoring the second signature.");
  3081. tor_free(sig);
  3082. continue;
  3083. }
  3084. if (ns->type != NS_TYPE_CONSENSUS) {
  3085. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3086. tok, ns->cert->signing_key, 0,
  3087. "network-status document")) {
  3088. tor_free(sig);
  3089. goto err;
  3090. }
  3091. sig->good_signature = 1;
  3092. } else {
  3093. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3094. tor_free(sig);
  3095. goto err;
  3096. }
  3097. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3098. sig->signature_len = (int) tok->object_size;
  3099. }
  3100. smartlist_add(v->sigs, sig);
  3101. ++n_signatures;
  3102. } SMARTLIST_FOREACH_END(_tok);
  3103. if (! n_signatures) {
  3104. log_warn(LD_DIR, "No signatures on networkstatus document.");
  3105. goto err;
  3106. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3107. log_warn(LD_DIR, "Received more than one signature on a "
  3108. "network-status vote.");
  3109. goto err;
  3110. }
  3111. if (eos_out)
  3112. *eos_out = end_of_footer;
  3113. goto done;
  3114. err:
  3115. dump_desc(s_dup, "v3 networkstatus");
  3116. networkstatus_vote_free(ns);
  3117. ns = NULL;
  3118. done:
  3119. if (tokens) {
  3120. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3121. smartlist_free(tokens);
  3122. }
  3123. if (voter) {
  3124. if (voter->sigs) {
  3125. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3126. document_signature_free(sig));
  3127. smartlist_free(voter->sigs);
  3128. }
  3129. tor_free(voter->nickname);
  3130. tor_free(voter->address);
  3131. tor_free(voter->contact);
  3132. tor_free(voter);
  3133. }
  3134. if (rs_tokens) {
  3135. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3136. smartlist_free(rs_tokens);
  3137. }
  3138. if (footer_tokens) {
  3139. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3140. smartlist_free(footer_tokens);
  3141. }
  3142. if (area) {
  3143. DUMP_AREA(area, "v3 networkstatus");
  3144. memarea_drop_all(area);
  3145. }
  3146. if (rs_area)
  3147. memarea_drop_all(rs_area);
  3148. tor_free(last_kwd);
  3149. return ns;
  3150. }
  3151. /** Return the common_digests_t that holds the digests of the
  3152. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3153. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  3154. * neeeded. */
  3155. static common_digests_t *
  3156. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3157. {
  3158. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  3159. if (!d) {
  3160. d = tor_malloc_zero(sizeof(common_digests_t));
  3161. strmap_set(sigs->digests, flavor_name, d);
  3162. }
  3163. return d;
  3164. }
  3165. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3166. * networkstatus according to the detached signatures document <b>sigs</b>,
  3167. * allocating a new common_digests_t as neeeded. */
  3168. static smartlist_t *
  3169. detached_get_signatures(ns_detached_signatures_t *sigs,
  3170. const char *flavor_name)
  3171. {
  3172. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3173. if (!sl) {
  3174. sl = smartlist_new();
  3175. strmap_set(sigs->signatures, flavor_name, sl);
  3176. }
  3177. return sl;
  3178. }
  3179. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3180. * <b>eos</b> and return the result. Return -1 on failure. */
  3181. ns_detached_signatures_t *
  3182. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3183. {
  3184. /* XXXX there is too much duplicate shared between this function and
  3185. * networkstatus_parse_vote_from_string(). */
  3186. directory_token_t *tok;
  3187. memarea_t *area = NULL;
  3188. common_digests_t *digests;
  3189. smartlist_t *tokens = smartlist_new();
  3190. ns_detached_signatures_t *sigs =
  3191. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3192. sigs->digests = strmap_new();
  3193. sigs->signatures = strmap_new();
  3194. if (!eos)
  3195. eos = s + strlen(s);
  3196. area = memarea_new();
  3197. if (tokenize_string(area,s, eos, tokens,
  3198. networkstatus_detached_signature_token_table, 0)) {
  3199. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3200. goto err;
  3201. }
  3202. /* Grab all the digest-like tokens. */
  3203. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3204. const char *algname;
  3205. digest_algorithm_t alg;
  3206. const char *flavor;
  3207. const char *hexdigest;
  3208. size_t expected_length;
  3209. tok = _tok;
  3210. if (tok->tp == K_CONSENSUS_DIGEST) {
  3211. algname = "sha1";
  3212. alg = DIGEST_SHA1;
  3213. flavor = "ns";
  3214. hexdigest = tok->args[0];
  3215. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3216. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3217. if (a<0) {
  3218. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3219. continue;
  3220. }
  3221. alg = (digest_algorithm_t) a;
  3222. flavor = tok->args[0];
  3223. algname = tok->args[1];
  3224. hexdigest = tok->args[2];
  3225. } else {
  3226. continue;
  3227. }
  3228. expected_length =
  3229. (alg == DIGEST_SHA1) ? HEX_DIGEST_LEN : HEX_DIGEST256_LEN;
  3230. if (strlen(hexdigest) != expected_length) {
  3231. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3232. "networkstatus signatures");
  3233. goto err;
  3234. }
  3235. digests = detached_get_digests(sigs, flavor);
  3236. tor_assert(digests);
  3237. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  3238. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3239. "signatures document", flavor, algname);
  3240. continue;
  3241. }
  3242. if (base16_decode(digests->d[alg], DIGEST256_LEN,
  3243. hexdigest, strlen(hexdigest)) < 0) {
  3244. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3245. "networkstatus signatures");
  3246. goto err;
  3247. }
  3248. } SMARTLIST_FOREACH_END(_tok);
  3249. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3250. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3251. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3252. goto err;
  3253. }
  3254. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3255. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3256. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3257. goto err;
  3258. }
  3259. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3260. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3261. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3262. goto err;
  3263. }
  3264. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3265. const char *id_hexdigest;
  3266. const char *sk_hexdigest;
  3267. const char *algname;
  3268. const char *flavor;
  3269. digest_algorithm_t alg;
  3270. char id_digest[DIGEST_LEN];
  3271. char sk_digest[DIGEST_LEN];
  3272. smartlist_t *siglist;
  3273. document_signature_t *sig;
  3274. int is_duplicate;
  3275. tok = _tok;
  3276. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3277. tor_assert(tok->n_args >= 2);
  3278. flavor = "ns";
  3279. algname = "sha1";
  3280. id_hexdigest = tok->args[0];
  3281. sk_hexdigest = tok->args[1];
  3282. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3283. tor_assert(tok->n_args >= 4);
  3284. flavor = tok->args[0];
  3285. algname = tok->args[1];
  3286. id_hexdigest = tok->args[2];
  3287. sk_hexdigest = tok->args[3];
  3288. } else {
  3289. continue;
  3290. }
  3291. {
  3292. int a = crypto_digest_algorithm_parse_name(algname);
  3293. if (a<0) {
  3294. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3295. continue;
  3296. }
  3297. alg = (digest_algorithm_t) a;
  3298. }
  3299. if (!tok->object_type ||
  3300. strcmp(tok->object_type, "SIGNATURE") ||
  3301. tok->object_size < 128 || tok->object_size > 512) {
  3302. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3303. goto err;
  3304. }
  3305. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3306. base16_decode(id_digest, sizeof(id_digest),
  3307. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  3308. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3309. "network-status vote.", escaped(id_hexdigest));
  3310. goto err;
  3311. }
  3312. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3313. base16_decode(sk_digest, sizeof(sk_digest),
  3314. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  3315. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3316. "network-status vote.", escaped(sk_hexdigest));
  3317. goto err;
  3318. }
  3319. siglist = detached_get_signatures(sigs, flavor);
  3320. is_duplicate = 0;
  3321. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3322. if (dsig->alg == alg &&
  3323. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3324. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3325. is_duplicate = 1;
  3326. }
  3327. });
  3328. if (is_duplicate) {
  3329. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3330. "found.");
  3331. continue;
  3332. }
  3333. sig = tor_malloc_zero(sizeof(document_signature_t));
  3334. sig->alg = alg;
  3335. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3336. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3337. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3338. tor_free(sig);
  3339. goto err;
  3340. }
  3341. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3342. sig->signature_len = (int) tok->object_size;
  3343. smartlist_add(siglist, sig);
  3344. } SMARTLIST_FOREACH_END(_tok);
  3345. goto done;
  3346. err:
  3347. ns_detached_signatures_free(sigs);
  3348. sigs = NULL;
  3349. done:
  3350. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3351. smartlist_free(tokens);
  3352. if (area) {
  3353. DUMP_AREA(area, "detached signatures");
  3354. memarea_drop_all(area);
  3355. }
  3356. return sigs;
  3357. }
  3358. /** Parse the addr policy in the string <b>s</b> and return it. If
  3359. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  3360. * ADDR_POLICY_REJECT) for items that specify no action.
  3361. *
  3362. * Returns NULL on policy errors.
  3363. *
  3364. * Set *<b>malformed_list</b> to true if the entire policy list should be
  3365. * discarded. Otherwise, set it to false, and only this item should be ignored
  3366. * on error - the rest of the policy list can continue to be processed and
  3367. * used.
  3368. *
  3369. * The addr_policy_t returned by this function can have its address set to
  3370. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  3371. * of AF_INET and AF_INET6 items.
  3372. */
  3373. MOCK_IMPL(addr_policy_t *,
  3374. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  3375. int *malformed_list))
  3376. {
  3377. directory_token_t *tok = NULL;
  3378. const char *cp, *eos;
  3379. /* Longest possible policy is
  3380. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  3381. * which contains a max-length IPv6 address, plus 26 characters.
  3382. * But note that there can be an arbitrary amount of space between the
  3383. * accept and the address:mask/port element.
  3384. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  3385. * IPv6 address. But making the buffer shorter might cause valid long lines,
  3386. * which parsed in previous versions, to fail to parse in new versions.
  3387. * (These lines would have to have excessive amounts of whitespace.) */
  3388. char line[TOR_ADDR_BUF_LEN*2 + 32];
  3389. addr_policy_t *r;
  3390. memarea_t *area = NULL;
  3391. tor_assert(malformed_list);
  3392. *malformed_list = 0;
  3393. s = eat_whitespace(s);
  3394. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  3395. * and ":" (port separator) are ambiguous */
  3396. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  3397. if (tor_snprintf(line, sizeof(line), "%s %s",
  3398. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  3399. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  3400. return NULL;
  3401. }
  3402. cp = line;
  3403. tor_strlower(line);
  3404. } else { /* assume an already well-formed address policy line */
  3405. cp = s;
  3406. }
  3407. eos = cp + strlen(cp);
  3408. area = memarea_new();
  3409. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  3410. if (tok->tp == ERR_) {
  3411. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  3412. goto err;
  3413. }
  3414. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  3415. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  3416. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  3417. goto err;
  3418. }
  3419. /* Use the extended interpretation of accept/reject *,
  3420. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  3421. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  3422. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  3423. if (!r) {
  3424. goto err;
  3425. }
  3426. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  3427. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  3428. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  3429. * either an IPv4 or IPv6 address. */
  3430. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3431. tor_addr_family(&r->addr) != AF_INET6) {
  3432. /* This is a non-fatal error, just ignore this one entry. */
  3433. *malformed_list = 0;
  3434. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  3435. "exit policy. Ignoring, but continuing to parse rules. (Use "
  3436. "accept/reject with IPv4 addresses.)",
  3437. tok->n_args == 1 ? tok->args[0] : "");
  3438. addr_policy_free(r);
  3439. r = NULL;
  3440. goto done;
  3441. }
  3442. goto done;
  3443. err:
  3444. *malformed_list = 1;
  3445. r = NULL;
  3446. done:
  3447. token_clear(tok);
  3448. if (area) {
  3449. DUMP_AREA(area, "policy item");
  3450. memarea_drop_all(area);
  3451. }
  3452. return r;
  3453. }
  3454. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  3455. * <b>router</b>. Return 0 on success, -1 on failure. */
  3456. static int
  3457. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  3458. {
  3459. addr_policy_t *newe;
  3460. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  3461. newe = router_parse_addr_policy(tok, 0);
  3462. if (!newe)
  3463. return -1;
  3464. if (! router->exit_policy)
  3465. router->exit_policy = smartlist_new();
  3466. /* Ensure that in descriptors, accept/reject fields are followed by
  3467. * IPv4 addresses, and accept6/reject6 fields are followed by
  3468. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  3469. * accept/reject followed by IPv6. */
  3470. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3471. tor_addr_family(&newe->addr) == AF_INET)
  3472. ||
  3473. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3474. tor_addr_family(&newe->addr) == AF_INET6)) {
  3475. /* There's nothing the user can do about other relays' descriptors,
  3476. * so we don't provide usage advice here. */
  3477. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3478. "policy '%s'. Discarding entire router descriptor.",
  3479. tok->n_args == 1 ? tok->args[0] : "");
  3480. addr_policy_free(newe);
  3481. return -1;
  3482. }
  3483. smartlist_add(router->exit_policy, newe);
  3484. return 0;
  3485. }
  3486. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  3487. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  3488. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  3489. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  3490. * policies */
  3491. static addr_policy_t *
  3492. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3493. {
  3494. addr_policy_t newe;
  3495. char *arg;
  3496. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3497. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3498. if (tok->n_args != 1)
  3499. return NULL;
  3500. arg = tok->args[0];
  3501. if (!strcmpstart(arg,"private"))
  3502. return router_parse_addr_policy_private(tok);
  3503. memset(&newe, 0, sizeof(newe));
  3504. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3505. newe.policy_type = ADDR_POLICY_REJECT;
  3506. else
  3507. newe.policy_type = ADDR_POLICY_ACCEPT;
  3508. /* accept6/reject6 * produces an IPv6 wildcard address only.
  3509. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  3510. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  3511. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  3512. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  3513. }
  3514. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3515. &newe.prt_min, &newe.prt_max) < 0) {
  3516. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3517. return NULL;
  3518. }
  3519. return addr_policy_get_canonical_entry(&newe);
  3520. }
  3521. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  3522. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3523. * router descriptors until earlier versions are obsolete.
  3524. *
  3525. * accept/reject and accept6/reject6 private all produce rules for both
  3526. * IPv4 and IPv6 addresses.
  3527. */
  3528. static addr_policy_t *
  3529. router_parse_addr_policy_private(directory_token_t *tok)
  3530. {
  3531. const char *arg;
  3532. uint16_t port_min, port_max;
  3533. addr_policy_t result;
  3534. arg = tok->args[0];
  3535. if (strcmpstart(arg, "private"))
  3536. return NULL;
  3537. arg += strlen("private");
  3538. arg = (char*) eat_whitespace(arg);
  3539. if (!arg || *arg != ':')
  3540. return NULL;
  3541. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  3542. return NULL;
  3543. memset(&result, 0, sizeof(result));
  3544. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3545. result.policy_type = ADDR_POLICY_REJECT;
  3546. else
  3547. result.policy_type = ADDR_POLICY_ACCEPT;
  3548. result.is_private = 1;
  3549. result.prt_min = port_min;
  3550. result.prt_max = port_max;
  3551. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  3552. log_warn(LD_GENERAL,
  3553. "'%s' expands into rules which apply to all private IPv4 and "
  3554. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  3555. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  3556. }
  3557. return addr_policy_get_canonical_entry(&result);
  3558. }
  3559. /** Log and exit if <b>t</b> is malformed */
  3560. void
  3561. assert_addr_policy_ok(smartlist_t *lst)
  3562. {
  3563. if (!lst) return;
  3564. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  3565. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  3566. t->policy_type == ADDR_POLICY_ACCEPT);
  3567. tor_assert(t->prt_min <= t->prt_max);
  3568. });
  3569. }
  3570. /*
  3571. * Low-level tokenizer for router descriptors and directories.
  3572. */
  3573. /** Free all resources allocated for <b>tok</b> */
  3574. static void
  3575. token_clear(directory_token_t *tok)
  3576. {
  3577. if (tok->key)
  3578. crypto_pk_free(tok->key);
  3579. }
  3580. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  3581. #define ALLOC(sz) memarea_alloc(area,sz)
  3582. #define STRDUP(str) memarea_strdup(area,str)
  3583. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  3584. #define RET_ERR(msg) \
  3585. STMT_BEGIN \
  3586. if (tok) token_clear(tok); \
  3587. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  3588. tok->tp = ERR_; \
  3589. tok->error = STRDUP(msg); \
  3590. goto done_tokenizing; \
  3591. STMT_END
  3592. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  3593. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  3594. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  3595. * conform to the syntax we wanted.
  3596. **/
  3597. static inline directory_token_t *
  3598. token_check_object(memarea_t *area, const char *kwd,
  3599. directory_token_t *tok, obj_syntax o_syn)
  3600. {
  3601. char ebuf[128];
  3602. switch (o_syn) {
  3603. case NO_OBJ:
  3604. /* No object is allowed for this token. */
  3605. if (tok->object_body) {
  3606. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  3607. RET_ERR(ebuf);
  3608. }
  3609. if (tok->key) {
  3610. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  3611. RET_ERR(ebuf);
  3612. }
  3613. break;
  3614. case NEED_OBJ:
  3615. /* There must be a (non-key) object. */
  3616. if (!tok->object_body) {
  3617. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  3618. RET_ERR(ebuf);
  3619. }
  3620. break;
  3621. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  3622. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  3623. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  3624. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  3625. kwd, crypto_pk_num_bits(tok->key));
  3626. RET_ERR(ebuf);
  3627. }
  3628. /* fall through */
  3629. case NEED_KEY: /* There must be some kind of key. */
  3630. if (!tok->key) {
  3631. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  3632. RET_ERR(ebuf);
  3633. }
  3634. if (o_syn != NEED_SKEY_1024) {
  3635. if (crypto_pk_key_is_private(tok->key)) {
  3636. tor_snprintf(ebuf, sizeof(ebuf),
  3637. "Private key given for %s, which wants a public key", kwd);
  3638. RET_ERR(ebuf);
  3639. }
  3640. } else { /* o_syn == NEED_SKEY_1024 */
  3641. if (!crypto_pk_key_is_private(tok->key)) {
  3642. tor_snprintf(ebuf, sizeof(ebuf),
  3643. "Public key given for %s, which wants a private key", kwd);
  3644. RET_ERR(ebuf);
  3645. }
  3646. }
  3647. break;
  3648. case OBJ_OK:
  3649. /* Anything goes with this token. */
  3650. break;
  3651. }
  3652. done_tokenizing:
  3653. return tok;
  3654. }
  3655. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  3656. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  3657. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  3658. * all storage in <b>area</b>. Return the number of arguments parsed, or
  3659. * return -1 if there was an insanely high number of arguments. */
  3660. static inline int
  3661. get_token_arguments(memarea_t *area, directory_token_t *tok,
  3662. const char *s, const char *eol)
  3663. {
  3664. /** Largest number of arguments we'll accept to any token, ever. */
  3665. #define MAX_ARGS 512
  3666. char *mem = memarea_strndup(area, s, eol-s);
  3667. char *cp = mem;
  3668. int j = 0;
  3669. char *args[MAX_ARGS];
  3670. while (*cp) {
  3671. if (j == MAX_ARGS)
  3672. return -1;
  3673. args[j++] = cp;
  3674. cp = (char*)find_whitespace(cp);
  3675. if (!cp || !*cp)
  3676. break; /* End of the line. */
  3677. *cp++ = '\0';
  3678. cp = (char*)eat_whitespace(cp);
  3679. }
  3680. tok->n_args = j;
  3681. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  3682. return j;
  3683. #undef MAX_ARGS
  3684. }
  3685. /** Helper function: read the next token from *s, advance *s to the end of the
  3686. * token, and return the parsed token. Parse *<b>s</b> according to the list
  3687. * of tokens in <b>table</b>.
  3688. */
  3689. static directory_token_t *
  3690. get_next_token(memarea_t *area,
  3691. const char **s, const char *eos, token_rule_t *table)
  3692. {
  3693. /** Reject any object at least this big; it is probably an overflow, an
  3694. * attack, a bug, or some other nonsense. */
  3695. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  3696. /** Reject any line at least this big; it is probably an overflow, an
  3697. * attack, a bug, or some other nonsense. */
  3698. #define MAX_LINE_LENGTH (128*1024)
  3699. const char *next, *eol, *obstart;
  3700. size_t obname_len;
  3701. int i;
  3702. directory_token_t *tok;
  3703. obj_syntax o_syn = NO_OBJ;
  3704. char ebuf[128];
  3705. const char *kwd = "";
  3706. tor_assert(area);
  3707. tok = ALLOC_ZERO(sizeof(directory_token_t));
  3708. tok->tp = ERR_;
  3709. /* Set *s to first token, eol to end-of-line, next to after first token */
  3710. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  3711. tor_assert(eos >= *s);
  3712. eol = memchr(*s, '\n', eos-*s);
  3713. if (!eol)
  3714. eol = eos;
  3715. if (eol - *s > MAX_LINE_LENGTH) {
  3716. RET_ERR("Line far too long");
  3717. }
  3718. next = find_whitespace_eos(*s, eol);
  3719. if (!strcmp_len(*s, "opt", next-*s)) {
  3720. /* Skip past an "opt" at the start of the line. */
  3721. *s = eat_whitespace_eos_no_nl(next, eol);
  3722. next = find_whitespace_eos(*s, eol);
  3723. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  3724. RET_ERR("Unexpected EOF");
  3725. }
  3726. /* Search the table for the appropriate entry. (I tried a binary search
  3727. * instead, but it wasn't any faster.) */
  3728. for (i = 0; table[i].t ; ++i) {
  3729. if (!strcmp_len(*s, table[i].t, next-*s)) {
  3730. /* We've found the keyword. */
  3731. kwd = table[i].t;
  3732. tok->tp = table[i].v;
  3733. o_syn = table[i].os;
  3734. *s = eat_whitespace_eos_no_nl(next, eol);
  3735. /* We go ahead whether there are arguments or not, so that tok->args is
  3736. * always set if we want arguments. */
  3737. if (table[i].concat_args) {
  3738. /* The keyword takes the line as a single argument */
  3739. tok->args = ALLOC(sizeof(char*));
  3740. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  3741. tok->n_args = 1;
  3742. } else {
  3743. /* This keyword takes multiple arguments. */
  3744. if (get_token_arguments(area, tok, *s, eol)<0) {
  3745. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  3746. RET_ERR(ebuf);
  3747. }
  3748. *s = eol;
  3749. }
  3750. if (tok->n_args < table[i].min_args) {
  3751. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  3752. RET_ERR(ebuf);
  3753. } else if (tok->n_args > table[i].max_args) {
  3754. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  3755. RET_ERR(ebuf);
  3756. }
  3757. break;
  3758. }
  3759. }
  3760. if (tok->tp == ERR_) {
  3761. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  3762. if (**s == '@')
  3763. tok->tp = A_UNKNOWN_;
  3764. else
  3765. tok->tp = K_OPT;
  3766. tok->args = ALLOC(sizeof(char*));
  3767. tok->args[0] = STRNDUP(*s, eol-*s);
  3768. tok->n_args = 1;
  3769. o_syn = OBJ_OK;
  3770. }
  3771. /* Check whether there's an object present */
  3772. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  3773. tor_assert(eos >= *s);
  3774. eol = memchr(*s, '\n', eos-*s);
  3775. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  3776. goto check_object;
  3777. obstart = *s; /* Set obstart to start of object spec */
  3778. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  3779. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  3780. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  3781. RET_ERR("Malformed object: bad begin line");
  3782. }
  3783. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  3784. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  3785. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  3786. /* Go to the end of the object */
  3787. next = tor_memstr(*s, eos-*s, "-----END ");
  3788. if (!next) {
  3789. RET_ERR("Malformed object: missing object end line");
  3790. }
  3791. tor_assert(eos >= next);
  3792. eol = memchr(next, '\n', eos-next);
  3793. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  3794. eol = eos;
  3795. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  3796. if ((size_t)(eol-next) != 9+obname_len+5 ||
  3797. strcmp_len(next+9, tok->object_type, obname_len) ||
  3798. strcmp_len(eol-5, "-----", 5)) {
  3799. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  3800. tok->object_type);
  3801. ebuf[sizeof(ebuf)-1] = '\0';
  3802. RET_ERR(ebuf);
  3803. }
  3804. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  3805. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  3806. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  3807. tok->key = crypto_pk_new();
  3808. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  3809. RET_ERR("Couldn't parse public key.");
  3810. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  3811. tok->key = crypto_pk_new();
  3812. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  3813. RET_ERR("Couldn't parse private key.");
  3814. } else { /* If it's something else, try to base64-decode it */
  3815. int r;
  3816. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  3817. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  3818. if (r<0)
  3819. RET_ERR("Malformed object: bad base64-encoded data");
  3820. tok->object_size = r;
  3821. }
  3822. *s = eol;
  3823. check_object:
  3824. tok = token_check_object(area, kwd, tok, o_syn);
  3825. done_tokenizing:
  3826. return tok;
  3827. #undef RET_ERR
  3828. #undef ALLOC
  3829. #undef ALLOC_ZERO
  3830. #undef STRDUP
  3831. #undef STRNDUP
  3832. }
  3833. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  3834. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  3835. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  3836. * entire string.
  3837. */
  3838. static int
  3839. tokenize_string(memarea_t *area,
  3840. const char *start, const char *end, smartlist_t *out,
  3841. token_rule_t *table, int flags)
  3842. {
  3843. const char **s;
  3844. directory_token_t *tok = NULL;
  3845. int counts[NIL_];
  3846. int i;
  3847. int first_nonannotation;
  3848. int prev_len = smartlist_len(out);
  3849. tor_assert(area);
  3850. s = &start;
  3851. if (!end) {
  3852. end = start+strlen(start);
  3853. } else {
  3854. /* it's only meaningful to check for nuls if we got an end-of-string ptr */
  3855. if (memchr(start, '\0', end-start)) {
  3856. log_warn(LD_DIR, "parse error: internal NUL character.");
  3857. return -1;
  3858. }
  3859. }
  3860. for (i = 0; i < NIL_; ++i)
  3861. counts[i] = 0;
  3862. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  3863. while (*s < end && (!tok || tok->tp != EOF_)) {
  3864. tok = get_next_token(area, s, end, table);
  3865. if (tok->tp == ERR_) {
  3866. log_warn(LD_DIR, "parse error: %s", tok->error);
  3867. token_clear(tok);
  3868. return -1;
  3869. }
  3870. ++counts[tok->tp];
  3871. smartlist_add(out, tok);
  3872. *s = eat_whitespace_eos(*s, end);
  3873. }
  3874. if (flags & TS_NOCHECK)
  3875. return 0;
  3876. if ((flags & TS_ANNOTATIONS_OK)) {
  3877. first_nonannotation = -1;
  3878. for (i = 0; i < smartlist_len(out); ++i) {
  3879. tok = smartlist_get(out, i);
  3880. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  3881. first_nonannotation = i;
  3882. break;
  3883. }
  3884. }
  3885. if (first_nonannotation < 0) {
  3886. log_warn(LD_DIR, "parse error: item contains only annotations");
  3887. return -1;
  3888. }
  3889. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  3890. tok = smartlist_get(out, i);
  3891. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3892. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  3893. return -1;
  3894. }
  3895. }
  3896. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  3897. if (first_nonannotation != prev_len) {
  3898. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  3899. return -1;
  3900. }
  3901. }
  3902. } else {
  3903. for (i=0; i < smartlist_len(out); ++i) {
  3904. tok = smartlist_get(out, i);
  3905. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3906. log_warn(LD_DIR, "parse error: no annotations allowed.");
  3907. return -1;
  3908. }
  3909. }
  3910. first_nonannotation = 0;
  3911. }
  3912. for (i = 0; table[i].t; ++i) {
  3913. if (counts[table[i].v] < table[i].min_cnt) {
  3914. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  3915. return -1;
  3916. }
  3917. if (counts[table[i].v] > table[i].max_cnt) {
  3918. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  3919. return -1;
  3920. }
  3921. if (table[i].pos & AT_START) {
  3922. if (smartlist_len(out) < 1 ||
  3923. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  3924. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  3925. return -1;
  3926. }
  3927. }
  3928. if (table[i].pos & AT_END) {
  3929. if (smartlist_len(out) < 1 ||
  3930. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  3931. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  3932. return -1;
  3933. }
  3934. }
  3935. }
  3936. return 0;
  3937. }
  3938. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  3939. * NULL if no such keyword is found.
  3940. */
  3941. static directory_token_t *
  3942. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  3943. {
  3944. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  3945. return NULL;
  3946. }
  3947. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  3948. * with an assert if no such keyword is found.
  3949. */
  3950. static directory_token_t *
  3951. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  3952. const char *keyword_as_string)
  3953. {
  3954. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  3955. if (PREDICT_UNLIKELY(!tok)) {
  3956. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  3957. "been validated. Internal error.", keyword_as_string, (int)keyword);
  3958. tor_assert(tok);
  3959. }
  3960. return tok;
  3961. }
  3962. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  3963. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  3964. * in the same order in which they occur in <b>s</b>. Otherwise return
  3965. * NULL. */
  3966. static smartlist_t *
  3967. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  3968. {
  3969. smartlist_t *out = NULL;
  3970. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3971. if (t->tp == k) {
  3972. if (!out)
  3973. out = smartlist_new();
  3974. smartlist_add(out, t);
  3975. });
  3976. return out;
  3977. }
  3978. /** Return a newly allocated smartlist of all accept or reject tokens in
  3979. * <b>s</b>.
  3980. */
  3981. static smartlist_t *
  3982. find_all_exitpolicy(smartlist_t *s)
  3983. {
  3984. smartlist_t *out = smartlist_new();
  3985. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3986. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  3987. t->tp == K_REJECT || t->tp == K_REJECT6)
  3988. smartlist_add(out,t));
  3989. return out;
  3990. }
  3991. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  3992. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  3993. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  3994. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  3995. *
  3996. * Return 0 on success and -1 on failure.
  3997. */
  3998. static int
  3999. router_get_hash_impl_helper(const char *s, size_t s_len,
  4000. const char *start_str,
  4001. const char *end_str, char end_c,
  4002. const char **start_out, const char **end_out)
  4003. {
  4004. const char *start, *end;
  4005. start = tor_memstr(s, s_len, start_str);
  4006. if (!start) {
  4007. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  4008. return -1;
  4009. }
  4010. if (start != s && *(start-1) != '\n') {
  4011. log_warn(LD_DIR,
  4012. "first occurrence of \"%s\" is not at the start of a line",
  4013. start_str);
  4014. return -1;
  4015. }
  4016. end = tor_memstr(start+strlen(start_str),
  4017. s_len - (start-s) - strlen(start_str), end_str);
  4018. if (!end) {
  4019. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  4020. return -1;
  4021. }
  4022. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  4023. if (!end) {
  4024. log_warn(LD_DIR,"couldn't find EOL");
  4025. return -1;
  4026. }
  4027. ++end;
  4028. *start_out = start;
  4029. *end_out = end;
  4030. return 0;
  4031. }
  4032. /** Compute the digest of the substring of <b>s</b> taken from the first
  4033. * occurrence of <b>start_str</b> through the first instance of c after the
  4034. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  4035. * result in <b>digest</b>; return 0 on success.
  4036. *
  4037. * If no such substring exists, return -1.
  4038. */
  4039. static int
  4040. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  4041. const char *start_str,
  4042. const char *end_str, char end_c,
  4043. digest_algorithm_t alg)
  4044. {
  4045. const char *start=NULL, *end=NULL;
  4046. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4047. &start,&end)<0)
  4048. return -1;
  4049. if (alg == DIGEST_SHA1) {
  4050. if (crypto_digest(digest, start, end-start)) {
  4051. log_warn(LD_BUG,"couldn't compute digest");
  4052. return -1;
  4053. }
  4054. } else {
  4055. if (crypto_digest256(digest, start, end-start, alg)) {
  4056. log_warn(LD_BUG,"couldn't compute digest");
  4057. return -1;
  4058. }
  4059. }
  4060. return 0;
  4061. }
  4062. /** As router_get_hash_impl, but compute all hashes. */
  4063. static int
  4064. router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
  4065. const char *start_str,
  4066. const char *end_str, char end_c)
  4067. {
  4068. const char *start=NULL, *end=NULL;
  4069. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4070. &start,&end)<0)
  4071. return -1;
  4072. if (crypto_common_digests(digests, start, end-start)) {
  4073. log_warn(LD_BUG,"couldn't compute digests");
  4074. return -1;
  4075. }
  4076. return 0;
  4077. }
  4078. /** Assuming that s starts with a microdesc, return the start of the
  4079. * *NEXT* one. Return NULL on "not found." */
  4080. static const char *
  4081. find_start_of_next_microdesc(const char *s, const char *eos)
  4082. {
  4083. int started_with_annotations;
  4084. s = eat_whitespace_eos(s, eos);
  4085. if (!s)
  4086. return NULL;
  4087. #define CHECK_LENGTH() STMT_BEGIN \
  4088. if (s+32 > eos) \
  4089. return NULL; \
  4090. STMT_END
  4091. #define NEXT_LINE() STMT_BEGIN \
  4092. s = memchr(s, '\n', eos-s); \
  4093. if (!s || s+1 >= eos) \
  4094. return NULL; \
  4095. s++; \
  4096. STMT_END
  4097. CHECK_LENGTH();
  4098. started_with_annotations = (*s == '@');
  4099. if (started_with_annotations) {
  4100. /* Start by advancing to the first non-annotation line. */
  4101. while (*s == '@')
  4102. NEXT_LINE();
  4103. }
  4104. CHECK_LENGTH();
  4105. /* Now we should be pointed at an onion-key line. If we are, then skip
  4106. * it. */
  4107. if (!strcmpstart(s, "onion-key"))
  4108. NEXT_LINE();
  4109. /* Okay, now we're pointed at the first line of the microdescriptor which is
  4110. not an annotation or onion-key. The next line that _is_ an annotation or
  4111. onion-key is the start of the next microdescriptor. */
  4112. while (s+32 < eos) {
  4113. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4114. return s;
  4115. NEXT_LINE();
  4116. }
  4117. return NULL;
  4118. #undef CHECK_LENGTH
  4119. #undef NEXT_LINE
  4120. }
  4121. /** Parse as many microdescriptors as are found from the string starting at
  4122. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4123. * annotations we recognize and ignore ones we don't.
  4124. *
  4125. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  4126. * descriptor in the body field of each microdesc_t.
  4127. *
  4128. * Return all newly parsed microdescriptors in a newly allocated
  4129. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  4130. * microdesc digest to it for every microdesc that we found to be badly
  4131. * formed. (This may cause duplicates) */
  4132. smartlist_t *
  4133. microdescs_parse_from_string(const char *s, const char *eos,
  4134. int allow_annotations,
  4135. saved_location_t where,
  4136. smartlist_t *invalid_digests_out)
  4137. {
  4138. smartlist_t *tokens;
  4139. smartlist_t *result;
  4140. microdesc_t *md = NULL;
  4141. memarea_t *area;
  4142. const char *start = s;
  4143. const char *start_of_next_microdesc;
  4144. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4145. const int copy_body = (where != SAVED_IN_CACHE);
  4146. directory_token_t *tok;
  4147. if (!eos)
  4148. eos = s + strlen(s);
  4149. s = eat_whitespace_eos(s, eos);
  4150. area = memarea_new();
  4151. result = smartlist_new();
  4152. tokens = smartlist_new();
  4153. while (s < eos) {
  4154. int okay = 0;
  4155. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4156. if (!start_of_next_microdesc)
  4157. start_of_next_microdesc = eos;
  4158. md = tor_malloc_zero(sizeof(microdesc_t));
  4159. {
  4160. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4161. "onion-key");
  4162. const int no_onion_key = (cp == NULL);
  4163. if (no_onion_key) {
  4164. cp = s; /* So that we have *some* junk to put in the body */
  4165. }
  4166. md->bodylen = start_of_next_microdesc - cp;
  4167. md->saved_location = where;
  4168. if (copy_body)
  4169. md->body = tor_memdup_nulterm(cp, md->bodylen);
  4170. else
  4171. md->body = (char*)cp;
  4172. md->off = cp - start;
  4173. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4174. if (no_onion_key) {
  4175. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  4176. goto next;
  4177. }
  4178. }
  4179. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4180. microdesc_token_table, flags)) {
  4181. log_warn(LD_DIR, "Unparseable microdescriptor");
  4182. goto next;
  4183. }
  4184. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4185. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4186. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4187. goto next;
  4188. }
  4189. }
  4190. tok = find_by_keyword(tokens, K_ONION_KEY);
  4191. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4192. log_warn(LD_DIR,
  4193. "Relay's onion key had invalid exponent.");
  4194. goto next;
  4195. }
  4196. md->onion_pkey = tok->key;
  4197. tok->key = NULL;
  4198. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  4199. curve25519_public_key_t k;
  4200. tor_assert(tok->n_args >= 1);
  4201. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  4202. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  4203. goto next;
  4204. }
  4205. md->onion_curve25519_pkey =
  4206. tor_memdup(&k, sizeof(curve25519_public_key_t));
  4207. }
  4208. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  4209. if (id_lines) {
  4210. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  4211. tor_assert(t->n_args >= 2);
  4212. if (!strcmp(t->args[0], "ed25519")) {
  4213. if (md->ed25519_identity_pkey) {
  4214. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  4215. goto next;
  4216. }
  4217. ed25519_public_key_t k;
  4218. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  4219. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  4220. goto next;
  4221. }
  4222. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  4223. }
  4224. } SMARTLIST_FOREACH_END(t);
  4225. smartlist_free(id_lines);
  4226. }
  4227. {
  4228. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4229. if (a_lines) {
  4230. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4231. smartlist_free(a_lines);
  4232. }
  4233. }
  4234. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4235. int i;
  4236. md->family = smartlist_new();
  4237. for (i=0;i<tok->n_args;++i) {
  4238. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4239. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4240. escaped(tok->args[i]));
  4241. goto next;
  4242. }
  4243. smartlist_add(md->family, tor_strdup(tok->args[i]));
  4244. }
  4245. }
  4246. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4247. md->exit_policy = parse_short_policy(tok->args[0]);
  4248. }
  4249. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4250. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4251. }
  4252. smartlist_add(result, md);
  4253. okay = 1;
  4254. md = NULL;
  4255. next:
  4256. if (! okay && invalid_digests_out) {
  4257. smartlist_add(invalid_digests_out,
  4258. tor_memdup(md->digest, DIGEST256_LEN));
  4259. }
  4260. microdesc_free(md);
  4261. md = NULL;
  4262. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4263. memarea_clear(area);
  4264. smartlist_clear(tokens);
  4265. s = start_of_next_microdesc;
  4266. }
  4267. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4268. memarea_drop_all(area);
  4269. smartlist_free(tokens);
  4270. return result;
  4271. }
  4272. /** Parse the Tor version of the platform string <b>platform</b>,
  4273. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4274. * the router is at least as new as the cutoff, else return 0.
  4275. */
  4276. int
  4277. tor_version_as_new_as(const char *platform, const char *cutoff)
  4278. {
  4279. tor_version_t cutoff_version, router_version;
  4280. char *s, *s2, *start;
  4281. char tmp[128];
  4282. tor_assert(platform);
  4283. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4284. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4285. return 0;
  4286. }
  4287. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4288. return 1;
  4289. start = (char *)eat_whitespace(platform+3);
  4290. if (!*start) return 0;
  4291. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4292. s2 = (char*)eat_whitespace(s);
  4293. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4294. s = (char*)find_whitespace(s2);
  4295. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4296. return 0;
  4297. strlcpy(tmp, start, s-start+1);
  4298. if (tor_version_parse(tmp, &router_version)<0) {
  4299. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4300. return 1; /* be safe and say yes */
  4301. }
  4302. /* Here's why we don't need to do any special handling for svn revisions:
  4303. * - If neither has an svn revision, we're fine.
  4304. * - If the router doesn't have an svn revision, we can't assume that it
  4305. * is "at least" any svn revision, so we need to return 0.
  4306. * - If the target version doesn't have an svn revision, any svn revision
  4307. * (or none at all) is good enough, so return 1.
  4308. * - If both target and router have an svn revision, we compare them.
  4309. */
  4310. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  4311. }
  4312. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  4313. * Return 0 on success, -1 on failure. */
  4314. int
  4315. tor_version_parse(const char *s, tor_version_t *out)
  4316. {
  4317. char *eos=NULL;
  4318. const char *cp=NULL;
  4319. /* Format is:
  4320. * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
  4321. */
  4322. tor_assert(s);
  4323. tor_assert(out);
  4324. memset(out, 0, sizeof(tor_version_t));
  4325. out->status = VER_RELEASE;
  4326. if (!strcasecmpstart(s, "Tor "))
  4327. s += 4;
  4328. cp = s;
  4329. #define NUMBER(m) \
  4330. do { \
  4331. out->m = (int)strtol(cp, &eos, 10); \
  4332. if (!eos || eos == cp) \
  4333. return -1; \
  4334. cp = eos; \
  4335. } while (0)
  4336. #define DOT() \
  4337. do { \
  4338. if (*cp != '.') \
  4339. return -1; \
  4340. ++cp; \
  4341. } while (0)
  4342. NUMBER(major);
  4343. DOT();
  4344. NUMBER(minor);
  4345. if (*cp == 0)
  4346. return 0;
  4347. else if (*cp == '-')
  4348. goto status_tag;
  4349. DOT();
  4350. NUMBER(micro);
  4351. /* Get status */
  4352. if (*cp == 0) {
  4353. return 0;
  4354. } else if (*cp == '.') {
  4355. ++cp;
  4356. } else if (*cp == '-') {
  4357. goto status_tag;
  4358. } else if (0==strncmp(cp, "pre", 3)) {
  4359. out->status = VER_PRE;
  4360. cp += 3;
  4361. } else if (0==strncmp(cp, "rc", 2)) {
  4362. out->status = VER_RC;
  4363. cp += 2;
  4364. } else {
  4365. return -1;
  4366. }
  4367. NUMBER(patchlevel);
  4368. status_tag:
  4369. /* Get status tag. */
  4370. if (*cp == '-' || *cp == '.')
  4371. ++cp;
  4372. eos = (char*) find_whitespace(cp);
  4373. if (eos-cp >= (int)sizeof(out->status_tag))
  4374. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  4375. else {
  4376. memcpy(out->status_tag, cp, eos-cp);
  4377. out->status_tag[eos-cp] = 0;
  4378. }
  4379. cp = eat_whitespace(eos);
  4380. if (!strcmpstart(cp, "(r")) {
  4381. cp += 2;
  4382. out->svn_revision = (int) strtol(cp,&eos,10);
  4383. } else if (!strcmpstart(cp, "(git-")) {
  4384. char *close_paren = strchr(cp, ')');
  4385. int hexlen;
  4386. char digest[DIGEST_LEN];
  4387. if (! close_paren)
  4388. return -1;
  4389. cp += 5;
  4390. if (close_paren-cp > HEX_DIGEST_LEN)
  4391. return -1;
  4392. hexlen = (int)(close_paren-cp);
  4393. memwipe(digest, 0, sizeof(digest));
  4394. if ( hexlen == 0 || (hexlen % 2) == 1)
  4395. return -1;
  4396. if (base16_decode(digest, hexlen/2, cp, hexlen))
  4397. return -1;
  4398. memcpy(out->git_tag, digest, hexlen/2);
  4399. out->git_tag_len = hexlen/2;
  4400. }
  4401. return 0;
  4402. #undef NUMBER
  4403. #undef DOT
  4404. }
  4405. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  4406. * b. */
  4407. int
  4408. tor_version_compare(tor_version_t *a, tor_version_t *b)
  4409. {
  4410. int i;
  4411. tor_assert(a);
  4412. tor_assert(b);
  4413. if ((i = a->major - b->major))
  4414. return i;
  4415. else if ((i = a->minor - b->minor))
  4416. return i;
  4417. else if ((i = a->micro - b->micro))
  4418. return i;
  4419. else if ((i = a->status - b->status))
  4420. return i;
  4421. else if ((i = a->patchlevel - b->patchlevel))
  4422. return i;
  4423. else if ((i = strcmp(a->status_tag, b->status_tag)))
  4424. return i;
  4425. else if ((i = a->svn_revision - b->svn_revision))
  4426. return i;
  4427. else if ((i = a->git_tag_len - b->git_tag_len))
  4428. return i;
  4429. else if (a->git_tag_len)
  4430. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  4431. else
  4432. return 0;
  4433. }
  4434. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  4435. */
  4436. int
  4437. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  4438. {
  4439. tor_assert(a);
  4440. tor_assert(b);
  4441. return ((a->major == b->major) &&
  4442. (a->minor == b->minor) &&
  4443. (a->micro == b->micro));
  4444. }
  4445. /** Helper: Given pointers to two strings describing tor versions, return -1
  4446. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  4447. * Used to sort a list of versions. */
  4448. static int
  4449. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  4450. {
  4451. const char *a = *_a, *b = *_b;
  4452. int ca, cb;
  4453. tor_version_t va, vb;
  4454. ca = tor_version_parse(a, &va);
  4455. cb = tor_version_parse(b, &vb);
  4456. /* If they both parse, compare them. */
  4457. if (!ca && !cb)
  4458. return tor_version_compare(&va,&vb);
  4459. /* If one parses, it comes first. */
  4460. if (!ca && cb)
  4461. return -1;
  4462. if (ca && !cb)
  4463. return 1;
  4464. /* If neither parses, compare strings. Also, the directory server admin
  4465. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  4466. return strcmp(a,b);
  4467. }
  4468. /** Sort a list of string-representations of versions in ascending order. */
  4469. void
  4470. sort_version_list(smartlist_t *versions, int remove_duplicates)
  4471. {
  4472. smartlist_sort(versions, compare_tor_version_str_ptr_);
  4473. if (remove_duplicates)
  4474. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  4475. }
  4476. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  4477. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  4478. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  4479. * encrypted introduction points to the newly allocated
  4480. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  4481. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  4482. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  4483. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  4484. * and -1 for failure.
  4485. *
  4486. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  4487. * be strict about time formats.
  4488. */
  4489. int
  4490. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  4491. char *desc_id_out,
  4492. char **intro_points_encrypted_out,
  4493. size_t *intro_points_encrypted_size_out,
  4494. size_t *encoded_size_out,
  4495. const char **next_out, const char *desc,
  4496. int as_hsdir)
  4497. {
  4498. rend_service_descriptor_t *result =
  4499. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  4500. char desc_hash[DIGEST_LEN];
  4501. const char *eos;
  4502. smartlist_t *tokens = smartlist_new();
  4503. directory_token_t *tok;
  4504. char secret_id_part[DIGEST_LEN];
  4505. int i, version, num_ok=1;
  4506. smartlist_t *versions;
  4507. char public_key_hash[DIGEST_LEN];
  4508. char test_desc_id[DIGEST_LEN];
  4509. memarea_t *area = NULL;
  4510. const int strict_time_fmt = as_hsdir;
  4511. tor_assert(desc);
  4512. /* Check if desc starts correctly. */
  4513. if (strncmp(desc, "rendezvous-service-descriptor ",
  4514. strlen("rendezvous-service-descriptor "))) {
  4515. log_info(LD_REND, "Descriptor does not start correctly.");
  4516. goto err;
  4517. }
  4518. /* Compute descriptor hash for later validation. */
  4519. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  4520. "rendezvous-service-descriptor ",
  4521. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  4522. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  4523. goto err;
  4524. }
  4525. /* Determine end of string. */
  4526. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  4527. if (!eos)
  4528. eos = desc + strlen(desc);
  4529. else
  4530. eos = eos + 1;
  4531. /* Check length. */
  4532. if (eos-desc > REND_DESC_MAX_SIZE) {
  4533. /* XXX023 If we are parsing this descriptor as a server, this
  4534. * should be a protocol warning. */
  4535. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  4536. "maximum rendezvous descriptor size of %d bytes.",
  4537. (int)(eos-desc), REND_DESC_MAX_SIZE);
  4538. goto err;
  4539. }
  4540. /* Tokenize descriptor. */
  4541. area = memarea_new();
  4542. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  4543. log_warn(LD_REND, "Error tokenizing descriptor.");
  4544. goto err;
  4545. }
  4546. /* Set next to next descriptor, if available. */
  4547. *next_out = eos;
  4548. /* Set length of encoded descriptor. */
  4549. *encoded_size_out = eos - desc;
  4550. /* Check min allowed length of token list. */
  4551. if (smartlist_len(tokens) < 7) {
  4552. log_warn(LD_REND, "Impossibly short descriptor.");
  4553. goto err;
  4554. }
  4555. /* Parse base32-encoded descriptor ID. */
  4556. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  4557. tor_assert(tok == smartlist_get(tokens, 0));
  4558. tor_assert(tok->n_args == 1);
  4559. if (!rend_valid_descriptor_id(tok->args[0])) {
  4560. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  4561. goto err;
  4562. }
  4563. if (base32_decode(desc_id_out, DIGEST_LEN,
  4564. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  4565. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  4566. tok->args[0]);
  4567. goto err;
  4568. }
  4569. /* Parse descriptor version. */
  4570. tok = find_by_keyword(tokens, R_VERSION);
  4571. tor_assert(tok->n_args == 1);
  4572. result->version =
  4573. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  4574. if (result->version != 2 || !num_ok) {
  4575. /* If it's <2, it shouldn't be under this format. If the number
  4576. * is greater than 2, we bumped it because we broke backward
  4577. * compatibility. See how version numbers in our other formats
  4578. * work. */
  4579. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  4580. escaped(tok->args[0]));
  4581. goto err;
  4582. }
  4583. /* Parse public key. */
  4584. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  4585. result->pk = tok->key;
  4586. tok->key = NULL; /* Prevent free */
  4587. /* Parse secret ID part. */
  4588. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  4589. tor_assert(tok->n_args == 1);
  4590. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  4591. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  4592. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  4593. goto err;
  4594. }
  4595. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  4596. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  4597. tok->args[0]);
  4598. goto err;
  4599. }
  4600. /* Parse publication time -- up-to-date check is done when storing the
  4601. * descriptor. */
  4602. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  4603. tor_assert(tok->n_args == 1);
  4604. if (parse_iso_time_(tok->args[0], &result->timestamp, strict_time_fmt) < 0) {
  4605. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  4606. goto err;
  4607. }
  4608. /* Parse protocol versions. */
  4609. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  4610. tor_assert(tok->n_args == 1);
  4611. versions = smartlist_new();
  4612. smartlist_split_string(versions, tok->args[0], ",",
  4613. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4614. for (i = 0; i < smartlist_len(versions); i++) {
  4615. version = (int) tor_parse_long(smartlist_get(versions, i),
  4616. 10, 0, INT_MAX, &num_ok, NULL);
  4617. if (!num_ok) /* It's a string; let's ignore it. */
  4618. continue;
  4619. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  4620. /* Avoid undefined left-shift behaviour. */
  4621. continue;
  4622. result->protocols |= 1 << version;
  4623. }
  4624. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  4625. smartlist_free(versions);
  4626. /* Parse encrypted introduction points. Don't verify. */
  4627. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  4628. if (tok) {
  4629. if (strcmp(tok->object_type, "MESSAGE")) {
  4630. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  4631. "type MESSAGE");
  4632. goto err;
  4633. }
  4634. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  4635. tok->object_size);
  4636. *intro_points_encrypted_size_out = tok->object_size;
  4637. } else {
  4638. *intro_points_encrypted_out = NULL;
  4639. *intro_points_encrypted_size_out = 0;
  4640. }
  4641. /* Parse and verify signature. */
  4642. tok = find_by_keyword(tokens, R_SIGNATURE);
  4643. note_crypto_pk_op(VERIFY_RTR);
  4644. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  4645. "v2 rendezvous service descriptor") < 0)
  4646. goto err;
  4647. /* Verify that descriptor ID belongs to public key and secret ID part. */
  4648. crypto_pk_get_digest(result->pk, public_key_hash);
  4649. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  4650. secret_id_part);
  4651. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  4652. log_warn(LD_REND, "Parsed descriptor ID does not match "
  4653. "computed descriptor ID.");
  4654. goto err;
  4655. }
  4656. goto done;
  4657. err:
  4658. rend_service_descriptor_free(result);
  4659. result = NULL;
  4660. done:
  4661. if (tokens) {
  4662. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4663. smartlist_free(tokens);
  4664. }
  4665. if (area)
  4666. memarea_drop_all(area);
  4667. *parsed_out = result;
  4668. if (result)
  4669. return 0;
  4670. return -1;
  4671. }
  4672. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  4673. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  4674. * write the result to a newly allocated string that is pointed to by
  4675. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  4676. * Return 0 if decryption was successful and -1 otherwise. */
  4677. int
  4678. rend_decrypt_introduction_points(char **ipos_decrypted,
  4679. size_t *ipos_decrypted_size,
  4680. const char *descriptor_cookie,
  4681. const char *ipos_encrypted,
  4682. size_t ipos_encrypted_size)
  4683. {
  4684. tor_assert(ipos_encrypted);
  4685. tor_assert(descriptor_cookie);
  4686. if (ipos_encrypted_size < 2) {
  4687. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4688. "small.");
  4689. return -1;
  4690. }
  4691. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  4692. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  4693. session_key[CIPHER_KEY_LEN], *dec;
  4694. int declen, client_blocks;
  4695. size_t pos = 0, len, client_entries_len;
  4696. crypto_digest_t *digest;
  4697. crypto_cipher_t *cipher;
  4698. client_blocks = (int) ipos_encrypted[1];
  4699. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  4700. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  4701. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  4702. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4703. "small.");
  4704. return -1;
  4705. }
  4706. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  4707. digest = crypto_digest_new();
  4708. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  4709. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  4710. crypto_digest_get_digest(digest, client_id,
  4711. REND_BASIC_AUTH_CLIENT_ID_LEN);
  4712. crypto_digest_free(digest);
  4713. for (pos = 2; pos < 2 + client_entries_len;
  4714. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  4715. if (tor_memeq(ipos_encrypted + pos, client_id,
  4716. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  4717. /* Attempt to decrypt introduction points. */
  4718. cipher = crypto_cipher_new(descriptor_cookie);
  4719. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  4720. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  4721. CIPHER_KEY_LEN) < 0) {
  4722. log_warn(LD_REND, "Could not decrypt session key for client.");
  4723. crypto_cipher_free(cipher);
  4724. return -1;
  4725. }
  4726. crypto_cipher_free(cipher);
  4727. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  4728. dec = tor_malloc(len);
  4729. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  4730. ipos_encrypted + 2 + client_entries_len,
  4731. ipos_encrypted_size - 2 - client_entries_len);
  4732. if (declen < 0) {
  4733. log_warn(LD_REND, "Could not decrypt introduction point string.");
  4734. tor_free(dec);
  4735. return -1;
  4736. }
  4737. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  4738. log_warn(LD_REND, "Decrypted introduction points don't "
  4739. "look like we could parse them.");
  4740. tor_free(dec);
  4741. continue;
  4742. }
  4743. *ipos_decrypted = dec;
  4744. *ipos_decrypted_size = declen;
  4745. return 0;
  4746. }
  4747. }
  4748. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  4749. "check your authorization for this service!");
  4750. return -1;
  4751. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  4752. char *dec;
  4753. int declen;
  4754. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  4755. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4756. "small.");
  4757. return -1;
  4758. }
  4759. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  4760. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  4761. ipos_encrypted_size -
  4762. CIPHER_IV_LEN - 1,
  4763. ipos_encrypted + 1,
  4764. ipos_encrypted_size - 1);
  4765. if (declen < 0) {
  4766. log_warn(LD_REND, "Decrypting introduction points failed!");
  4767. tor_free(dec);
  4768. return -1;
  4769. }
  4770. *ipos_decrypted = dec;
  4771. *ipos_decrypted_size = declen;
  4772. return 0;
  4773. } else {
  4774. log_warn(LD_REND, "Unknown authorization type number: %d",
  4775. ipos_encrypted[0]);
  4776. return -1;
  4777. }
  4778. }
  4779. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  4780. * length <b>intro_points_encoded_size</b> and write the result to the
  4781. * descriptor in <b>parsed</b>; return the number of successfully parsed
  4782. * introduction points or -1 in case of a failure. */
  4783. int
  4784. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  4785. const char *intro_points_encoded,
  4786. size_t intro_points_encoded_size)
  4787. {
  4788. const char *current_ipo, *end_of_intro_points;
  4789. smartlist_t *tokens = NULL;
  4790. directory_token_t *tok;
  4791. rend_intro_point_t *intro;
  4792. extend_info_t *info;
  4793. int result, num_ok=1;
  4794. memarea_t *area = NULL;
  4795. tor_assert(parsed);
  4796. /** Function may only be invoked once. */
  4797. tor_assert(!parsed->intro_nodes);
  4798. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  4799. log_warn(LD_REND, "Empty or zero size introduction point list");
  4800. goto err;
  4801. }
  4802. /* Consider one intro point after the other. */
  4803. current_ipo = intro_points_encoded;
  4804. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  4805. tokens = smartlist_new();
  4806. parsed->intro_nodes = smartlist_new();
  4807. area = memarea_new();
  4808. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  4809. "introduction-point ")) {
  4810. /* Determine end of string. */
  4811. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  4812. "\nintroduction-point ");
  4813. if (!eos)
  4814. eos = end_of_intro_points;
  4815. else
  4816. eos = eos+1;
  4817. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  4818. /* Free tokens and clear token list. */
  4819. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4820. smartlist_clear(tokens);
  4821. memarea_clear(area);
  4822. /* Tokenize string. */
  4823. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  4824. log_warn(LD_REND, "Error tokenizing introduction point");
  4825. goto err;
  4826. }
  4827. /* Advance to next introduction point, if available. */
  4828. current_ipo = eos;
  4829. /* Check minimum allowed length of introduction point. */
  4830. if (smartlist_len(tokens) < 5) {
  4831. log_warn(LD_REND, "Impossibly short introduction point.");
  4832. goto err;
  4833. }
  4834. /* Allocate new intro point and extend info. */
  4835. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  4836. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  4837. /* Parse identifier. */
  4838. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  4839. if (base32_decode(info->identity_digest, DIGEST_LEN,
  4840. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  4841. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  4842. tok->args[0]);
  4843. rend_intro_point_free(intro);
  4844. goto err;
  4845. }
  4846. /* Write identifier to nickname. */
  4847. info->nickname[0] = '$';
  4848. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  4849. info->identity_digest, DIGEST_LEN);
  4850. /* Parse IP address. */
  4851. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  4852. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  4853. log_warn(LD_REND, "Could not parse introduction point address.");
  4854. rend_intro_point_free(intro);
  4855. goto err;
  4856. }
  4857. if (tor_addr_family(&info->addr) != AF_INET) {
  4858. log_warn(LD_REND, "Introduction point address was not ipv4.");
  4859. rend_intro_point_free(intro);
  4860. goto err;
  4861. }
  4862. /* Parse onion port. */
  4863. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  4864. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  4865. &num_ok,NULL);
  4866. if (!info->port || !num_ok) {
  4867. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  4868. escaped(tok->args[0]));
  4869. rend_intro_point_free(intro);
  4870. goto err;
  4871. }
  4872. /* Parse onion key. */
  4873. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  4874. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4875. log_warn(LD_REND,
  4876. "Introduction point's onion key had invalid exponent.");
  4877. rend_intro_point_free(intro);
  4878. goto err;
  4879. }
  4880. info->onion_key = tok->key;
  4881. tok->key = NULL; /* Prevent free */
  4882. /* Parse service key. */
  4883. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  4884. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4885. log_warn(LD_REND,
  4886. "Introduction point key had invalid exponent.");
  4887. rend_intro_point_free(intro);
  4888. goto err;
  4889. }
  4890. intro->intro_key = tok->key;
  4891. tok->key = NULL; /* Prevent free */
  4892. /* Add extend info to list of introduction points. */
  4893. smartlist_add(parsed->intro_nodes, intro);
  4894. }
  4895. result = smartlist_len(parsed->intro_nodes);
  4896. goto done;
  4897. err:
  4898. result = -1;
  4899. done:
  4900. /* Free tokens and clear token list. */
  4901. if (tokens) {
  4902. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4903. smartlist_free(tokens);
  4904. }
  4905. if (area)
  4906. memarea_drop_all(area);
  4907. return result;
  4908. }
  4909. /** Parse the content of a client_key file in <b>ckstr</b> and add
  4910. * rend_authorized_client_t's for each parsed client to
  4911. * <b>parsed_clients</b>. Return the number of parsed clients as result
  4912. * or -1 for failure. */
  4913. int
  4914. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  4915. {
  4916. int result = -1;
  4917. smartlist_t *tokens;
  4918. directory_token_t *tok;
  4919. const char *current_entry = NULL;
  4920. memarea_t *area = NULL;
  4921. char *err_msg = NULL;
  4922. if (!ckstr || strlen(ckstr) == 0)
  4923. return -1;
  4924. tokens = smartlist_new();
  4925. /* Begin parsing with first entry, skipping comments or whitespace at the
  4926. * beginning. */
  4927. area = memarea_new();
  4928. current_entry = eat_whitespace(ckstr);
  4929. while (!strcmpstart(current_entry, "client-name ")) {
  4930. rend_authorized_client_t *parsed_entry;
  4931. /* Determine end of string. */
  4932. const char *eos = strstr(current_entry, "\nclient-name ");
  4933. if (!eos)
  4934. eos = current_entry + strlen(current_entry);
  4935. else
  4936. eos = eos + 1;
  4937. /* Free tokens and clear token list. */
  4938. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4939. smartlist_clear(tokens);
  4940. memarea_clear(area);
  4941. /* Tokenize string. */
  4942. if (tokenize_string(area, current_entry, eos, tokens,
  4943. client_keys_token_table, 0)) {
  4944. log_warn(LD_REND, "Error tokenizing client keys file.");
  4945. goto err;
  4946. }
  4947. /* Advance to next entry, if available. */
  4948. current_entry = eos;
  4949. /* Check minimum allowed length of token list. */
  4950. if (smartlist_len(tokens) < 2) {
  4951. log_warn(LD_REND, "Impossibly short client key entry.");
  4952. goto err;
  4953. }
  4954. /* Parse client name. */
  4955. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  4956. tor_assert(tok == smartlist_get(tokens, 0));
  4957. tor_assert(tok->n_args == 1);
  4958. if (!rend_valid_client_name(tok->args[0])) {
  4959. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  4960. "between 1 and %d, and valid characters are "
  4961. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  4962. goto err;
  4963. }
  4964. /* Check if client name is duplicate. */
  4965. if (strmap_get(parsed_clients, tok->args[0])) {
  4966. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  4967. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  4968. goto err;
  4969. }
  4970. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  4971. parsed_entry->client_name = tor_strdup(tok->args[0]);
  4972. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  4973. /* Parse client key. */
  4974. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  4975. if (tok) {
  4976. parsed_entry->client_key = tok->key;
  4977. tok->key = NULL; /* Prevent free */
  4978. }
  4979. /* Parse descriptor cookie. */
  4980. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  4981. tor_assert(tok->n_args == 1);
  4982. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  4983. NULL, &err_msg) < 0) {
  4984. tor_assert(err_msg);
  4985. log_warn(LD_REND, "%s", err_msg);
  4986. tor_free(err_msg);
  4987. goto err;
  4988. }
  4989. }
  4990. result = strmap_size(parsed_clients);
  4991. goto done;
  4992. err:
  4993. result = -1;
  4994. done:
  4995. /* Free tokens and clear token list. */
  4996. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4997. smartlist_free(tokens);
  4998. if (area)
  4999. memarea_drop_all(area);
  5000. return result;
  5001. }