routerparse.c 165 KB

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