routerparse.c 120 KB

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