routerparse.c 165 KB

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