routerparse.c 173 KB

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