routerparse.c 112 KB

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