routerparse.c 167 KB

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