routerparse.c 179 KB

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