routerparse.c 172 KB

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