routerparse.c 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerparse.c
  8. * \brief Code to parse and validate router descriptors, consenus directories,
  9. * and similar objects.
  10. *
  11. * The objects parsed by this module use a common text-based metaformat,
  12. * documented in dir-spec.txt in torspec.git. This module is itself divided
  13. * into two major kinds of function: code to handle the metaformat, and code
  14. * to convert from particular instances of the metaformat into the
  15. * objects that Tor uses.
  16. *
  17. * The generic parsing code works by calling a table-based tokenizer on the
  18. * input string. Each token corresponds to a single line with a token, plus
  19. * optional arguments on that line, plus an optional base-64 encoded object
  20. * after that line. Each token has a definition in a table of token_rule_t
  21. * entries that describes how many arguments it can take, whether it takes an
  22. * object, how many times it may appear, whether it must appear first, and so
  23. * on.
  24. *
  25. * The tokenizer function tokenize_string() converts its string input into a
  26. * smartlist full of instances of directory_token_t, according to a provided
  27. * table of token_rule_t.
  28. *
  29. * The generic parts of this module additionally include functions for
  30. * finding the start and end of signed information inside a signed object, and
  31. * computing the digest that will be signed.
  32. *
  33. * There are also functions for saving objects to disk that have caused
  34. * parsing to fail.
  35. *
  36. * The specific parts of this module describe conversions between
  37. * particular lists of directory_token_t and particular objects. The
  38. * kinds of objects that can be parsed here are:
  39. * <ul>
  40. * <li>router descriptors (managed from routerlist.c)
  41. * <li>extra-info documents (managed from routerlist.c)
  42. * <li>microdescriptors (managed from microdesc.c)
  43. * <li>vote and consensus networkstatus documents, and the routerstatus_t
  44. * objects that they comprise (managed from networkstatus.c)
  45. * <li>detached-signature objects used by authorities for gathering
  46. * signatures on the networkstatus consensus (managed from dirvote.c)
  47. * <li>authority key certificates (managed from routerlist.c)
  48. * <li>hidden service descriptors (managed from rendcommon.c and rendcache.c)
  49. * </ul>
  50. **/
  51. #define ROUTERPARSE_PRIVATE
  52. #include "core/or/or.h"
  53. #include "app/config/config.h"
  54. #include "core/or/circuitstats.h"
  55. #include "core/or/policies.h"
  56. #include "core/or/protover.h"
  57. #include "feature/client/entrynodes.h"
  58. #include "feature/dirauth/shared_random.h"
  59. #include "feature/dircommon/voting_schedule.h"
  60. #include "feature/dirparse/parsecommon.h"
  61. #include "feature/dirparse/routerparse.h"
  62. #include "feature/hs_common/shared_random_client.h"
  63. #include "feature/nodelist/authcert.h"
  64. #include "feature/nodelist/describe.h"
  65. #include "feature/nodelist/microdesc.h"
  66. #include "feature/nodelist/networkstatus.h"
  67. #include "feature/nodelist/nickname.h"
  68. #include "feature/nodelist/routerinfo.h"
  69. #include "feature/nodelist/routerlist.h"
  70. #include "feature/nodelist/torcert.h"
  71. #include "feature/relay/router.h"
  72. #include "feature/relay/routerkeys.h"
  73. #include "feature/rend/rendcommon.h"
  74. #include "feature/stats/rephist.h"
  75. #include "lib/crypt_ops/crypto_format.h"
  76. #include "lib/crypt_ops/crypto_util.h"
  77. #include "lib/memarea/memarea.h"
  78. #include "lib/sandbox/sandbox.h"
  79. #include "feature/dirparse/authcert_parse.h"
  80. #include "feature/dirparse/sigcommon.h"
  81. #include "feature/dirparse/unparseable.h"
  82. #include "feature/dirauth/dirvote.h"
  83. #include "core/or/addr_policy_st.h"
  84. #include "feature/nodelist/authority_cert_st.h"
  85. #include "feature/nodelist/document_signature_st.h"
  86. #include "core/or/extend_info_st.h"
  87. #include "feature/nodelist/extrainfo_st.h"
  88. #include "feature/nodelist/microdesc_st.h"
  89. #include "feature/nodelist/networkstatus_st.h"
  90. #include "feature/nodelist/networkstatus_voter_info_st.h"
  91. #include "feature/dirauth/ns_detached_signatures_st.h"
  92. #include "feature/rend/rend_authorized_client_st.h"
  93. #include "feature/rend/rend_intro_point_st.h"
  94. #include "feature/rend/rend_service_descriptor_st.h"
  95. #include "feature/nodelist/routerinfo_st.h"
  96. #include "feature/nodelist/routerlist_st.h"
  97. #include "core/or/tor_version_st.h"
  98. #include "feature/dirauth/vote_microdesc_hash_st.h"
  99. #include "feature/nodelist/vote_routerstatus_st.h"
  100. #include "lib/container/bloomfilt.h"
  101. #undef log
  102. #include <math.h>
  103. /****************************************************************************/
  104. /** List of tokens recognized in router descriptors */
  105. static token_rule_t routerdesc_token_table[] = {
  106. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  107. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  108. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  109. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  110. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  111. T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
  112. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  113. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  114. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  115. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  116. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  117. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  118. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  119. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  120. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  121. T01("proto", K_PROTO, CONCAT_ARGS, NO_OBJ ),
  122. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  123. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  124. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  125. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  126. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  127. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  128. T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
  129. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  130. T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
  131. T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
  132. EQ(1), NEED_OBJ ),
  133. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  134. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  135. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  136. T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
  137. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  138. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  139. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  140. T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
  141. END_OF_TABLE
  142. };
  143. /** List of tokens recognized in extra-info documents. */
  144. static token_rule_t extrainfo_token_table[] = {
  145. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  146. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  147. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  148. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  149. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  150. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  151. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  152. T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
  153. T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
  154. T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
  155. T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
  156. T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
  157. T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
  158. T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
  159. T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
  160. T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
  161. T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
  162. T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
  163. T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
  164. T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
  165. T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
  166. T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
  167. T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
  168. T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
  169. T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
  170. T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
  171. T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
  172. T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
  173. T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
  174. T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
  175. T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
  176. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  177. END_OF_TABLE
  178. };
  179. /** List of tokens recognized in the body part of v3 networkstatus
  180. * documents. */
  181. static token_rule_t rtrstatus_token_table[] = {
  182. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  183. T1( "r", K_R, GE(7), NO_OBJ ),
  184. T0N("a", K_A, GE(1), NO_OBJ ),
  185. T1( "s", K_S, ARGS, NO_OBJ ),
  186. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  187. T01("w", K_W, ARGS, NO_OBJ ),
  188. T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
  189. T0N("id", K_ID, GE(2), NO_OBJ ),
  190. T01("pr", K_PROTO, CONCAT_ARGS, NO_OBJ ),
  191. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  192. END_OF_TABLE
  193. };
  194. /** List of tokens recognized in V3 networkstatus votes. */
  195. static token_rule_t networkstatus_token_table[] = {
  196. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  197. GE(1), NO_OBJ ),
  198. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  199. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  200. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  201. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  202. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  203. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  204. T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
  205. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  206. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  207. T01("signing-ed25519", K_SIGNING_CERT_ED, NO_ARGS , NEED_OBJ ),
  208. T01("shared-rand-participate",K_SR_FLAG, NO_ARGS, NO_OBJ ),
  209. T0N("shared-rand-commit", K_COMMIT, GE(3), NO_OBJ ),
  210. T01("shared-rand-previous-value", K_PREVIOUS_SRV,EQ(2), NO_OBJ ),
  211. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  212. T0N("package", K_PACKAGE, CONCAT_ARGS, NO_OBJ ),
  213. T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
  214. CONCAT_ARGS, NO_OBJ ),
  215. T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
  216. CONCAT_ARGS, NO_OBJ ),
  217. T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
  218. CONCAT_ARGS, NO_OBJ ),
  219. T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
  220. CONCAT_ARGS, NO_OBJ ),
  221. #include "feature/dirparse/authcert_members.i"
  222. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  223. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  224. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  225. T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
  226. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  227. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  228. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  229. T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
  230. END_OF_TABLE
  231. };
  232. /** List of tokens recognized in V3 networkstatus consensuses. */
  233. static token_rule_t networkstatus_consensus_token_table[] = {
  234. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  235. GE(1), NO_OBJ ),
  236. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  237. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  238. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  239. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  240. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  241. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  242. T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  243. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  244. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  245. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  246. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  247. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  248. T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
  249. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  250. T01("shared-rand-previous-value", K_PREVIOUS_SRV, EQ(2), NO_OBJ ),
  251. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  252. T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
  253. CONCAT_ARGS, NO_OBJ ),
  254. T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
  255. CONCAT_ARGS, NO_OBJ ),
  256. T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
  257. CONCAT_ARGS, NO_OBJ ),
  258. T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
  259. CONCAT_ARGS, NO_OBJ ),
  260. END_OF_TABLE
  261. };
  262. /** List of tokens recognized in the footer of v1 directory footers. */
  263. static token_rule_t networkstatus_vote_footer_token_table[] = {
  264. T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
  265. T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
  266. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  267. END_OF_TABLE
  268. };
  269. /** List of tokens recognized in detached networkstatus signature documents. */
  270. static token_rule_t networkstatus_detached_signature_token_table[] = {
  271. T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
  272. T("additional-digest", K_ADDITIONAL_DIGEST,GE(3), NO_OBJ ),
  273. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  274. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  275. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  276. T("additional-signature", K_ADDITIONAL_SIGNATURE, GE(4), NEED_OBJ ),
  277. T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  278. END_OF_TABLE
  279. };
  280. /** List of tokens recognized in microdescriptors */
  281. static token_rule_t microdesc_token_table[] = {
  282. T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  283. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  284. T0N("id", K_ID, GE(2), NO_OBJ ),
  285. T0N("a", K_A, GE(1), NO_OBJ ),
  286. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  287. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  288. T01("p6", K_P6, CONCAT_ARGS, NO_OBJ ),
  289. A01("@last-listed", A_LAST_LISTED, CONCAT_ARGS, NO_OBJ ),
  290. END_OF_TABLE
  291. };
  292. #undef T
  293. /* static function prototypes */
  294. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  295. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
  296. unsigned fmt_flags);
  297. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  298. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  299. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  300. * <b>s</b>. Return 0 on success, -1 on failure.
  301. */
  302. int
  303. router_get_router_hash(const char *s, size_t s_len, char *digest)
  304. {
  305. return router_get_hash_impl(s, s_len, digest,
  306. "router ","\nrouter-signature", '\n',
  307. DIGEST_SHA1);
  308. }
  309. /** Try to find the start and end of the signed portion of a networkstatus
  310. * document in <b>s</b>. On success, set <b>start_out</b> to the first
  311. * character of the document, and <b>end_out</b> to a position one after the
  312. * final character of the signed document, and return 0. On failure, return
  313. * -1. */
  314. int
  315. router_get_networkstatus_v3_signed_boundaries(const char *s,
  316. const char **start_out,
  317. const char **end_out)
  318. {
  319. return router_get_hash_impl_helper(s, strlen(s),
  320. "network-status-version",
  321. "\ndirectory-signature",
  322. ' ', LOG_INFO,
  323. start_out, end_out);
  324. }
  325. /** Set <b>digest_out</b> to the SHA3-256 digest of the signed portion of the
  326. * networkstatus vote in <b>s</b> -- or of the entirety of <b>s</b> if no
  327. * signed portion can be identified. Return 0 on success, -1 on failure. */
  328. int
  329. router_get_networkstatus_v3_sha3_as_signed(uint8_t *digest_out,
  330. const char *s)
  331. {
  332. const char *start, *end;
  333. if (router_get_networkstatus_v3_signed_boundaries(s, &start, &end) < 0) {
  334. start = s;
  335. end = s + strlen(s);
  336. }
  337. tor_assert(start);
  338. tor_assert(end);
  339. return crypto_digest256((char*)digest_out, start, end-start,
  340. DIGEST_SHA3_256);
  341. }
  342. /** Set <b>digests</b> to all the digests of the consensus document in
  343. * <b>s</b> */
  344. int
  345. router_get_networkstatus_v3_hashes(const char *s, common_digests_t *digests)
  346. {
  347. return router_get_hashes_impl(s,strlen(s),digests,
  348. "network-status-version",
  349. "\ndirectory-signature",
  350. ' ');
  351. }
  352. /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
  353. * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
  354. int
  355. router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
  356. {
  357. return router_get_hash_impl(s, s_len, digest, "extra-info",
  358. "\nrouter-signature",'\n', DIGEST_SHA1);
  359. }
  360. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  361. * or to the first of the annotations proceeding the next router or
  362. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  363. * we found an extrainfo, or false if found a router. Do not scan beyond
  364. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  365. static int
  366. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  367. const char *eos,
  368. int *is_extrainfo_out)
  369. {
  370. const char *annotations = NULL;
  371. const char *s = *s_ptr;
  372. s = eat_whitespace_eos(s, eos);
  373. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  374. /* We're at the start of a line. */
  375. tor_assert(*s != '\n');
  376. if (*s == '@' && !annotations) {
  377. annotations = s;
  378. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  379. *s_ptr = annotations ? annotations : s;
  380. *is_extrainfo_out = 0;
  381. return 0;
  382. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  383. *s_ptr = annotations ? annotations : s;
  384. *is_extrainfo_out = 1;
  385. return 0;
  386. }
  387. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  388. break;
  389. s = eat_whitespace_eos(s, eos);
  390. }
  391. return -1;
  392. }
  393. /** Given a string *<b>s</b> containing a concatenated sequence of router
  394. * descriptors (or extra-info documents if <b>want_extrainfo</b> is set),
  395. * parses them and stores the result in <b>dest</b>. All routers are marked
  396. * running and valid. Advances *s to a point immediately following the last
  397. * router entry. Ignore any trailing router entries that are not complete.
  398. *
  399. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  400. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  401. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  402. *
  403. * Returns 0 on success and -1 on failure. Adds a digest to
  404. * <b>invalid_digests_out</b> for every entry that was unparseable or
  405. * invalid. (This may cause duplicate entries.)
  406. */
  407. int
  408. router_parse_list_from_string(const char **s, const char *eos,
  409. smartlist_t *dest,
  410. saved_location_t saved_location,
  411. int want_extrainfo,
  412. int allow_annotations,
  413. const char *prepend_annotations,
  414. smartlist_t *invalid_digests_out)
  415. {
  416. routerinfo_t *router;
  417. extrainfo_t *extrainfo;
  418. signed_descriptor_t *signed_desc = NULL;
  419. void *elt;
  420. const char *end, *start;
  421. int have_extrainfo;
  422. tor_assert(s);
  423. tor_assert(*s);
  424. tor_assert(dest);
  425. start = *s;
  426. if (!eos)
  427. eos = *s + strlen(*s);
  428. tor_assert(eos >= *s);
  429. while (1) {
  430. char raw_digest[DIGEST_LEN];
  431. int have_raw_digest = 0;
  432. int dl_again = 0;
  433. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  434. break;
  435. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  436. if (end)
  437. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  438. if (end)
  439. end += strlen("\n-----END SIGNATURE-----\n");
  440. if (!end)
  441. break;
  442. elt = NULL;
  443. if (have_extrainfo && want_extrainfo) {
  444. routerlist_t *rl = router_get_routerlist();
  445. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  446. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  447. saved_location != SAVED_IN_CACHE,
  448. rl->identity_map, &dl_again);
  449. if (extrainfo) {
  450. signed_desc = &extrainfo->cache_info;
  451. elt = extrainfo;
  452. }
  453. } else if (!have_extrainfo && !want_extrainfo) {
  454. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  455. router = router_parse_entry_from_string(*s, end,
  456. saved_location != SAVED_IN_CACHE,
  457. allow_annotations,
  458. prepend_annotations, &dl_again);
  459. if (router) {
  460. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  461. router_describe(router),
  462. router_purpose_to_string(router->purpose));
  463. signed_desc = &router->cache_info;
  464. elt = router;
  465. }
  466. }
  467. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  468. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  469. }
  470. if (!elt) {
  471. *s = end;
  472. continue;
  473. }
  474. if (saved_location != SAVED_NOWHERE) {
  475. tor_assert(signed_desc);
  476. signed_desc->saved_location = saved_location;
  477. signed_desc->saved_offset = *s - start;
  478. }
  479. *s = end;
  480. smartlist_add(dest, elt);
  481. }
  482. return 0;
  483. }
  484. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  485. * with at least one argument (use GE(1) in setup). If found, store
  486. * address and port number to <b>addr_out</b> and
  487. * <b>port_out</b>. Return number of OR ports found. */
  488. static int
  489. find_single_ipv6_orport(const smartlist_t *list,
  490. tor_addr_t *addr_out,
  491. uint16_t *port_out)
  492. {
  493. int ret = 0;
  494. tor_assert(list != NULL);
  495. tor_assert(addr_out != NULL);
  496. tor_assert(port_out != NULL);
  497. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  498. tor_addr_t a;
  499. maskbits_t bits;
  500. uint16_t port_min, port_max;
  501. tor_assert(t->n_args >= 1);
  502. /* XXXX Prop186 the full spec allows much more than this. */
  503. if (tor_addr_parse_mask_ports(t->args[0], 0,
  504. &a, &bits, &port_min,
  505. &port_max) == AF_INET6 &&
  506. bits == 128 &&
  507. port_min == port_max) {
  508. /* Okay, this is one we can understand. Use it and ignore
  509. any potential more addresses in list. */
  510. tor_addr_copy(addr_out, &a);
  511. *port_out = port_min;
  512. ret = 1;
  513. break;
  514. }
  515. } SMARTLIST_FOREACH_END(t);
  516. return ret;
  517. }
  518. /** Helper function: reads a single router entry from *<b>s</b> ...
  519. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  520. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  521. * s through end into the signed_descriptor_body of the resulting
  522. * routerinfo_t.
  523. *
  524. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  525. *
  526. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  527. * before the router; if it's false, reject the router if it's annotated. If
  528. * <b>prepend_annotations</b> is set, it should contain some annotations:
  529. * append them to the front of the router before parsing it, and keep them
  530. * around when caching the router.
  531. *
  532. * Only one of allow_annotations and prepend_annotations may be set.
  533. *
  534. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  535. * if it's okay to try to download a descriptor with this same digest again,
  536. * and 0 if it isn't. (It might not be okay to download it again if part of
  537. * the part covered by the digest is invalid.)
  538. */
  539. routerinfo_t *
  540. router_parse_entry_from_string(const char *s, const char *end,
  541. int cache_copy, int allow_annotations,
  542. const char *prepend_annotations,
  543. int *can_dl_again_out)
  544. {
  545. routerinfo_t *router = NULL;
  546. char digest[128];
  547. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  548. directory_token_t *tok;
  549. struct in_addr in;
  550. const char *start_of_annotations, *cp, *s_dup = s;
  551. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  552. int ok = 1;
  553. memarea_t *area = NULL;
  554. tor_cert_t *ntor_cc_cert = NULL;
  555. /* Do not set this to '1' until we have parsed everything that we intend to
  556. * parse that's covered by the hash. */
  557. int can_dl_again = 0;
  558. crypto_pk_t *rsa_pubkey = NULL;
  559. tor_assert(!allow_annotations || !prepend_annotations);
  560. if (!end) {
  561. end = s + strlen(s);
  562. }
  563. /* point 'end' to a point immediately after the final newline. */
  564. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  565. --end;
  566. area = memarea_new();
  567. tokens = smartlist_new();
  568. if (prepend_annotations) {
  569. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  570. routerdesc_token_table,TS_NOCHECK)) {
  571. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  572. goto err;
  573. }
  574. }
  575. start_of_annotations = s;
  576. cp = tor_memstr(s, end-s, "\nrouter ");
  577. if (!cp) {
  578. if (end-s < 7 || strcmpstart(s, "router ")) {
  579. log_warn(LD_DIR, "No router keyword found.");
  580. goto err;
  581. }
  582. } else {
  583. s = cp+1;
  584. }
  585. if (start_of_annotations != s) { /* We have annotations */
  586. if (allow_annotations) {
  587. if (tokenize_string(area,start_of_annotations,s,tokens,
  588. routerdesc_token_table,TS_NOCHECK)) {
  589. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  590. goto err;
  591. }
  592. } else {
  593. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  594. "loaded from disk. Dropping it.");
  595. goto err;
  596. }
  597. }
  598. if (router_get_router_hash(s, end - s, digest) < 0) {
  599. log_warn(LD_DIR, "Couldn't compute router hash.");
  600. goto err;
  601. }
  602. {
  603. int flags = 0;
  604. if (allow_annotations)
  605. flags |= TS_ANNOTATIONS_OK;
  606. if (prepend_annotations)
  607. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  608. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  609. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  610. goto err;
  611. }
  612. }
  613. if (smartlist_len(tokens) < 2) {
  614. log_warn(LD_DIR, "Impossibly short router descriptor.");
  615. goto err;
  616. }
  617. tok = find_by_keyword(tokens, K_ROUTER);
  618. const int router_token_pos = smartlist_pos(tokens, tok);
  619. tor_assert(tok->n_args >= 5);
  620. router = tor_malloc_zero(sizeof(routerinfo_t));
  621. router->cert_expiration_time = TIME_MAX;
  622. router->cache_info.routerlist_index = -1;
  623. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  624. router->cache_info.signed_descriptor_len = end-s;
  625. if (cache_copy) {
  626. size_t len = router->cache_info.signed_descriptor_len +
  627. router->cache_info.annotations_len;
  628. char *signed_body =
  629. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  630. if (prepend_annotations) {
  631. memcpy(signed_body, prepend_annotations, prepend_len);
  632. signed_body += prepend_len;
  633. }
  634. /* This assertion will always succeed.
  635. * len == signed_desc_len + annotations_len
  636. * == end-s + s-start_of_annotations + prepend_len
  637. * == end-start_of_annotations + prepend_len
  638. * We already wrote prepend_len bytes into the buffer; now we're
  639. * writing end-start_of_annotations -NM. */
  640. tor_assert(signed_body+(end-start_of_annotations) ==
  641. router->cache_info.signed_descriptor_body+len);
  642. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  643. router->cache_info.signed_descriptor_body[len] = '\0';
  644. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  645. }
  646. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  647. router->nickname = tor_strdup(tok->args[0]);
  648. if (!is_legal_nickname(router->nickname)) {
  649. log_warn(LD_DIR,"Router nickname is invalid");
  650. goto err;
  651. }
  652. if (!tor_inet_aton(tok->args[1], &in)) {
  653. log_warn(LD_DIR,"Router address is not an IP address.");
  654. goto err;
  655. }
  656. router->addr = ntohl(in.s_addr);
  657. router->or_port =
  658. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  659. if (!ok) {
  660. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  661. goto err;
  662. }
  663. router->dir_port =
  664. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  665. if (!ok) {
  666. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  667. goto err;
  668. }
  669. tok = find_by_keyword(tokens, K_BANDWIDTH);
  670. tor_assert(tok->n_args >= 3);
  671. router->bandwidthrate = (int)
  672. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  673. if (!ok) {
  674. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  675. escaped(tok->args[0]));
  676. goto err;
  677. }
  678. router->bandwidthburst =
  679. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  680. if (!ok) {
  681. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  682. goto err;
  683. }
  684. router->bandwidthcapacity = (int)
  685. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  686. if (!ok) {
  687. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  688. goto err;
  689. }
  690. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  691. tor_assert(tok->n_args);
  692. router->purpose = router_purpose_from_string(tok->args[0]);
  693. } else {
  694. router->purpose = ROUTER_PURPOSE_GENERAL;
  695. }
  696. router->cache_info.send_unencrypted =
  697. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  698. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  699. tor_assert(tok->n_args >= 1);
  700. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  701. if (!ok) {
  702. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  703. goto err;
  704. }
  705. }
  706. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  707. tor_assert(tok->n_args >= 1);
  708. router->is_hibernating
  709. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  710. }
  711. tok = find_by_keyword(tokens, K_PUBLISHED);
  712. tor_assert(tok->n_args == 1);
  713. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  714. goto err;
  715. tok = find_by_keyword(tokens, K_ONION_KEY);
  716. if (!crypto_pk_public_exponent_ok(tok->key)) {
  717. log_warn(LD_DIR,
  718. "Relay's onion key had invalid exponent.");
  719. goto err;
  720. }
  721. router_set_rsa_onion_pkey(tok->key, &router->onion_pkey,
  722. &router->onion_pkey_len);
  723. crypto_pk_free(tok->key);
  724. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  725. curve25519_public_key_t k;
  726. tor_assert(tok->n_args >= 1);
  727. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  728. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  729. goto err;
  730. }
  731. router->onion_curve25519_pkey =
  732. tor_memdup(&k, sizeof(curve25519_public_key_t));
  733. }
  734. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  735. router->identity_pkey = tok->key;
  736. tok->key = NULL; /* Prevent free */
  737. if (crypto_pk_get_digest(router->identity_pkey,
  738. router->cache_info.identity_digest)) {
  739. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  740. }
  741. {
  742. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  743. *master_key_tok;
  744. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  745. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  746. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  747. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  748. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  749. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  750. !!cc_tap_tok + !!cc_ntor_tok;
  751. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  752. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  753. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  754. "cross-certification support");
  755. goto err;
  756. }
  757. if (master_key_tok && !ed_sig_tok) {
  758. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  759. "certificate");
  760. goto err;
  761. }
  762. if (ed_sig_tok) {
  763. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  764. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  765. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  766. (ed_cert_token_pos != router_token_pos + 1 &&
  767. ed_cert_token_pos != router_token_pos - 1)) {
  768. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  769. goto err;
  770. }
  771. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  772. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  773. goto err;
  774. }
  775. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  776. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  777. goto err;
  778. }
  779. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  780. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  781. "in decriptor");
  782. goto err;
  783. }
  784. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  785. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  786. "in decriptor");
  787. goto err;
  788. }
  789. if (strcmp(cc_ntor_tok->args[0], "0") &&
  790. strcmp(cc_ntor_tok->args[0], "1")) {
  791. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  792. goto err;
  793. }
  794. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  795. uint8_t d256[DIGEST256_LEN];
  796. const char *signed_start, *signed_end;
  797. tor_cert_t *cert = tor_cert_parse(
  798. (const uint8_t*)ed_cert_tok->object_body,
  799. ed_cert_tok->object_size);
  800. if (! cert) {
  801. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  802. goto err;
  803. }
  804. /* makes sure it gets freed. */
  805. router->cache_info.signing_key_cert = cert;
  806. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  807. ! cert->signing_key_included) {
  808. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  809. goto err;
  810. }
  811. if (master_key_tok) {
  812. /* This token is optional, but if it's present, it must match
  813. * the signature in the signing cert, or supplant it. */
  814. tor_assert(master_key_tok->n_args >= 1);
  815. ed25519_public_key_t pkey;
  816. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  817. log_warn(LD_DIR, "Can't parse ed25519 master key");
  818. goto err;
  819. }
  820. if (fast_memneq(&cert->signing_key.pubkey,
  821. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  822. log_warn(LD_DIR, "Ed25519 master key does not match "
  823. "key in certificate");
  824. goto err;
  825. }
  826. }
  827. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  828. cc_ntor_tok->object_size);
  829. if (!ntor_cc_cert) {
  830. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  831. goto err;
  832. }
  833. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  834. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  835. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  836. goto err;
  837. }
  838. ed25519_public_key_t ntor_cc_pk;
  839. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  840. router->onion_curve25519_pkey,
  841. ntor_cc_sign_bit)<0) {
  842. log_warn(LD_DIR, "Error converting onion key to ed25519");
  843. goto err;
  844. }
  845. if (router_get_hash_impl_helper(s, end-s, "router ",
  846. "\nrouter-sig-ed25519",
  847. ' ', LOG_WARN,
  848. &signed_start, &signed_end) < 0) {
  849. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  850. goto err;
  851. }
  852. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  853. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  854. strlen(ED_DESC_SIGNATURE_PREFIX));
  855. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  856. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  857. crypto_digest_free(d);
  858. ed25519_checkable_t check[3];
  859. int check_ok[3];
  860. time_t expires = TIME_MAX;
  861. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  862. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  863. goto err;
  864. }
  865. if (tor_cert_get_checkable_sig(&check[1],
  866. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  867. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  868. goto err;
  869. }
  870. if (ed25519_signature_from_base64(&check[2].signature,
  871. ed_sig_tok->args[0])<0) {
  872. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  873. goto err;
  874. }
  875. check[2].pubkey = &cert->signed_key;
  876. check[2].msg = d256;
  877. check[2].len = DIGEST256_LEN;
  878. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  879. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  880. goto err;
  881. }
  882. rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
  883. router->onion_pkey_len);
  884. if (check_tap_onion_key_crosscert(
  885. (const uint8_t*)cc_tap_tok->object_body,
  886. (int)cc_tap_tok->object_size,
  887. rsa_pubkey,
  888. &cert->signing_key,
  889. (const uint8_t*)router->cache_info.identity_digest)<0) {
  890. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  891. goto err;
  892. }
  893. /* We check this before adding it to the routerlist. */
  894. router->cert_expiration_time = expires;
  895. }
  896. }
  897. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  898. /* If there's a fingerprint line, it must match the identity digest. */
  899. char d[DIGEST_LEN];
  900. tor_assert(tok->n_args == 1);
  901. tor_strstrip(tok->args[0], " ");
  902. if (base16_decode(d, DIGEST_LEN,
  903. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  904. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  905. escaped(tok->args[0]));
  906. goto err;
  907. }
  908. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  909. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  910. tok->args[0]);
  911. goto err;
  912. }
  913. }
  914. {
  915. const char *version = NULL, *protocols = NULL;
  916. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  917. router->platform = tor_strdup(tok->args[0]);
  918. version = tok->args[0];
  919. }
  920. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  921. router->protocol_list = tor_strdup(tok->args[0]);
  922. protocols = tok->args[0];
  923. }
  924. summarize_protover_flags(&router->pv, protocols, version);
  925. }
  926. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  927. router->contact_info = tor_strdup(tok->args[0]);
  928. }
  929. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  930. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  931. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  932. "older Tors.");
  933. goto err;
  934. }
  935. {
  936. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  937. if (or_addresses) {
  938. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  939. &router->ipv6_orport);
  940. smartlist_free(or_addresses);
  941. }
  942. }
  943. exit_policy_tokens = find_all_exitpolicy(tokens);
  944. if (!smartlist_len(exit_policy_tokens)) {
  945. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  946. goto err;
  947. }
  948. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  949. if (router_add_exit_policy(router,t)<0) {
  950. log_warn(LD_DIR,"Error in exit policy");
  951. goto err;
  952. });
  953. policy_expand_private(&router->exit_policy);
  954. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  955. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  956. if (! router->ipv6_exit_policy) {
  957. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  958. goto err;
  959. }
  960. }
  961. if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
  962. (!router->ipv6_exit_policy ||
  963. short_policy_is_reject_star(router->ipv6_exit_policy)))
  964. router->policy_is_reject_star = 1;
  965. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  966. int i;
  967. router->declared_family = smartlist_new();
  968. for (i=0;i<tok->n_args;++i) {
  969. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  970. log_warn(LD_DIR, "Illegal nickname %s in family line",
  971. escaped(tok->args[i]));
  972. goto err;
  973. }
  974. smartlist_add_strdup(router->declared_family, tok->args[i]);
  975. }
  976. }
  977. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  978. router->caches_extra_info = 1;
  979. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  980. router->allow_single_hop_exits = 1;
  981. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  982. tor_assert(tok->n_args >= 1);
  983. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  984. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  985. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  986. log_warn(LD_DIR,"Invalid extra info digest");
  987. }
  988. } else {
  989. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  990. }
  991. if (tok->n_args >= 2) {
  992. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  993. tok->args[1]) < 0) {
  994. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  995. escaped(tok->args[1]));
  996. }
  997. }
  998. }
  999. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1000. router->wants_to_be_hs_dir = 1;
  1001. }
  1002. /* This router accepts tunnelled directory requests via begindir if it has
  1003. * an open dirport or it included "tunnelled-dir-server". */
  1004. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1005. router->supports_tunnelled_dir_requests = 1;
  1006. }
  1007. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1008. if (!router->or_port) {
  1009. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1010. goto err;
  1011. }
  1012. /* We've checked everything that's covered by the hash. */
  1013. can_dl_again = 1;
  1014. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1015. "router descriptor") < 0)
  1016. goto err;
  1017. if (!router->platform) {
  1018. router->platform = tor_strdup("<unknown>");
  1019. }
  1020. goto done;
  1021. err:
  1022. dump_desc(s_dup, "router descriptor");
  1023. routerinfo_free(router);
  1024. router = NULL;
  1025. done:
  1026. crypto_pk_free(rsa_pubkey);
  1027. tor_cert_free(ntor_cc_cert);
  1028. if (tokens) {
  1029. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1030. smartlist_free(tokens);
  1031. }
  1032. smartlist_free(exit_policy_tokens);
  1033. if (area) {
  1034. DUMP_AREA(area, "routerinfo");
  1035. memarea_drop_all(area);
  1036. }
  1037. if (can_dl_again_out)
  1038. *can_dl_again_out = can_dl_again;
  1039. return router;
  1040. }
  1041. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1042. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1043. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1044. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1045. * as a map from router identity to routerinfo_t when looking up signing keys.
  1046. *
  1047. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1048. * if it's okay to try to download an extrainfo with this same digest again,
  1049. * and 0 if it isn't. (It might not be okay to download it again if part of
  1050. * the part covered by the digest is invalid.)
  1051. */
  1052. extrainfo_t *
  1053. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1054. int cache_copy, struct digest_ri_map_t *routermap,
  1055. int *can_dl_again_out)
  1056. {
  1057. extrainfo_t *extrainfo = NULL;
  1058. char digest[128];
  1059. smartlist_t *tokens = NULL;
  1060. directory_token_t *tok;
  1061. crypto_pk_t *key = NULL;
  1062. routerinfo_t *router = NULL;
  1063. memarea_t *area = NULL;
  1064. const char *s_dup = s;
  1065. /* Do not set this to '1' until we have parsed everything that we intend to
  1066. * parse that's covered by the hash. */
  1067. int can_dl_again = 0;
  1068. if (BUG(s == NULL))
  1069. return NULL;
  1070. if (!end) {
  1071. end = s + strlen(s);
  1072. }
  1073. /* point 'end' to a point immediately after the final newline. */
  1074. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1075. --end;
  1076. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1077. log_warn(LD_DIR, "Couldn't compute router hash.");
  1078. goto err;
  1079. }
  1080. tokens = smartlist_new();
  1081. area = memarea_new();
  1082. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1083. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1084. goto err;
  1085. }
  1086. if (smartlist_len(tokens) < 2) {
  1087. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1088. goto err;
  1089. }
  1090. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  1091. tok = smartlist_get(tokens,0);
  1092. if (tok->tp != K_EXTRA_INFO) {
  1093. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1094. goto err;
  1095. }
  1096. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1097. extrainfo->cache_info.is_extrainfo = 1;
  1098. if (cache_copy)
  1099. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  1100. extrainfo->cache_info.signed_descriptor_len = end-s;
  1101. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1102. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  1103. tor_assert(tok->n_args >= 2);
  1104. if (!is_legal_nickname(tok->args[0])) {
  1105. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1106. goto err;
  1107. }
  1108. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1109. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1110. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1111. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1112. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1113. escaped(tok->args[1]));
  1114. goto err;
  1115. }
  1116. tok = find_by_keyword(tokens, K_PUBLISHED);
  1117. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1118. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1119. escaped(tok->args[0]));
  1120. goto err;
  1121. }
  1122. {
  1123. directory_token_t *ed_sig_tok, *ed_cert_tok;
  1124. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1125. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1126. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  1127. if (n_ed_toks != 0 && n_ed_toks != 2) {
  1128. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1129. "cross-certification support");
  1130. goto err;
  1131. }
  1132. if (ed_sig_tok) {
  1133. tor_assert(ed_cert_tok);
  1134. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1135. if (ed_cert_token_pos != 1) {
  1136. /* Accept this in position 0 XXXX */
  1137. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1138. goto err;
  1139. }
  1140. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1141. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1142. goto err;
  1143. }
  1144. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1145. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1146. goto err;
  1147. }
  1148. uint8_t d256[DIGEST256_LEN];
  1149. const char *signed_start, *signed_end;
  1150. tor_cert_t *cert = tor_cert_parse(
  1151. (const uint8_t*)ed_cert_tok->object_body,
  1152. ed_cert_tok->object_size);
  1153. if (! cert) {
  1154. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1155. goto err;
  1156. }
  1157. /* makes sure it gets freed. */
  1158. extrainfo->cache_info.signing_key_cert = cert;
  1159. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1160. ! cert->signing_key_included) {
  1161. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1162. goto err;
  1163. }
  1164. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1165. "\nrouter-sig-ed25519",
  1166. ' ', LOG_WARN,
  1167. &signed_start, &signed_end) < 0) {
  1168. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1169. goto err;
  1170. }
  1171. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1172. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1173. strlen(ED_DESC_SIGNATURE_PREFIX));
  1174. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1175. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1176. crypto_digest_free(d);
  1177. ed25519_checkable_t check[2];
  1178. int check_ok[2];
  1179. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  1180. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1181. goto err;
  1182. }
  1183. if (ed25519_signature_from_base64(&check[1].signature,
  1184. ed_sig_tok->args[0])<0) {
  1185. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1186. goto err;
  1187. }
  1188. check[1].pubkey = &cert->signed_key;
  1189. check[1].msg = d256;
  1190. check[1].len = DIGEST256_LEN;
  1191. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1192. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1193. goto err;
  1194. }
  1195. /* We don't check the certificate expiration time: checking that it
  1196. * matches the cert in the router descriptor is adequate. */
  1197. }
  1198. }
  1199. /* We've checked everything that's covered by the hash. */
  1200. can_dl_again = 1;
  1201. if (routermap &&
  1202. (router = digestmap_get((digestmap_t*)routermap,
  1203. extrainfo->cache_info.identity_digest))) {
  1204. key = router->identity_pkey;
  1205. }
  1206. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1207. if (strcmp(tok->object_type, "SIGNATURE") ||
  1208. tok->object_size < 128 || tok->object_size > 512) {
  1209. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1210. goto err;
  1211. }
  1212. if (key) {
  1213. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1214. "extra-info") < 0)
  1215. goto err;
  1216. if (router)
  1217. extrainfo->cache_info.send_unencrypted =
  1218. router->cache_info.send_unencrypted;
  1219. } else {
  1220. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1221. tok->object_size);
  1222. extrainfo->pending_sig_len = tok->object_size;
  1223. }
  1224. goto done;
  1225. err:
  1226. dump_desc(s_dup, "extra-info descriptor");
  1227. extrainfo_free(extrainfo);
  1228. extrainfo = NULL;
  1229. done:
  1230. if (tokens) {
  1231. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1232. smartlist_free(tokens);
  1233. }
  1234. if (area) {
  1235. DUMP_AREA(area, "extrainfo");
  1236. memarea_drop_all(area);
  1237. }
  1238. if (can_dl_again_out)
  1239. *can_dl_again_out = can_dl_again;
  1240. return extrainfo;
  1241. }
  1242. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1243. * object (starting with "r " at the start of a line). If none is found,
  1244. * return the start of the directory footer, or the next directory signature.
  1245. * If none is found, return the end of the string. */
  1246. static inline const char *
  1247. find_start_of_next_routerstatus(const char *s)
  1248. {
  1249. const char *eos, *footer, *sig;
  1250. if ((eos = strstr(s, "\nr ")))
  1251. ++eos;
  1252. else
  1253. eos = s + strlen(s);
  1254. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  1255. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  1256. if (footer && sig)
  1257. return MIN(footer, sig) + 1;
  1258. else if (footer)
  1259. return footer+1;
  1260. else if (sig)
  1261. return sig+1;
  1262. else
  1263. return eos;
  1264. }
  1265. /** Parse the GuardFraction string from a consensus or vote.
  1266. *
  1267. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  1268. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  1269. * the same semantic as in routerstatus_parse_entry_from_string(). */
  1270. STATIC int
  1271. routerstatus_parse_guardfraction(const char *guardfraction_str,
  1272. networkstatus_t *vote,
  1273. vote_routerstatus_t *vote_rs,
  1274. routerstatus_t *rs)
  1275. {
  1276. int ok;
  1277. const char *end_of_header = NULL;
  1278. int is_consensus = !vote_rs;
  1279. uint32_t guardfraction;
  1280. tor_assert(bool_eq(vote, vote_rs));
  1281. /* If this info comes from a consensus, but we should't apply
  1282. guardfraction, just exit. */
  1283. if (is_consensus && !should_apply_guardfraction(NULL)) {
  1284. return 0;
  1285. }
  1286. end_of_header = strchr(guardfraction_str, '=');
  1287. if (!end_of_header) {
  1288. return -1;
  1289. }
  1290. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  1291. 10, 0, 100, &ok, NULL);
  1292. if (!ok) {
  1293. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  1294. return -1;
  1295. }
  1296. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  1297. is_consensus ? "consensus" : "vote",
  1298. guardfraction_str, rs->nickname);
  1299. if (!is_consensus) { /* We are parsing a vote */
  1300. vote_rs->status.guardfraction_percentage = guardfraction;
  1301. vote_rs->status.has_guardfraction = 1;
  1302. } else {
  1303. /* We are parsing a consensus. Only apply guardfraction to guards. */
  1304. if (rs->is_possible_guard) {
  1305. rs->guardfraction_percentage = guardfraction;
  1306. rs->has_guardfraction = 1;
  1307. } else {
  1308. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  1309. "This is not supposed to happen. Not applying. ", rs->nickname);
  1310. }
  1311. }
  1312. return 0;
  1313. }
  1314. /** Summarize the protocols listed in <b>protocols</b> into <b>out</b>,
  1315. * falling back or correcting them based on <b>version</b> as appropriate.
  1316. */
  1317. STATIC void
  1318. summarize_protover_flags(protover_summary_flags_t *out,
  1319. const char *protocols,
  1320. const char *version)
  1321. {
  1322. tor_assert(out);
  1323. memset(out, 0, sizeof(*out));
  1324. if (protocols) {
  1325. out->protocols_known = 1;
  1326. out->supports_extend2_cells =
  1327. protocol_list_supports_protocol(protocols, PRT_RELAY, 2);
  1328. out->supports_ed25519_link_handshake_compat =
  1329. protocol_list_supports_protocol(protocols, PRT_LINKAUTH, 3);
  1330. out->supports_ed25519_link_handshake_any =
  1331. protocol_list_supports_protocol_or_later(protocols, PRT_LINKAUTH, 3);
  1332. out->supports_ed25519_hs_intro =
  1333. protocol_list_supports_protocol(protocols, PRT_HSINTRO, 4);
  1334. out->supports_v3_hsdir =
  1335. protocol_list_supports_protocol(protocols, PRT_HSDIR,
  1336. PROTOVER_HSDIR_V3);
  1337. out->supports_v3_rendezvous_point =
  1338. protocol_list_supports_protocol(protocols, PRT_HSREND,
  1339. PROTOVER_HS_RENDEZVOUS_POINT_V3);
  1340. }
  1341. if (version && !strcmpstart(version, "Tor ")) {
  1342. if (!out->protocols_known) {
  1343. /* The version is a "Tor" version, and where there is no
  1344. * list of protocol versions that we should be looking at instead. */
  1345. out->supports_extend2_cells =
  1346. tor_version_as_new_as(version, "0.2.4.8-alpha");
  1347. out->protocols_known = 1;
  1348. } else {
  1349. /* Bug #22447 forces us to filter on this version. */
  1350. if (!tor_version_as_new_as(version, "0.3.0.8")) {
  1351. out->supports_v3_hsdir = 0;
  1352. }
  1353. }
  1354. }
  1355. }
  1356. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1357. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1358. * object in the string, and advance *<b>s</b> to just after the end of the
  1359. * router status. Return NULL and advance *<b>s</b> on error.
  1360. *
  1361. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1362. * routerstatus but use <b>vote_rs</b> instead.
  1363. *
  1364. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1365. * consensus, and we should parse it according to the method used to
  1366. * make that consensus.
  1367. *
  1368. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  1369. **/
  1370. STATIC routerstatus_t *
  1371. routerstatus_parse_entry_from_string(memarea_t *area,
  1372. const char **s, smartlist_t *tokens,
  1373. networkstatus_t *vote,
  1374. vote_routerstatus_t *vote_rs,
  1375. int consensus_method,
  1376. consensus_flavor_t flav)
  1377. {
  1378. const char *eos, *s_dup = *s;
  1379. routerstatus_t *rs = NULL;
  1380. directory_token_t *tok;
  1381. char timebuf[ISO_TIME_LEN+1];
  1382. struct in_addr in;
  1383. int offset = 0;
  1384. tor_assert(tokens);
  1385. tor_assert(bool_eq(vote, vote_rs));
  1386. if (!consensus_method)
  1387. flav = FLAV_NS;
  1388. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  1389. eos = find_start_of_next_routerstatus(*s);
  1390. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1391. log_warn(LD_DIR, "Error tokenizing router status");
  1392. goto err;
  1393. }
  1394. if (smartlist_len(tokens) < 1) {
  1395. log_warn(LD_DIR, "Impossibly short router status");
  1396. goto err;
  1397. }
  1398. tok = find_by_keyword(tokens, K_R);
  1399. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  1400. if (flav == FLAV_NS) {
  1401. if (tok->n_args < 8) {
  1402. log_warn(LD_DIR, "Too few arguments to r");
  1403. goto err;
  1404. }
  1405. } else if (flav == FLAV_MICRODESC) {
  1406. offset = -1; /* There is no descriptor digest in an md consensus r line */
  1407. }
  1408. if (vote_rs) {
  1409. rs = &vote_rs->status;
  1410. } else {
  1411. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1412. }
  1413. if (!is_legal_nickname(tok->args[0])) {
  1414. log_warn(LD_DIR,
  1415. "Invalid nickname %s in router status; skipping.",
  1416. escaped(tok->args[0]));
  1417. goto err;
  1418. }
  1419. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1420. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1421. log_warn(LD_DIR, "Error decoding identity digest %s",
  1422. escaped(tok->args[1]));
  1423. goto err;
  1424. }
  1425. if (flav == FLAV_NS) {
  1426. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1427. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1428. escaped(tok->args[2]));
  1429. goto err;
  1430. }
  1431. }
  1432. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1433. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  1434. parse_iso_time(timebuf, &rs->published_on)<0) {
  1435. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  1436. tok->args[3+offset], tok->args[4+offset],
  1437. offset, (int)flav);
  1438. goto err;
  1439. }
  1440. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  1441. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1442. escaped(tok->args[5+offset]));
  1443. goto err;
  1444. }
  1445. rs->addr = ntohl(in.s_addr);
  1446. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  1447. 10,0,65535,NULL,NULL);
  1448. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  1449. 10,0,65535,NULL,NULL);
  1450. {
  1451. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  1452. if (a_lines) {
  1453. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  1454. smartlist_free(a_lines);
  1455. }
  1456. }
  1457. tok = find_opt_by_keyword(tokens, K_S);
  1458. if (tok && vote) {
  1459. int i;
  1460. vote_rs->flags = 0;
  1461. for (i=0; i < tok->n_args; ++i) {
  1462. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1463. if (p >= 0) {
  1464. vote_rs->flags |= (UINT64_C(1)<<p);
  1465. } else {
  1466. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1467. escaped(tok->args[i]));
  1468. goto err;
  1469. }
  1470. }
  1471. } else if (tok) {
  1472. /* This is a consensus, not a vote. */
  1473. int i;
  1474. for (i=0; i < tok->n_args; ++i) {
  1475. if (!strcmp(tok->args[i], "Exit"))
  1476. rs->is_exit = 1;
  1477. else if (!strcmp(tok->args[i], "Stable"))
  1478. rs->is_stable = 1;
  1479. else if (!strcmp(tok->args[i], "Fast"))
  1480. rs->is_fast = 1;
  1481. else if (!strcmp(tok->args[i], "Running"))
  1482. rs->is_flagged_running = 1;
  1483. else if (!strcmp(tok->args[i], "Named"))
  1484. rs->is_named = 1;
  1485. else if (!strcmp(tok->args[i], "Valid"))
  1486. rs->is_valid = 1;
  1487. else if (!strcmp(tok->args[i], "Guard"))
  1488. rs->is_possible_guard = 1;
  1489. else if (!strcmp(tok->args[i], "BadExit"))
  1490. rs->is_bad_exit = 1;
  1491. else if (!strcmp(tok->args[i], "Authority"))
  1492. rs->is_authority = 1;
  1493. else if (!strcmp(tok->args[i], "Unnamed") &&
  1494. consensus_method >= 2) {
  1495. /* Unnamed is computed right by consensus method 2 and later. */
  1496. rs->is_unnamed = 1;
  1497. } else if (!strcmp(tok->args[i], "HSDir")) {
  1498. rs->is_hs_dir = 1;
  1499. } else if (!strcmp(tok->args[i], "V2Dir")) {
  1500. rs->is_v2_dir = 1;
  1501. }
  1502. }
  1503. /* These are implied true by having been included in a consensus made
  1504. * with a given method */
  1505. rs->is_flagged_running = 1; /* Starting with consensus method 4. */
  1506. rs->is_valid = 1; /* Starting with consensus method 24. */
  1507. }
  1508. {
  1509. const char *protocols = NULL, *version = NULL;
  1510. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  1511. tor_assert(tok->n_args == 1);
  1512. protocols = tok->args[0];
  1513. }
  1514. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1515. tor_assert(tok->n_args == 1);
  1516. version = tok->args[0];
  1517. if (vote_rs) {
  1518. vote_rs->version = tor_strdup(tok->args[0]);
  1519. }
  1520. }
  1521. summarize_protover_flags(&rs->pv, protocols, version);
  1522. }
  1523. /* handle weighting/bandwidth info */
  1524. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1525. int i;
  1526. for (i=0; i < tok->n_args; ++i) {
  1527. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1528. int ok;
  1529. rs->bandwidth_kb =
  1530. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1531. 10, 0, UINT32_MAX,
  1532. &ok, NULL);
  1533. if (!ok) {
  1534. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1535. goto err;
  1536. }
  1537. rs->has_bandwidth = 1;
  1538. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  1539. int ok;
  1540. vote_rs->measured_bw_kb =
  1541. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1542. 10, 0, UINT32_MAX, &ok, NULL);
  1543. if (!ok) {
  1544. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  1545. escaped(tok->args[i]));
  1546. goto err;
  1547. }
  1548. vote_rs->has_measured_bw = 1;
  1549. vote->has_measured_bws = 1;
  1550. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  1551. rs->bw_is_unmeasured = 1;
  1552. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  1553. if (routerstatus_parse_guardfraction(tok->args[i],
  1554. vote, vote_rs, rs) < 0) {
  1555. goto err;
  1556. }
  1557. }
  1558. }
  1559. }
  1560. /* parse exit policy summaries */
  1561. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1562. tor_assert(tok->n_args == 1);
  1563. if (strcmpstart(tok->args[0], "accept ") &&
  1564. strcmpstart(tok->args[0], "reject ")) {
  1565. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1566. escaped(tok->args[0]));
  1567. goto err;
  1568. }
  1569. /* XXX weasel: parse this into ports and represent them somehow smart,
  1570. * maybe not here but somewhere on if we need it for the client.
  1571. * we should still parse it here to check it's valid tho.
  1572. */
  1573. rs->exitsummary = tor_strdup(tok->args[0]);
  1574. rs->has_exitsummary = 1;
  1575. }
  1576. if (vote_rs) {
  1577. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  1578. if (t->tp == K_M && t->n_args) {
  1579. vote_microdesc_hash_t *line =
  1580. tor_malloc(sizeof(vote_microdesc_hash_t));
  1581. line->next = vote_rs->microdesc;
  1582. line->microdesc_hash_line = tor_strdup(t->args[0]);
  1583. vote_rs->microdesc = line;
  1584. }
  1585. if (t->tp == K_ID) {
  1586. tor_assert(t->n_args >= 2);
  1587. if (!strcmp(t->args[0], "ed25519")) {
  1588. vote_rs->has_ed25519_listing = 1;
  1589. if (strcmp(t->args[1], "none") &&
  1590. digest256_from_base64((char*)vote_rs->ed25519_id,
  1591. t->args[1])<0) {
  1592. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  1593. goto err;
  1594. }
  1595. }
  1596. }
  1597. if (t->tp == K_PROTO) {
  1598. tor_assert(t->n_args == 1);
  1599. vote_rs->protocols = tor_strdup(t->args[0]);
  1600. }
  1601. } SMARTLIST_FOREACH_END(t);
  1602. } else if (flav == FLAV_MICRODESC) {
  1603. tok = find_opt_by_keyword(tokens, K_M);
  1604. if (tok) {
  1605. tor_assert(tok->n_args);
  1606. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  1607. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  1608. escaped(tok->args[0]));
  1609. goto err;
  1610. }
  1611. } else {
  1612. log_info(LD_BUG, "Found an entry in networkstatus with no "
  1613. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  1614. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  1615. fmt_addr32(rs->addr), rs->or_port);
  1616. }
  1617. }
  1618. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1619. rs->is_named = 0;
  1620. goto done;
  1621. err:
  1622. dump_desc(s_dup, "routerstatus entry");
  1623. if (rs && !vote_rs)
  1624. routerstatus_free(rs);
  1625. rs = NULL;
  1626. done:
  1627. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1628. smartlist_clear(tokens);
  1629. if (area) {
  1630. DUMP_AREA(area, "routerstatus entry");
  1631. memarea_clear(area);
  1632. }
  1633. *s = eos;
  1634. return rs;
  1635. }
  1636. int
  1637. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  1638. {
  1639. const vote_routerstatus_t *a = *_a, *b = *_b;
  1640. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  1641. DIGEST_LEN);
  1642. }
  1643. /** Verify the bandwidth weights of a network status document */
  1644. int
  1645. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  1646. {
  1647. int64_t G=0, M=0, E=0, D=0, T=0;
  1648. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  1649. double Gtotal=0, Mtotal=0, Etotal=0;
  1650. const char *casename = NULL;
  1651. int valid = 1;
  1652. (void) consensus_method;
  1653. const int64_t weight_scale = networkstatus_get_weight_scale_param(ns);
  1654. tor_assert(weight_scale >= 1);
  1655. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  1656. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  1657. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  1658. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  1659. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  1660. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  1661. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  1662. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  1663. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  1664. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  1665. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  1666. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  1667. || Wem<0 || Wee<0 || Wed<0) {
  1668. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  1669. return 0;
  1670. }
  1671. // First, sanity check basic summing properties that hold for all cases
  1672. // We use > 1 as the check for these because they are computed as integers.
  1673. // Sometimes there are rounding errors.
  1674. if (fabs(Wmm - weight_scale) > 1) {
  1675. log_warn(LD_BUG, "Wmm=%f != %"PRId64,
  1676. Wmm, (weight_scale));
  1677. valid = 0;
  1678. }
  1679. if (fabs(Wem - Wee) > 1) {
  1680. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  1681. valid = 0;
  1682. }
  1683. if (fabs(Wgm - Wgg) > 1) {
  1684. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  1685. valid = 0;
  1686. }
  1687. if (fabs(Weg - Wed) > 1) {
  1688. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  1689. valid = 0;
  1690. }
  1691. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  1692. log_warn(LD_BUG, "Wgg=%f != %"PRId64" - Wmg=%f", Wgg,
  1693. (weight_scale), Wmg);
  1694. valid = 0;
  1695. }
  1696. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  1697. log_warn(LD_BUG, "Wee=%f != %"PRId64" - Wme=%f", Wee,
  1698. (weight_scale), Wme);
  1699. valid = 0;
  1700. }
  1701. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  1702. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != %"PRId64,
  1703. Wgd, Wmd, Wed, (weight_scale));
  1704. valid = 0;
  1705. }
  1706. Wgg /= weight_scale;
  1707. Wgm /= weight_scale; (void) Wgm; // unused from here on.
  1708. Wgd /= weight_scale;
  1709. Wmg /= weight_scale;
  1710. Wmm /= weight_scale;
  1711. Wme /= weight_scale;
  1712. Wmd /= weight_scale;
  1713. Weg /= weight_scale; (void) Weg; // unused from here on.
  1714. Wem /= weight_scale; (void) Wem; // unused from here on.
  1715. Wee /= weight_scale;
  1716. Wed /= weight_scale;
  1717. // Then, gather G, M, E, D, T to determine case
  1718. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  1719. int is_exit = 0;
  1720. /* Bug #2203: Don't count bad exits as exits for balancing */
  1721. is_exit = rs->is_exit && !rs->is_bad_exit;
  1722. if (rs->has_bandwidth) {
  1723. T += rs->bandwidth_kb;
  1724. if (is_exit && rs->is_possible_guard) {
  1725. D += rs->bandwidth_kb;
  1726. Gtotal += Wgd*rs->bandwidth_kb;
  1727. Mtotal += Wmd*rs->bandwidth_kb;
  1728. Etotal += Wed*rs->bandwidth_kb;
  1729. } else if (is_exit) {
  1730. E += rs->bandwidth_kb;
  1731. Mtotal += Wme*rs->bandwidth_kb;
  1732. Etotal += Wee*rs->bandwidth_kb;
  1733. } else if (rs->is_possible_guard) {
  1734. G += rs->bandwidth_kb;
  1735. Gtotal += Wgg*rs->bandwidth_kb;
  1736. Mtotal += Wmg*rs->bandwidth_kb;
  1737. } else {
  1738. M += rs->bandwidth_kb;
  1739. Mtotal += Wmm*rs->bandwidth_kb;
  1740. }
  1741. } else {
  1742. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  1743. routerstatus_describe(rs));
  1744. }
  1745. } SMARTLIST_FOREACH_END(rs);
  1746. // Finally, check equality conditions depending upon case 1, 2 or 3
  1747. // Full equality cases: 1, 3b
  1748. // Partial equality cases: 2b (E=G), 3a (M=E)
  1749. // Fully unknown: 2a
  1750. if (3*E >= T && 3*G >= T) {
  1751. // Case 1: Neither are scarce
  1752. casename = "Case 1";
  1753. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  1754. log_warn(LD_DIR,
  1755. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  1756. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1757. " T=%"PRId64". "
  1758. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1759. casename, Etotal, Mtotal,
  1760. (G), (M), (E),
  1761. (D), (T),
  1762. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1763. valid = 0;
  1764. }
  1765. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1766. log_warn(LD_DIR,
  1767. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1768. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1769. " T=%"PRId64". "
  1770. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1771. casename, Etotal, Gtotal,
  1772. (G), (M), (E),
  1773. (D), (T),
  1774. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1775. valid = 0;
  1776. }
  1777. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  1778. log_warn(LD_DIR,
  1779. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  1780. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1781. " T=%"PRId64". "
  1782. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1783. casename, Mtotal, Gtotal,
  1784. (G), (M), (E),
  1785. (D), (T),
  1786. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1787. valid = 0;
  1788. }
  1789. } else if (3*E < T && 3*G < T) {
  1790. int64_t R = MIN(E, G);
  1791. int64_t S = MAX(E, G);
  1792. /*
  1793. * Case 2: Both Guards and Exits are scarce
  1794. * Balance D between E and G, depending upon
  1795. * D capacity and scarcity. Devote no extra
  1796. * bandwidth to middle nodes.
  1797. */
  1798. if (R+D < S) { // Subcase a
  1799. double Rtotal, Stotal;
  1800. if (E < G) {
  1801. Rtotal = Etotal;
  1802. Stotal = Gtotal;
  1803. } else {
  1804. Rtotal = Gtotal;
  1805. Stotal = Etotal;
  1806. }
  1807. casename = "Case 2a";
  1808. // Rtotal < Stotal
  1809. if (Rtotal > Stotal) {
  1810. log_warn(LD_DIR,
  1811. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  1812. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1813. " T=%"PRId64". "
  1814. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1815. casename, Rtotal, Stotal,
  1816. (G), (M), (E),
  1817. (D), (T),
  1818. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1819. valid = 0;
  1820. }
  1821. // Rtotal < T/3
  1822. if (3*Rtotal > T) {
  1823. log_warn(LD_DIR,
  1824. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  1825. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  1826. " D=%"PRId64" T=%"PRId64". "
  1827. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1828. casename, Rtotal*3, (T),
  1829. (G), (M), (E),
  1830. (D), (T),
  1831. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1832. valid = 0;
  1833. }
  1834. // Stotal < T/3
  1835. if (3*Stotal > T) {
  1836. log_warn(LD_DIR,
  1837. "Bw Weight Failure for %s: 3*Stotal %f > T "
  1838. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  1839. " D=%"PRId64" T=%"PRId64". "
  1840. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1841. casename, Stotal*3, (T),
  1842. (G), (M), (E),
  1843. (D), (T),
  1844. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1845. valid = 0;
  1846. }
  1847. // Mtotal > T/3
  1848. if (3*Mtotal < T) {
  1849. log_warn(LD_DIR,
  1850. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  1851. "%"PRId64". "
  1852. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1853. " T=%"PRId64". "
  1854. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1855. casename, Mtotal*3, (T),
  1856. (G), (M), (E),
  1857. (D), (T),
  1858. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1859. valid = 0;
  1860. }
  1861. } else { // Subcase b: R+D > S
  1862. casename = "Case 2b";
  1863. /* Check the rare-M redirect case. */
  1864. if (D != 0 && 3*M < T) {
  1865. casename = "Case 2b (balanced)";
  1866. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  1867. log_warn(LD_DIR,
  1868. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  1869. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1870. " T=%"PRId64". "
  1871. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1872. casename, Etotal, Mtotal,
  1873. (G), (M), (E),
  1874. (D), (T),
  1875. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1876. valid = 0;
  1877. }
  1878. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1879. log_warn(LD_DIR,
  1880. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1881. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1882. " T=%"PRId64". "
  1883. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1884. casename, Etotal, Gtotal,
  1885. (G), (M), (E),
  1886. (D), (T),
  1887. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1888. valid = 0;
  1889. }
  1890. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  1891. log_warn(LD_DIR,
  1892. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  1893. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1894. " T=%"PRId64". "
  1895. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1896. casename, Mtotal, Gtotal,
  1897. (G), (M), (E),
  1898. (D), (T),
  1899. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1900. valid = 0;
  1901. }
  1902. } else {
  1903. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1904. log_warn(LD_DIR,
  1905. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1906. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1907. " T=%"PRId64". "
  1908. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1909. casename, Etotal, Gtotal,
  1910. (G), (M), (E),
  1911. (D), (T),
  1912. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1913. valid = 0;
  1914. }
  1915. }
  1916. }
  1917. } else { // if (E < T/3 || G < T/3) {
  1918. int64_t S = MIN(E, G);
  1919. int64_t NS = MAX(E, G);
  1920. if (3*(S+D) < T) { // Subcase a:
  1921. double Stotal;
  1922. double NStotal;
  1923. if (G < E) {
  1924. casename = "Case 3a (G scarce)";
  1925. Stotal = Gtotal;
  1926. NStotal = Etotal;
  1927. } else { // if (G >= E) {
  1928. casename = "Case 3a (E scarce)";
  1929. NStotal = Gtotal;
  1930. Stotal = Etotal;
  1931. }
  1932. // Stotal < T/3
  1933. if (3*Stotal > T) {
  1934. log_warn(LD_DIR,
  1935. "Bw Weight Failure for %s: 3*Stotal %f > T "
  1936. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  1937. " D=%"PRId64" T=%"PRId64". "
  1938. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1939. casename, Stotal*3, (T),
  1940. (G), (M), (E),
  1941. (D), (T),
  1942. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1943. valid = 0;
  1944. }
  1945. if (NS >= M) {
  1946. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  1947. log_warn(LD_DIR,
  1948. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  1949. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1950. " T=%"PRId64". "
  1951. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1952. casename, NStotal, Mtotal,
  1953. (G), (M), (E),
  1954. (D), (T),
  1955. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1956. valid = 0;
  1957. }
  1958. } else {
  1959. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  1960. if (3*NStotal < T) {
  1961. log_warn(LD_DIR,
  1962. "Bw Weight Failure for %s: 3*NStotal %f < T "
  1963. "%"PRId64". G=%"PRId64" M=%"PRId64
  1964. " E=%"PRId64" D=%"PRId64" T=%"PRId64". "
  1965. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1966. casename, NStotal*3, (T),
  1967. (G), (M), (E),
  1968. (D), (T),
  1969. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1970. valid = 0;
  1971. }
  1972. }
  1973. } else { // Subcase b: S+D >= T/3
  1974. casename = "Case 3b";
  1975. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  1976. log_warn(LD_DIR,
  1977. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  1978. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1979. " T=%"PRId64". "
  1980. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1981. casename, Etotal, Mtotal,
  1982. (G), (M), (E),
  1983. (D), (T),
  1984. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1985. valid = 0;
  1986. }
  1987. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1988. log_warn(LD_DIR,
  1989. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1990. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1991. " T=%"PRId64". "
  1992. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1993. casename, Etotal, Gtotal,
  1994. (G), (M), (E),
  1995. (D), (T),
  1996. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1997. valid = 0;
  1998. }
  1999. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2000. log_warn(LD_DIR,
  2001. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2002. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  2003. " T=%"PRId64". "
  2004. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2005. casename, Mtotal, Gtotal,
  2006. (G), (M), (E),
  2007. (D), (T),
  2008. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2009. valid = 0;
  2010. }
  2011. }
  2012. }
  2013. if (valid)
  2014. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2015. casename);
  2016. return valid;
  2017. }
  2018. /** Check if a shared random value of type <b>srv_type</b> is in
  2019. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  2020. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  2021. * it's the responsibility of the caller to free it. */
  2022. static int
  2023. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  2024. sr_srv_t **srv_out)
  2025. {
  2026. int ret = -1;
  2027. directory_token_t *tok;
  2028. sr_srv_t *srv = NULL;
  2029. smartlist_t *chunks;
  2030. tor_assert(tokens);
  2031. chunks = smartlist_new();
  2032. tok = find_opt_by_keyword(tokens, srv_type);
  2033. if (!tok) {
  2034. /* That's fine, no SRV is allowed. */
  2035. ret = 0;
  2036. goto end;
  2037. }
  2038. for (int i = 0; i < tok->n_args; i++) {
  2039. smartlist_add(chunks, tok->args[i]);
  2040. }
  2041. srv = sr_parse_srv(chunks);
  2042. if (srv == NULL) {
  2043. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  2044. goto end;
  2045. }
  2046. /* All is good. */
  2047. *srv_out = srv;
  2048. ret = 0;
  2049. end:
  2050. smartlist_free(chunks);
  2051. return ret;
  2052. }
  2053. /** Extract any shared random values found in <b>tokens</b> and place them in
  2054. * the networkstatus <b>ns</b>. */
  2055. static void
  2056. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  2057. {
  2058. const char *voter_identity;
  2059. networkstatus_voter_info_t *voter;
  2060. tor_assert(ns);
  2061. tor_assert(tokens);
  2062. /* Can be only one of them else code flow. */
  2063. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  2064. if (ns->type == NS_TYPE_VOTE) {
  2065. voter = smartlist_get(ns->voters, 0);
  2066. tor_assert(voter);
  2067. voter_identity = hex_str(voter->identity_digest,
  2068. sizeof(voter->identity_digest));
  2069. } else {
  2070. /* Consensus has multiple voters so no specific voter. */
  2071. voter_identity = "consensus";
  2072. }
  2073. /* We extract both, and on error everything is stopped because it means
  2074. * the vote is malformed for the shared random value(s). */
  2075. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  2076. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  2077. voter_identity);
  2078. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  2079. }
  2080. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  2081. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  2082. voter_identity);
  2083. }
  2084. }
  2085. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  2086. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  2087. networkstatus_t *
  2088. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  2089. networkstatus_type_t ns_type)
  2090. {
  2091. smartlist_t *tokens = smartlist_new();
  2092. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  2093. networkstatus_voter_info_t *voter = NULL;
  2094. networkstatus_t *ns = NULL;
  2095. common_digests_t ns_digests;
  2096. uint8_t sha3_as_signed[DIGEST256_LEN];
  2097. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  2098. directory_token_t *tok;
  2099. struct in_addr in;
  2100. int i, inorder, n_signatures = 0;
  2101. memarea_t *area = NULL, *rs_area = NULL;
  2102. consensus_flavor_t flav = FLAV_NS;
  2103. char *last_kwd=NULL;
  2104. tor_assert(s);
  2105. if (eos_out)
  2106. *eos_out = NULL;
  2107. if (router_get_networkstatus_v3_hashes(s, &ns_digests) ||
  2108. router_get_networkstatus_v3_sha3_as_signed(sha3_as_signed, s)<0) {
  2109. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2110. goto err;
  2111. }
  2112. area = memarea_new();
  2113. end_of_header = find_start_of_next_routerstatus(s);
  2114. if (tokenize_string(area, s, end_of_header, tokens,
  2115. (ns_type == NS_TYPE_CONSENSUS) ?
  2116. networkstatus_consensus_token_table :
  2117. networkstatus_token_table, 0)) {
  2118. log_warn(LD_DIR, "Error tokenizing network-status header");
  2119. goto err;
  2120. }
  2121. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2122. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  2123. memcpy(&ns->digest_sha3_as_signed, sha3_as_signed, sizeof(sha3_as_signed));
  2124. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2125. tor_assert(tok);
  2126. if (tok->n_args > 1) {
  2127. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  2128. if (flavor < 0) {
  2129. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  2130. escaped(tok->args[1]));
  2131. goto err;
  2132. }
  2133. ns->flavor = flav = flavor;
  2134. }
  2135. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  2136. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  2137. goto err;
  2138. }
  2139. if (ns_type != NS_TYPE_CONSENSUS) {
  2140. const char *end_of_cert = NULL;
  2141. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2142. goto err;
  2143. ++cert;
  2144. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2145. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2146. goto err;
  2147. }
  2148. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2149. tor_assert(tok->n_args);
  2150. if (!strcmp(tok->args[0], "vote")) {
  2151. ns->type = NS_TYPE_VOTE;
  2152. } else if (!strcmp(tok->args[0], "consensus")) {
  2153. ns->type = NS_TYPE_CONSENSUS;
  2154. } else if (!strcmp(tok->args[0], "opinion")) {
  2155. ns->type = NS_TYPE_OPINION;
  2156. } else {
  2157. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2158. escaped(tok->args[0]));
  2159. goto err;
  2160. }
  2161. if (ns_type != ns->type) {
  2162. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2163. goto err;
  2164. }
  2165. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2166. tok = find_by_keyword(tokens, K_PUBLISHED);
  2167. if (parse_iso_time(tok->args[0], &ns->published))
  2168. goto err;
  2169. ns->supported_methods = smartlist_new();
  2170. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2171. if (tok) {
  2172. for (i=0; i < tok->n_args; ++i)
  2173. smartlist_add_strdup(ns->supported_methods, tok->args[i]);
  2174. } else {
  2175. smartlist_add_strdup(ns->supported_methods, "1");
  2176. }
  2177. } else {
  2178. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2179. if (tok) {
  2180. int num_ok;
  2181. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2182. &num_ok, NULL);
  2183. if (!num_ok)
  2184. goto err;
  2185. } else {
  2186. ns->consensus_method = 1;
  2187. }
  2188. }
  2189. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
  2190. ns->recommended_client_protocols = tor_strdup(tok->args[0]);
  2191. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
  2192. ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
  2193. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
  2194. ns->required_client_protocols = tor_strdup(tok->args[0]);
  2195. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
  2196. ns->required_relay_protocols = tor_strdup(tok->args[0]);
  2197. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2198. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2199. goto err;
  2200. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2201. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2202. goto err;
  2203. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2204. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2205. goto err;
  2206. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2207. tor_assert(tok->n_args >= 2);
  2208. {
  2209. int ok;
  2210. ns->vote_seconds =
  2211. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2212. if (!ok)
  2213. goto err;
  2214. ns->dist_seconds =
  2215. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2216. if (!ok)
  2217. goto err;
  2218. }
  2219. if (ns->valid_after +
  2220. (get_options()->TestingTorNetwork ?
  2221. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  2222. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2223. goto err;
  2224. }
  2225. if (ns->valid_after +
  2226. (get_options()->TestingTorNetwork ?
  2227. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  2228. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2229. goto err;
  2230. }
  2231. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2232. log_warn(LD_DIR, "Vote seconds is too short");
  2233. goto err;
  2234. }
  2235. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2236. log_warn(LD_DIR, "Dist seconds is too short");
  2237. goto err;
  2238. }
  2239. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2240. ns->client_versions = tor_strdup(tok->args[0]);
  2241. }
  2242. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2243. ns->server_versions = tor_strdup(tok->args[0]);
  2244. }
  2245. {
  2246. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  2247. ns->package_lines = smartlist_new();
  2248. if (package_lst) {
  2249. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  2250. smartlist_add_strdup(ns->package_lines, t->args[0]));
  2251. }
  2252. smartlist_free(package_lst);
  2253. }
  2254. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2255. ns->known_flags = smartlist_new();
  2256. inorder = 1;
  2257. for (i = 0; i < tok->n_args; ++i) {
  2258. smartlist_add_strdup(ns->known_flags, tok->args[i]);
  2259. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2260. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2261. inorder = 0;
  2262. }
  2263. }
  2264. if (!inorder) {
  2265. log_warn(LD_DIR, "known-flags not in order");
  2266. goto err;
  2267. }
  2268. if (ns->type != NS_TYPE_CONSENSUS &&
  2269. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  2270. /* If we allowed more than 64 flags in votes, then parsing them would make
  2271. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  2272. * bit-shift. This is only for votes and opinions: consensus users don't
  2273. * care about flags they don't recognize, and so don't build a bitfield
  2274. * for them. */
  2275. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  2276. goto err;
  2277. }
  2278. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2279. if (tok) {
  2280. int any_dups = 0;
  2281. inorder = 1;
  2282. ns->net_params = smartlist_new();
  2283. for (i = 0; i < tok->n_args; ++i) {
  2284. int ok=0;
  2285. char *eq = strchr(tok->args[i], '=');
  2286. size_t eq_pos;
  2287. if (!eq) {
  2288. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2289. goto err;
  2290. }
  2291. eq_pos = eq-tok->args[i];
  2292. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2293. if (!ok) {
  2294. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2295. goto err;
  2296. }
  2297. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2298. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2299. inorder = 0;
  2300. }
  2301. if (last_kwd && eq_pos == strlen(last_kwd) &&
  2302. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  2303. log_warn(LD_DIR, "Duplicate value for %s parameter",
  2304. escaped(tok->args[i]));
  2305. any_dups = 1;
  2306. }
  2307. tor_free(last_kwd);
  2308. last_kwd = tor_strndup(tok->args[i], eq_pos);
  2309. smartlist_add_strdup(ns->net_params, tok->args[i]);
  2310. }
  2311. if (!inorder) {
  2312. log_warn(LD_DIR, "params not in order");
  2313. goto err;
  2314. }
  2315. if (any_dups) {
  2316. log_warn(LD_DIR, "Duplicate in parameters");
  2317. goto err;
  2318. }
  2319. }
  2320. ns->voters = smartlist_new();
  2321. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2322. tok = _tok;
  2323. if (tok->tp == K_DIR_SOURCE) {
  2324. tor_assert(tok->n_args >= 6);
  2325. if (voter)
  2326. smartlist_add(ns->voters, voter);
  2327. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2328. voter->sigs = smartlist_new();
  2329. if (ns->type != NS_TYPE_CONSENSUS)
  2330. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  2331. voter->nickname = tor_strdup(tok->args[0]);
  2332. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2333. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2334. tok->args[1], HEX_DIGEST_LEN)
  2335. != sizeof(voter->identity_digest)) {
  2336. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2337. "network-status document.", escaped(tok->args[1]));
  2338. goto err;
  2339. }
  2340. if (ns->type != NS_TYPE_CONSENSUS &&
  2341. tor_memneq(ns->cert->cache_info.identity_digest,
  2342. voter->identity_digest, DIGEST_LEN)) {
  2343. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2344. goto err;
  2345. }
  2346. if (ns->type != NS_TYPE_CONSENSUS) {
  2347. if (authority_cert_is_blacklisted(ns->cert)) {
  2348. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  2349. "signing key %s",
  2350. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  2351. goto err;
  2352. }
  2353. }
  2354. voter->address = tor_strdup(tok->args[2]);
  2355. if (!tor_inet_aton(tok->args[3], &in)) {
  2356. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2357. escaped(tok->args[3]));
  2358. goto err;
  2359. }
  2360. voter->addr = ntohl(in.s_addr);
  2361. int ok;
  2362. voter->dir_port = (uint16_t)
  2363. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2364. if (!ok)
  2365. goto err;
  2366. voter->or_port = (uint16_t)
  2367. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2368. if (!ok)
  2369. goto err;
  2370. } else if (tok->tp == K_CONTACT) {
  2371. if (!voter || voter->contact) {
  2372. log_warn(LD_DIR, "contact element is out of place.");
  2373. goto err;
  2374. }
  2375. voter->contact = tor_strdup(tok->args[0]);
  2376. } else if (tok->tp == K_VOTE_DIGEST) {
  2377. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2378. tor_assert(tok->n_args >= 1);
  2379. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2380. log_warn(LD_DIR, "vote-digest element is out of place.");
  2381. goto err;
  2382. }
  2383. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2384. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2385. tok->args[0], HEX_DIGEST_LEN)
  2386. != sizeof(voter->vote_digest)) {
  2387. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2388. "network-status consensus.", escaped(tok->args[0]));
  2389. goto err;
  2390. }
  2391. }
  2392. } SMARTLIST_FOREACH_END(_tok);
  2393. if (voter) {
  2394. smartlist_add(ns->voters, voter);
  2395. voter = NULL;
  2396. }
  2397. if (smartlist_len(ns->voters) == 0) {
  2398. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  2399. goto err;
  2400. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2401. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2402. goto err;
  2403. }
  2404. if (ns->type != NS_TYPE_CONSENSUS &&
  2405. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2406. int bad = 1;
  2407. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2408. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  2409. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  2410. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  2411. bad = 1;
  2412. else
  2413. bad = 0;
  2414. }
  2415. if (bad) {
  2416. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2417. escaped(tok->args[0]));
  2418. }
  2419. }
  2420. /* If this is a vote document, check if information about the shared
  2421. randomness protocol is included, and extract it. */
  2422. if (ns->type == NS_TYPE_VOTE) {
  2423. dirvote_parse_sr_commits(ns, tokens);
  2424. }
  2425. /* For both a vote and consensus, extract the shared random values. */
  2426. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  2427. extract_shared_random_srvs(ns, tokens);
  2428. }
  2429. /* Parse routerstatus lines. */
  2430. rs_tokens = smartlist_new();
  2431. rs_area = memarea_new();
  2432. s = end_of_header;
  2433. ns->routerstatus_list = smartlist_new();
  2434. while (!strcmpstart(s, "r ")) {
  2435. if (ns->type != NS_TYPE_CONSENSUS) {
  2436. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2437. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2438. rs, 0, 0)) {
  2439. smartlist_add(ns->routerstatus_list, rs);
  2440. } else {
  2441. vote_routerstatus_free(rs);
  2442. }
  2443. } else {
  2444. routerstatus_t *rs;
  2445. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2446. NULL, NULL,
  2447. ns->consensus_method,
  2448. flav))) {
  2449. /* Use exponential-backoff scheduling when downloading microdescs */
  2450. smartlist_add(ns->routerstatus_list, rs);
  2451. }
  2452. }
  2453. }
  2454. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2455. routerstatus_t *rs1, *rs2;
  2456. if (ns->type != NS_TYPE_CONSENSUS) {
  2457. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2458. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2459. rs1 = &a->status; rs2 = &b->status;
  2460. } else {
  2461. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2462. rs2 = smartlist_get(ns->routerstatus_list, i);
  2463. }
  2464. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2465. >= 0) {
  2466. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  2467. goto err;
  2468. }
  2469. }
  2470. if (ns_type != NS_TYPE_CONSENSUS) {
  2471. digest256map_t *ed_id_map = digest256map_new();
  2472. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  2473. vrs) {
  2474. if (! vrs->has_ed25519_listing ||
  2475. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  2476. continue;
  2477. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  2478. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  2479. "unique");
  2480. digest256map_free(ed_id_map, NULL);
  2481. goto err;
  2482. }
  2483. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  2484. } SMARTLIST_FOREACH_END(vrs);
  2485. digest256map_free(ed_id_map, NULL);
  2486. }
  2487. /* Parse footer; check signature. */
  2488. footer_tokens = smartlist_new();
  2489. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2490. ++end_of_footer;
  2491. else
  2492. end_of_footer = s + strlen(s);
  2493. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2494. networkstatus_vote_footer_token_table, 0)) {
  2495. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2496. goto err;
  2497. }
  2498. {
  2499. int found_sig = 0;
  2500. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2501. tok = _tok;
  2502. if (tok->tp == K_DIRECTORY_SIGNATURE)
  2503. found_sig = 1;
  2504. else if (found_sig) {
  2505. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  2506. goto err;
  2507. }
  2508. } SMARTLIST_FOREACH_END(_tok);
  2509. }
  2510. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  2511. if (tok != smartlist_get(footer_tokens, 0)) {
  2512. log_warn(LD_DIR, "Misplaced directory-footer token");
  2513. goto err;
  2514. }
  2515. }
  2516. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  2517. if (tok) {
  2518. ns->weight_params = smartlist_new();
  2519. for (i = 0; i < tok->n_args; ++i) {
  2520. int ok=0;
  2521. char *eq = strchr(tok->args[i], '=');
  2522. if (!eq) {
  2523. log_warn(LD_DIR, "Bad element '%s' in weight params",
  2524. escaped(tok->args[i]));
  2525. goto err;
  2526. }
  2527. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2528. if (!ok) {
  2529. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2530. goto err;
  2531. }
  2532. smartlist_add_strdup(ns->weight_params, tok->args[i]);
  2533. }
  2534. }
  2535. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2536. char declared_identity[DIGEST_LEN];
  2537. networkstatus_voter_info_t *v;
  2538. document_signature_t *sig;
  2539. const char *id_hexdigest = NULL;
  2540. const char *sk_hexdigest = NULL;
  2541. digest_algorithm_t alg = DIGEST_SHA1;
  2542. tok = _tok;
  2543. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2544. continue;
  2545. tor_assert(tok->n_args >= 2);
  2546. if (tok->n_args == 2) {
  2547. id_hexdigest = tok->args[0];
  2548. sk_hexdigest = tok->args[1];
  2549. } else {
  2550. const char *algname = tok->args[0];
  2551. int a;
  2552. id_hexdigest = tok->args[1];
  2553. sk_hexdigest = tok->args[2];
  2554. a = crypto_digest_algorithm_parse_name(algname);
  2555. if (a<0) {
  2556. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  2557. escaped(algname));
  2558. continue;
  2559. }
  2560. alg = a;
  2561. }
  2562. if (!tok->object_type ||
  2563. strcmp(tok->object_type, "SIGNATURE") ||
  2564. tok->object_size < 128 || tok->object_size > 512) {
  2565. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2566. goto err;
  2567. }
  2568. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  2569. base16_decode(declared_identity, sizeof(declared_identity),
  2570. id_hexdigest, HEX_DIGEST_LEN)
  2571. != sizeof(declared_identity)) {
  2572. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2573. "network-status document.", escaped(id_hexdigest));
  2574. goto err;
  2575. }
  2576. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2577. log_warn(LD_DIR, "ID on signature on network-status document does "
  2578. "not match any declared directory source.");
  2579. goto err;
  2580. }
  2581. sig = tor_malloc_zero(sizeof(document_signature_t));
  2582. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  2583. sig->alg = alg;
  2584. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  2585. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  2586. sk_hexdigest, HEX_DIGEST_LEN)
  2587. != sizeof(sig->signing_key_digest)) {
  2588. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  2589. "network-status document.", escaped(sk_hexdigest));
  2590. tor_free(sig);
  2591. goto err;
  2592. }
  2593. if (ns->type != NS_TYPE_CONSENSUS) {
  2594. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  2595. DIGEST_LEN)) {
  2596. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2597. "network-status vote.");
  2598. tor_free(sig);
  2599. goto err;
  2600. }
  2601. }
  2602. if (networkstatus_get_voter_sig_by_alg(v, sig->alg)) {
  2603. /* We already parsed a vote with this algorithm from this voter. Use the
  2604. first one. */
  2605. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  2606. "that contains two signatures from the same voter with the same "
  2607. "algorithm. Ignoring the second signature.");
  2608. tor_free(sig);
  2609. continue;
  2610. }
  2611. if (ns->type != NS_TYPE_CONSENSUS) {
  2612. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  2613. tok, ns->cert->signing_key, 0,
  2614. "network-status document")) {
  2615. tor_free(sig);
  2616. goto err;
  2617. }
  2618. sig->good_signature = 1;
  2619. } else {
  2620. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  2621. tor_free(sig);
  2622. goto err;
  2623. }
  2624. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  2625. sig->signature_len = (int) tok->object_size;
  2626. }
  2627. smartlist_add(v->sigs, sig);
  2628. ++n_signatures;
  2629. } SMARTLIST_FOREACH_END(_tok);
  2630. if (! n_signatures) {
  2631. log_warn(LD_DIR, "No signatures on networkstatus document.");
  2632. goto err;
  2633. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  2634. log_warn(LD_DIR, "Received more than one signature on a "
  2635. "network-status vote.");
  2636. goto err;
  2637. }
  2638. if (eos_out)
  2639. *eos_out = end_of_footer;
  2640. goto done;
  2641. err:
  2642. dump_desc(s_dup, "v3 networkstatus");
  2643. networkstatus_vote_free(ns);
  2644. ns = NULL;
  2645. done:
  2646. if (tokens) {
  2647. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2648. smartlist_free(tokens);
  2649. }
  2650. if (voter) {
  2651. if (voter->sigs) {
  2652. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  2653. document_signature_free(sig));
  2654. smartlist_free(voter->sigs);
  2655. }
  2656. tor_free(voter->nickname);
  2657. tor_free(voter->address);
  2658. tor_free(voter->contact);
  2659. tor_free(voter);
  2660. }
  2661. if (rs_tokens) {
  2662. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  2663. smartlist_free(rs_tokens);
  2664. }
  2665. if (footer_tokens) {
  2666. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  2667. smartlist_free(footer_tokens);
  2668. }
  2669. if (area) {
  2670. DUMP_AREA(area, "v3 networkstatus");
  2671. memarea_drop_all(area);
  2672. }
  2673. if (rs_area)
  2674. memarea_drop_all(rs_area);
  2675. tor_free(last_kwd);
  2676. return ns;
  2677. }
  2678. /** Return the common_digests_t that holds the digests of the
  2679. * <b>flavor_name</b>-flavored networkstatus according to the detached
  2680. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  2681. * needed. */
  2682. static common_digests_t *
  2683. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  2684. {
  2685. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  2686. if (!d) {
  2687. d = tor_malloc_zero(sizeof(common_digests_t));
  2688. strmap_set(sigs->digests, flavor_name, d);
  2689. }
  2690. return d;
  2691. }
  2692. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  2693. * networkstatus according to the detached signatures document <b>sigs</b>,
  2694. * allocating a new common_digests_t as needed. */
  2695. static smartlist_t *
  2696. detached_get_signatures(ns_detached_signatures_t *sigs,
  2697. const char *flavor_name)
  2698. {
  2699. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  2700. if (!sl) {
  2701. sl = smartlist_new();
  2702. strmap_set(sigs->signatures, flavor_name, sl);
  2703. }
  2704. return sl;
  2705. }
  2706. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2707. * <b>eos</b> and return the result. Return -1 on failure. */
  2708. ns_detached_signatures_t *
  2709. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2710. {
  2711. /* XXXX there is too much duplicate shared between this function and
  2712. * networkstatus_parse_vote_from_string(). */
  2713. directory_token_t *tok;
  2714. memarea_t *area = NULL;
  2715. common_digests_t *digests;
  2716. smartlist_t *tokens = smartlist_new();
  2717. ns_detached_signatures_t *sigs =
  2718. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2719. sigs->digests = strmap_new();
  2720. sigs->signatures = strmap_new();
  2721. if (!eos)
  2722. eos = s + strlen(s);
  2723. area = memarea_new();
  2724. if (tokenize_string(area,s, eos, tokens,
  2725. networkstatus_detached_signature_token_table, 0)) {
  2726. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2727. goto err;
  2728. }
  2729. /* Grab all the digest-like tokens. */
  2730. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2731. const char *algname;
  2732. digest_algorithm_t alg;
  2733. const char *flavor;
  2734. const char *hexdigest;
  2735. size_t expected_length, digest_length;
  2736. tok = _tok;
  2737. if (tok->tp == K_CONSENSUS_DIGEST) {
  2738. algname = "sha1";
  2739. alg = DIGEST_SHA1;
  2740. flavor = "ns";
  2741. hexdigest = tok->args[0];
  2742. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  2743. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  2744. if (a<0) {
  2745. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  2746. continue;
  2747. }
  2748. alg = (digest_algorithm_t) a;
  2749. flavor = tok->args[0];
  2750. algname = tok->args[1];
  2751. hexdigest = tok->args[2];
  2752. } else {
  2753. continue;
  2754. }
  2755. digest_length = crypto_digest_algorithm_get_length(alg);
  2756. expected_length = digest_length * 2; /* hex encoding */
  2757. if (strlen(hexdigest) != expected_length) {
  2758. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2759. "networkstatus signatures");
  2760. goto err;
  2761. }
  2762. digests = detached_get_digests(sigs, flavor);
  2763. tor_assert(digests);
  2764. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  2765. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  2766. "signatures document", flavor, algname);
  2767. continue;
  2768. }
  2769. if (base16_decode(digests->d[alg], digest_length,
  2770. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  2771. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  2772. "networkstatus signatures");
  2773. goto err;
  2774. }
  2775. } SMARTLIST_FOREACH_END(_tok);
  2776. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2777. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2778. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2779. goto err;
  2780. }
  2781. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2782. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2783. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2784. goto err;
  2785. }
  2786. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2787. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2788. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2789. goto err;
  2790. }
  2791. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2792. const char *id_hexdigest;
  2793. const char *sk_hexdigest;
  2794. const char *algname;
  2795. const char *flavor;
  2796. digest_algorithm_t alg;
  2797. char id_digest[DIGEST_LEN];
  2798. char sk_digest[DIGEST_LEN];
  2799. smartlist_t *siglist;
  2800. document_signature_t *sig;
  2801. int is_duplicate;
  2802. tok = _tok;
  2803. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  2804. tor_assert(tok->n_args >= 2);
  2805. flavor = "ns";
  2806. algname = "sha1";
  2807. id_hexdigest = tok->args[0];
  2808. sk_hexdigest = tok->args[1];
  2809. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  2810. tor_assert(tok->n_args >= 4);
  2811. flavor = tok->args[0];
  2812. algname = tok->args[1];
  2813. id_hexdigest = tok->args[2];
  2814. sk_hexdigest = tok->args[3];
  2815. } else {
  2816. continue;
  2817. }
  2818. {
  2819. int a = crypto_digest_algorithm_parse_name(algname);
  2820. if (a<0) {
  2821. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  2822. continue;
  2823. }
  2824. alg = (digest_algorithm_t) a;
  2825. }
  2826. if (!tok->object_type ||
  2827. strcmp(tok->object_type, "SIGNATURE") ||
  2828. tok->object_size < 128 || tok->object_size > 512) {
  2829. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2830. goto err;
  2831. }
  2832. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  2833. base16_decode(id_digest, sizeof(id_digest),
  2834. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  2835. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2836. "network-status vote.", escaped(id_hexdigest));
  2837. goto err;
  2838. }
  2839. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  2840. base16_decode(sk_digest, sizeof(sk_digest),
  2841. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  2842. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  2843. "network-status vote.", escaped(sk_hexdigest));
  2844. goto err;
  2845. }
  2846. siglist = detached_get_signatures(sigs, flavor);
  2847. is_duplicate = 0;
  2848. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  2849. if (dsig->alg == alg &&
  2850. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  2851. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  2852. is_duplicate = 1;
  2853. }
  2854. });
  2855. if (is_duplicate) {
  2856. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  2857. "found.");
  2858. continue;
  2859. }
  2860. sig = tor_malloc_zero(sizeof(document_signature_t));
  2861. sig->alg = alg;
  2862. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  2863. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  2864. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  2865. tor_free(sig);
  2866. goto err;
  2867. }
  2868. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  2869. sig->signature_len = (int) tok->object_size;
  2870. smartlist_add(siglist, sig);
  2871. } SMARTLIST_FOREACH_END(_tok);
  2872. goto done;
  2873. err:
  2874. ns_detached_signatures_free(sigs);
  2875. sigs = NULL;
  2876. done:
  2877. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2878. smartlist_free(tokens);
  2879. if (area) {
  2880. DUMP_AREA(area, "detached signatures");
  2881. memarea_drop_all(area);
  2882. }
  2883. return sigs;
  2884. }
  2885. /** Parse the addr policy in the string <b>s</b> and return it. If
  2886. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2887. * ADDR_POLICY_REJECT) for items that specify no action.
  2888. *
  2889. * Returns NULL on policy errors.
  2890. *
  2891. * Set *<b>malformed_list</b> to true if the entire policy list should be
  2892. * discarded. Otherwise, set it to false, and only this item should be ignored
  2893. * on error - the rest of the policy list can continue to be processed and
  2894. * used.
  2895. *
  2896. * The addr_policy_t returned by this function can have its address set to
  2897. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  2898. * of AF_INET and AF_INET6 items.
  2899. */
  2900. MOCK_IMPL(addr_policy_t *,
  2901. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  2902. int *malformed_list))
  2903. {
  2904. directory_token_t *tok = NULL;
  2905. const char *cp, *eos;
  2906. /* Longest possible policy is
  2907. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  2908. * which contains a max-length IPv6 address, plus 26 characters.
  2909. * But note that there can be an arbitrary amount of space between the
  2910. * accept and the address:mask/port element.
  2911. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  2912. * IPv6 address. But making the buffer shorter might cause valid long lines,
  2913. * which parsed in previous versions, to fail to parse in new versions.
  2914. * (These lines would have to have excessive amounts of whitespace.) */
  2915. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2916. addr_policy_t *r;
  2917. memarea_t *area = NULL;
  2918. tor_assert(malformed_list);
  2919. *malformed_list = 0;
  2920. s = eat_whitespace(s);
  2921. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  2922. * and ":" (port separator) are ambiguous */
  2923. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2924. if (tor_snprintf(line, sizeof(line), "%s %s",
  2925. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2926. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2927. return NULL;
  2928. }
  2929. cp = line;
  2930. tor_strlower(line);
  2931. } else { /* assume an already well-formed address policy line */
  2932. cp = s;
  2933. }
  2934. eos = cp + strlen(cp);
  2935. area = memarea_new();
  2936. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  2937. if (tok->tp == ERR_) {
  2938. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2939. goto err;
  2940. }
  2941. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  2942. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  2943. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2944. goto err;
  2945. }
  2946. /* Use the extended interpretation of accept/reject *,
  2947. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  2948. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  2949. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  2950. if (!r) {
  2951. goto err;
  2952. }
  2953. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  2954. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  2955. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  2956. * either an IPv4 or IPv6 address. */
  2957. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2958. tor_addr_family(&r->addr) != AF_INET6) {
  2959. /* This is a non-fatal error, just ignore this one entry. */
  2960. *malformed_list = 0;
  2961. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  2962. "exit policy. Ignoring, but continuing to parse rules. (Use "
  2963. "accept/reject with IPv4 addresses.)",
  2964. tok->n_args == 1 ? tok->args[0] : "");
  2965. addr_policy_free(r);
  2966. r = NULL;
  2967. goto done;
  2968. }
  2969. goto done;
  2970. err:
  2971. *malformed_list = 1;
  2972. r = NULL;
  2973. done:
  2974. token_clear(tok);
  2975. if (area) {
  2976. DUMP_AREA(area, "policy item");
  2977. memarea_drop_all(area);
  2978. }
  2979. return r;
  2980. }
  2981. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2982. * <b>router</b>. Return 0 on success, -1 on failure. */
  2983. static int
  2984. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2985. {
  2986. addr_policy_t *newe;
  2987. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  2988. newe = router_parse_addr_policy(tok, 0);
  2989. if (!newe)
  2990. return -1;
  2991. if (! router->exit_policy)
  2992. router->exit_policy = smartlist_new();
  2993. /* Ensure that in descriptors, accept/reject fields are followed by
  2994. * IPv4 addresses, and accept6/reject6 fields are followed by
  2995. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  2996. * accept/reject followed by IPv6. */
  2997. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2998. tor_addr_family(&newe->addr) == AF_INET)
  2999. ||
  3000. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3001. tor_addr_family(&newe->addr) == AF_INET6)) {
  3002. /* There's nothing the user can do about other relays' descriptors,
  3003. * so we don't provide usage advice here. */
  3004. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3005. "policy '%s'. Discarding entire router descriptor.",
  3006. tok->n_args == 1 ? tok->args[0] : "");
  3007. addr_policy_free(newe);
  3008. return -1;
  3009. }
  3010. smartlist_add(router->exit_policy, newe);
  3011. return 0;
  3012. }
  3013. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  3014. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  3015. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  3016. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  3017. * policies */
  3018. static addr_policy_t *
  3019. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3020. {
  3021. addr_policy_t newe;
  3022. char *arg;
  3023. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3024. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3025. if (tok->n_args != 1)
  3026. return NULL;
  3027. arg = tok->args[0];
  3028. if (!strcmpstart(arg,"private"))
  3029. return router_parse_addr_policy_private(tok);
  3030. memset(&newe, 0, sizeof(newe));
  3031. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3032. newe.policy_type = ADDR_POLICY_REJECT;
  3033. else
  3034. newe.policy_type = ADDR_POLICY_ACCEPT;
  3035. /* accept6/reject6 * produces an IPv6 wildcard address only.
  3036. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  3037. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  3038. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  3039. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  3040. }
  3041. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3042. &newe.prt_min, &newe.prt_max) < 0) {
  3043. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3044. return NULL;
  3045. }
  3046. return addr_policy_get_canonical_entry(&newe);
  3047. }
  3048. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  3049. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3050. * router descriptors until earlier versions are obsolete.
  3051. *
  3052. * accept/reject and accept6/reject6 private all produce rules for both
  3053. * IPv4 and IPv6 addresses.
  3054. */
  3055. static addr_policy_t *
  3056. router_parse_addr_policy_private(directory_token_t *tok)
  3057. {
  3058. const char *arg;
  3059. uint16_t port_min, port_max;
  3060. addr_policy_t result;
  3061. arg = tok->args[0];
  3062. if (strcmpstart(arg, "private"))
  3063. return NULL;
  3064. arg += strlen("private");
  3065. arg = (char*) eat_whitespace(arg);
  3066. if (!arg || *arg != ':')
  3067. return NULL;
  3068. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  3069. return NULL;
  3070. memset(&result, 0, sizeof(result));
  3071. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3072. result.policy_type = ADDR_POLICY_REJECT;
  3073. else
  3074. result.policy_type = ADDR_POLICY_ACCEPT;
  3075. result.is_private = 1;
  3076. result.prt_min = port_min;
  3077. result.prt_max = port_max;
  3078. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  3079. log_warn(LD_GENERAL,
  3080. "'%s' expands into rules which apply to all private IPv4 and "
  3081. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  3082. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  3083. }
  3084. return addr_policy_get_canonical_entry(&result);
  3085. }
  3086. /** Log and exit if <b>t</b> is malformed */
  3087. void
  3088. assert_addr_policy_ok(smartlist_t *lst)
  3089. {
  3090. if (!lst) return;
  3091. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  3092. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  3093. t->policy_type == ADDR_POLICY_ACCEPT);
  3094. tor_assert(t->prt_min <= t->prt_max);
  3095. });
  3096. }
  3097. /** Return a newly allocated smartlist of all accept or reject tokens in
  3098. * <b>s</b>.
  3099. */
  3100. static smartlist_t *
  3101. find_all_exitpolicy(smartlist_t *s)
  3102. {
  3103. smartlist_t *out = smartlist_new();
  3104. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3105. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  3106. t->tp == K_REJECT || t->tp == K_REJECT6)
  3107. smartlist_add(out,t));
  3108. return out;
  3109. }
  3110. /** Assuming that s starts with a microdesc, return the start of the
  3111. * *NEXT* one. Return NULL on "not found." */
  3112. static const char *
  3113. find_start_of_next_microdesc(const char *s, const char *eos)
  3114. {
  3115. int started_with_annotations;
  3116. s = eat_whitespace_eos(s, eos);
  3117. if (!s)
  3118. return NULL;
  3119. #define CHECK_LENGTH() STMT_BEGIN \
  3120. if (s+32 > eos) \
  3121. return NULL; \
  3122. STMT_END
  3123. #define NEXT_LINE() STMT_BEGIN \
  3124. s = memchr(s, '\n', eos-s); \
  3125. if (!s || s+1 >= eos) \
  3126. return NULL; \
  3127. s++; \
  3128. STMT_END
  3129. CHECK_LENGTH();
  3130. started_with_annotations = (*s == '@');
  3131. if (started_with_annotations) {
  3132. /* Start by advancing to the first non-annotation line. */
  3133. while (*s == '@')
  3134. NEXT_LINE();
  3135. }
  3136. CHECK_LENGTH();
  3137. /* Now we should be pointed at an onion-key line. If we are, then skip
  3138. * it. */
  3139. if (!strcmpstart(s, "onion-key"))
  3140. NEXT_LINE();
  3141. /* Okay, now we're pointed at the first line of the microdescriptor which is
  3142. not an annotation or onion-key. The next line that _is_ an annotation or
  3143. onion-key is the start of the next microdescriptor. */
  3144. while (s+32 < eos) {
  3145. if (*s == '@' || !strcmpstart(s, "onion-key"))
  3146. return s;
  3147. NEXT_LINE();
  3148. }
  3149. return NULL;
  3150. #undef CHECK_LENGTH
  3151. #undef NEXT_LINE
  3152. }
  3153. /** Parse as many microdescriptors as are found from the string starting at
  3154. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  3155. * annotations we recognize and ignore ones we don't.
  3156. *
  3157. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  3158. * descriptor in the body field of each microdesc_t.
  3159. *
  3160. * Return all newly parsed microdescriptors in a newly allocated
  3161. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  3162. * microdesc digest to it for every microdesc that we found to be badly
  3163. * formed. (This may cause duplicates) */
  3164. smartlist_t *
  3165. microdescs_parse_from_string(const char *s, const char *eos,
  3166. int allow_annotations,
  3167. saved_location_t where,
  3168. smartlist_t *invalid_digests_out)
  3169. {
  3170. smartlist_t *tokens;
  3171. smartlist_t *result;
  3172. microdesc_t *md = NULL;
  3173. memarea_t *area;
  3174. const char *start = s;
  3175. const char *start_of_next_microdesc;
  3176. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  3177. const int copy_body = (where != SAVED_IN_CACHE);
  3178. directory_token_t *tok;
  3179. if (!eos)
  3180. eos = s + strlen(s);
  3181. s = eat_whitespace_eos(s, eos);
  3182. area = memarea_new();
  3183. result = smartlist_new();
  3184. tokens = smartlist_new();
  3185. while (s < eos) {
  3186. int okay = 0;
  3187. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  3188. if (!start_of_next_microdesc)
  3189. start_of_next_microdesc = eos;
  3190. md = tor_malloc_zero(sizeof(microdesc_t));
  3191. {
  3192. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  3193. "onion-key");
  3194. const int no_onion_key = (cp == NULL);
  3195. if (no_onion_key) {
  3196. cp = s; /* So that we have *some* junk to put in the body */
  3197. }
  3198. md->bodylen = start_of_next_microdesc - cp;
  3199. md->saved_location = where;
  3200. if (copy_body)
  3201. md->body = tor_memdup_nulterm(cp, md->bodylen);
  3202. else
  3203. md->body = (char*)cp;
  3204. md->off = cp - start;
  3205. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  3206. if (no_onion_key) {
  3207. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  3208. goto next;
  3209. }
  3210. }
  3211. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  3212. microdesc_token_table, flags)) {
  3213. log_warn(LD_DIR, "Unparseable microdescriptor");
  3214. goto next;
  3215. }
  3216. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  3217. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  3218. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  3219. goto next;
  3220. }
  3221. }
  3222. tok = find_by_keyword(tokens, K_ONION_KEY);
  3223. if (!crypto_pk_public_exponent_ok(tok->key)) {
  3224. log_warn(LD_DIR,
  3225. "Relay's onion key had invalid exponent.");
  3226. goto next;
  3227. }
  3228. router_set_rsa_onion_pkey(tok->key, &md->onion_pkey,
  3229. &md->onion_pkey_len);
  3230. crypto_pk_free(tok->key);
  3231. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  3232. curve25519_public_key_t k;
  3233. tor_assert(tok->n_args >= 1);
  3234. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  3235. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  3236. goto next;
  3237. }
  3238. md->onion_curve25519_pkey =
  3239. tor_memdup(&k, sizeof(curve25519_public_key_t));
  3240. }
  3241. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  3242. if (id_lines) {
  3243. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  3244. tor_assert(t->n_args >= 2);
  3245. if (!strcmp(t->args[0], "ed25519")) {
  3246. if (md->ed25519_identity_pkey) {
  3247. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  3248. smartlist_free(id_lines);
  3249. goto next;
  3250. }
  3251. ed25519_public_key_t k;
  3252. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  3253. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  3254. smartlist_free(id_lines);
  3255. goto next;
  3256. }
  3257. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  3258. }
  3259. } SMARTLIST_FOREACH_END(t);
  3260. smartlist_free(id_lines);
  3261. }
  3262. {
  3263. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  3264. if (a_lines) {
  3265. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  3266. smartlist_free(a_lines);
  3267. }
  3268. }
  3269. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  3270. int i;
  3271. md->family = smartlist_new();
  3272. for (i=0;i<tok->n_args;++i) {
  3273. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  3274. log_warn(LD_DIR, "Illegal nickname %s in family line",
  3275. escaped(tok->args[i]));
  3276. goto next;
  3277. }
  3278. smartlist_add_strdup(md->family, tok->args[i]);
  3279. }
  3280. }
  3281. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  3282. md->exit_policy = parse_short_policy(tok->args[0]);
  3283. }
  3284. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  3285. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  3286. }
  3287. smartlist_add(result, md);
  3288. okay = 1;
  3289. md = NULL;
  3290. next:
  3291. if (! okay && invalid_digests_out) {
  3292. smartlist_add(invalid_digests_out,
  3293. tor_memdup(md->digest, DIGEST256_LEN));
  3294. }
  3295. microdesc_free(md);
  3296. md = NULL;
  3297. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3298. memarea_clear(area);
  3299. smartlist_clear(tokens);
  3300. s = start_of_next_microdesc;
  3301. }
  3302. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3303. memarea_drop_all(area);
  3304. smartlist_free(tokens);
  3305. return result;
  3306. }
  3307. /** Called on startup; right now we just handle scanning the unparseable
  3308. * descriptor dumps, but hang anything else we might need to do in the
  3309. * future here as well.
  3310. */
  3311. void
  3312. routerparse_init(void)
  3313. {
  3314. /*
  3315. * Check both if the sandbox is active and whether it's configured; no
  3316. * point in loading all that if we won't be able to use it after the
  3317. * sandbox becomes active.
  3318. */
  3319. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  3320. dump_desc_init();
  3321. }
  3322. }
  3323. /** Clean up all data structures used by routerparse.c at exit */
  3324. void
  3325. routerparse_free_all(void)
  3326. {
  3327. dump_desc_fifo_cleanup();
  3328. }