routerparse.c 182 KB

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