routerparse.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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. #undef T
  180. /* static function prototypes */
  181. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  182. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
  183. unsigned fmt_flags);
  184. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  185. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  186. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  187. * <b>s</b>. Return 0 on success, -1 on failure.
  188. */
  189. int
  190. router_get_router_hash(const char *s, size_t s_len, char *digest)
  191. {
  192. return router_get_hash_impl(s, s_len, digest,
  193. "router ","\nrouter-signature", '\n',
  194. DIGEST_SHA1);
  195. }
  196. /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
  197. * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
  198. int
  199. router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
  200. {
  201. return router_get_hash_impl(s, s_len, digest, "extra-info",
  202. "\nrouter-signature",'\n', DIGEST_SHA1);
  203. }
  204. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  205. * or to the first of the annotations proceeding the next router or
  206. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  207. * we found an extrainfo, or false if found a router. Do not scan beyond
  208. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  209. static int
  210. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  211. const char *eos,
  212. int *is_extrainfo_out)
  213. {
  214. const char *annotations = NULL;
  215. const char *s = *s_ptr;
  216. s = eat_whitespace_eos(s, eos);
  217. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  218. /* We're at the start of a line. */
  219. tor_assert(*s != '\n');
  220. if (*s == '@' && !annotations) {
  221. annotations = s;
  222. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  223. *s_ptr = annotations ? annotations : s;
  224. *is_extrainfo_out = 0;
  225. return 0;
  226. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  227. *s_ptr = annotations ? annotations : s;
  228. *is_extrainfo_out = 1;
  229. return 0;
  230. }
  231. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  232. break;
  233. s = eat_whitespace_eos(s, eos);
  234. }
  235. return -1;
  236. }
  237. /** Given a string *<b>s</b> containing a concatenated sequence of router
  238. * descriptors (or extra-info documents if <b>want_extrainfo</b> is set),
  239. * parses them and stores the result in <b>dest</b>. All routers are marked
  240. * running and valid. Advances *s to a point immediately following the last
  241. * router entry. Ignore any trailing router entries that are not complete.
  242. *
  243. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  244. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  245. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  246. *
  247. * Returns 0 on success and -1 on failure. Adds a digest to
  248. * <b>invalid_digests_out</b> for every entry that was unparseable or
  249. * invalid. (This may cause duplicate entries.)
  250. */
  251. int
  252. router_parse_list_from_string(const char **s, const char *eos,
  253. smartlist_t *dest,
  254. saved_location_t saved_location,
  255. int want_extrainfo,
  256. int allow_annotations,
  257. const char *prepend_annotations,
  258. smartlist_t *invalid_digests_out)
  259. {
  260. routerinfo_t *router;
  261. extrainfo_t *extrainfo;
  262. signed_descriptor_t *signed_desc = NULL;
  263. void *elt;
  264. const char *end, *start;
  265. int have_extrainfo;
  266. tor_assert(s);
  267. tor_assert(*s);
  268. tor_assert(dest);
  269. start = *s;
  270. if (!eos)
  271. eos = *s + strlen(*s);
  272. tor_assert(eos >= *s);
  273. while (1) {
  274. char raw_digest[DIGEST_LEN];
  275. int have_raw_digest = 0;
  276. int dl_again = 0;
  277. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  278. break;
  279. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  280. if (end)
  281. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  282. if (end)
  283. end += strlen("\n-----END SIGNATURE-----\n");
  284. if (!end)
  285. break;
  286. elt = NULL;
  287. if (have_extrainfo && want_extrainfo) {
  288. routerlist_t *rl = router_get_routerlist();
  289. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  290. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  291. saved_location != SAVED_IN_CACHE,
  292. rl->identity_map, &dl_again);
  293. if (extrainfo) {
  294. signed_desc = &extrainfo->cache_info;
  295. elt = extrainfo;
  296. }
  297. } else if (!have_extrainfo && !want_extrainfo) {
  298. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  299. router = router_parse_entry_from_string(*s, end,
  300. saved_location != SAVED_IN_CACHE,
  301. allow_annotations,
  302. prepend_annotations, &dl_again);
  303. if (router) {
  304. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  305. router_describe(router),
  306. router_purpose_to_string(router->purpose));
  307. signed_desc = &router->cache_info;
  308. elt = router;
  309. }
  310. }
  311. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  312. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  313. }
  314. if (!elt) {
  315. *s = end;
  316. continue;
  317. }
  318. if (saved_location != SAVED_NOWHERE) {
  319. tor_assert(signed_desc);
  320. signed_desc->saved_location = saved_location;
  321. signed_desc->saved_offset = *s - start;
  322. }
  323. *s = end;
  324. smartlist_add(dest, elt);
  325. }
  326. return 0;
  327. }
  328. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  329. * with at least one argument (use GE(1) in setup). If found, store
  330. * address and port number to <b>addr_out</b> and
  331. * <b>port_out</b>. Return number of OR ports found. */
  332. int
  333. find_single_ipv6_orport(const smartlist_t *list,
  334. tor_addr_t *addr_out,
  335. uint16_t *port_out)
  336. {
  337. int ret = 0;
  338. tor_assert(list != NULL);
  339. tor_assert(addr_out != NULL);
  340. tor_assert(port_out != NULL);
  341. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  342. tor_addr_t a;
  343. maskbits_t bits;
  344. uint16_t port_min, port_max;
  345. tor_assert(t->n_args >= 1);
  346. /* XXXX Prop186 the full spec allows much more than this. */
  347. if (tor_addr_parse_mask_ports(t->args[0], 0,
  348. &a, &bits, &port_min,
  349. &port_max) == AF_INET6 &&
  350. bits == 128 &&
  351. port_min == port_max) {
  352. /* Okay, this is one we can understand. Use it and ignore
  353. any potential more addresses in list. */
  354. tor_addr_copy(addr_out, &a);
  355. *port_out = port_min;
  356. ret = 1;
  357. break;
  358. }
  359. } SMARTLIST_FOREACH_END(t);
  360. return ret;
  361. }
  362. /** Helper function: reads a single router entry from *<b>s</b> ...
  363. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  364. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  365. * s through end into the signed_descriptor_body of the resulting
  366. * routerinfo_t.
  367. *
  368. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  369. *
  370. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  371. * before the router; if it's false, reject the router if it's annotated. If
  372. * <b>prepend_annotations</b> is set, it should contain some annotations:
  373. * append them to the front of the router before parsing it, and keep them
  374. * around when caching the router.
  375. *
  376. * Only one of allow_annotations and prepend_annotations may be set.
  377. *
  378. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  379. * if it's okay to try to download a descriptor with this same digest again,
  380. * and 0 if it isn't. (It might not be okay to download it again if part of
  381. * the part covered by the digest is invalid.)
  382. */
  383. routerinfo_t *
  384. router_parse_entry_from_string(const char *s, const char *end,
  385. int cache_copy, int allow_annotations,
  386. const char *prepend_annotations,
  387. int *can_dl_again_out)
  388. {
  389. routerinfo_t *router = NULL;
  390. char digest[128];
  391. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  392. directory_token_t *tok;
  393. struct in_addr in;
  394. const char *start_of_annotations, *cp, *s_dup = s;
  395. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  396. int ok = 1;
  397. memarea_t *area = NULL;
  398. tor_cert_t *ntor_cc_cert = NULL;
  399. /* Do not set this to '1' until we have parsed everything that we intend to
  400. * parse that's covered by the hash. */
  401. int can_dl_again = 0;
  402. crypto_pk_t *rsa_pubkey = NULL;
  403. tor_assert(!allow_annotations || !prepend_annotations);
  404. if (!end) {
  405. end = s + strlen(s);
  406. }
  407. /* point 'end' to a point immediately after the final newline. */
  408. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  409. --end;
  410. area = memarea_new();
  411. tokens = smartlist_new();
  412. if (prepend_annotations) {
  413. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  414. routerdesc_token_table,TS_NOCHECK)) {
  415. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  416. goto err;
  417. }
  418. }
  419. start_of_annotations = s;
  420. cp = tor_memstr(s, end-s, "\nrouter ");
  421. if (!cp) {
  422. if (end-s < 7 || strcmpstart(s, "router ")) {
  423. log_warn(LD_DIR, "No router keyword found.");
  424. goto err;
  425. }
  426. } else {
  427. s = cp+1;
  428. }
  429. if (start_of_annotations != s) { /* We have annotations */
  430. if (allow_annotations) {
  431. if (tokenize_string(area,start_of_annotations,s,tokens,
  432. routerdesc_token_table,TS_NOCHECK)) {
  433. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  434. goto err;
  435. }
  436. } else {
  437. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  438. "loaded from disk. Dropping it.");
  439. goto err;
  440. }
  441. }
  442. if (router_get_router_hash(s, end - s, digest) < 0) {
  443. log_warn(LD_DIR, "Couldn't compute router hash.");
  444. goto err;
  445. }
  446. {
  447. int flags = 0;
  448. if (allow_annotations)
  449. flags |= TS_ANNOTATIONS_OK;
  450. if (prepend_annotations)
  451. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  452. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  453. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  454. goto err;
  455. }
  456. }
  457. if (smartlist_len(tokens) < 2) {
  458. log_warn(LD_DIR, "Impossibly short router descriptor.");
  459. goto err;
  460. }
  461. tok = find_by_keyword(tokens, K_ROUTER);
  462. const int router_token_pos = smartlist_pos(tokens, tok);
  463. tor_assert(tok->n_args >= 5);
  464. router = tor_malloc_zero(sizeof(routerinfo_t));
  465. router->cert_expiration_time = TIME_MAX;
  466. router->cache_info.routerlist_index = -1;
  467. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  468. router->cache_info.signed_descriptor_len = end-s;
  469. if (cache_copy) {
  470. size_t len = router->cache_info.signed_descriptor_len +
  471. router->cache_info.annotations_len;
  472. char *signed_body =
  473. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  474. if (prepend_annotations) {
  475. memcpy(signed_body, prepend_annotations, prepend_len);
  476. signed_body += prepend_len;
  477. }
  478. /* This assertion will always succeed.
  479. * len == signed_desc_len + annotations_len
  480. * == end-s + s-start_of_annotations + prepend_len
  481. * == end-start_of_annotations + prepend_len
  482. * We already wrote prepend_len bytes into the buffer; now we're
  483. * writing end-start_of_annotations -NM. */
  484. tor_assert(signed_body+(end-start_of_annotations) ==
  485. router->cache_info.signed_descriptor_body+len);
  486. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  487. router->cache_info.signed_descriptor_body[len] = '\0';
  488. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  489. }
  490. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  491. router->nickname = tor_strdup(tok->args[0]);
  492. if (!is_legal_nickname(router->nickname)) {
  493. log_warn(LD_DIR,"Router nickname is invalid");
  494. goto err;
  495. }
  496. if (!tor_inet_aton(tok->args[1], &in)) {
  497. log_warn(LD_DIR,"Router address is not an IP address.");
  498. goto err;
  499. }
  500. router->addr = ntohl(in.s_addr);
  501. router->or_port =
  502. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  503. if (!ok) {
  504. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  505. goto err;
  506. }
  507. router->dir_port =
  508. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  509. if (!ok) {
  510. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  511. goto err;
  512. }
  513. tok = find_by_keyword(tokens, K_BANDWIDTH);
  514. tor_assert(tok->n_args >= 3);
  515. router->bandwidthrate = (int)
  516. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  517. if (!ok) {
  518. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  519. escaped(tok->args[0]));
  520. goto err;
  521. }
  522. router->bandwidthburst =
  523. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  524. if (!ok) {
  525. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  526. goto err;
  527. }
  528. router->bandwidthcapacity = (int)
  529. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  530. if (!ok) {
  531. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  532. goto err;
  533. }
  534. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  535. tor_assert(tok->n_args);
  536. router->purpose = router_purpose_from_string(tok->args[0]);
  537. } else {
  538. router->purpose = ROUTER_PURPOSE_GENERAL;
  539. }
  540. router->cache_info.send_unencrypted =
  541. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  542. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  543. tor_assert(tok->n_args >= 1);
  544. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  545. if (!ok) {
  546. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  547. goto err;
  548. }
  549. }
  550. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  551. tor_assert(tok->n_args >= 1);
  552. router->is_hibernating
  553. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  554. }
  555. tok = find_by_keyword(tokens, K_PUBLISHED);
  556. tor_assert(tok->n_args == 1);
  557. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  558. goto err;
  559. tok = find_by_keyword(tokens, K_ONION_KEY);
  560. if (!crypto_pk_public_exponent_ok(tok->key)) {
  561. log_warn(LD_DIR,
  562. "Relay's onion key had invalid exponent.");
  563. goto err;
  564. }
  565. router_set_rsa_onion_pkey(tok->key, &router->onion_pkey,
  566. &router->onion_pkey_len);
  567. crypto_pk_free(tok->key);
  568. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  569. curve25519_public_key_t k;
  570. tor_assert(tok->n_args >= 1);
  571. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  572. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  573. goto err;
  574. }
  575. router->onion_curve25519_pkey =
  576. tor_memdup(&k, sizeof(curve25519_public_key_t));
  577. }
  578. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  579. router->identity_pkey = tok->key;
  580. tok->key = NULL; /* Prevent free */
  581. if (crypto_pk_get_digest(router->identity_pkey,
  582. router->cache_info.identity_digest)) {
  583. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  584. }
  585. {
  586. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  587. *master_key_tok;
  588. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  589. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  590. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  591. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  592. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  593. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  594. !!cc_tap_tok + !!cc_ntor_tok;
  595. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  596. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  597. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  598. "cross-certification support");
  599. goto err;
  600. }
  601. if (master_key_tok && !ed_sig_tok) {
  602. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  603. "certificate");
  604. goto err;
  605. }
  606. if (ed_sig_tok) {
  607. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  608. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  609. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  610. (ed_cert_token_pos != router_token_pos + 1 &&
  611. ed_cert_token_pos != router_token_pos - 1)) {
  612. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  613. goto err;
  614. }
  615. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  616. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  617. goto err;
  618. }
  619. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  620. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  621. goto err;
  622. }
  623. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  624. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  625. "in decriptor");
  626. goto err;
  627. }
  628. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  629. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  630. "in decriptor");
  631. goto err;
  632. }
  633. if (strcmp(cc_ntor_tok->args[0], "0") &&
  634. strcmp(cc_ntor_tok->args[0], "1")) {
  635. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  636. goto err;
  637. }
  638. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  639. uint8_t d256[DIGEST256_LEN];
  640. const char *signed_start, *signed_end;
  641. tor_cert_t *cert = tor_cert_parse(
  642. (const uint8_t*)ed_cert_tok->object_body,
  643. ed_cert_tok->object_size);
  644. if (! cert) {
  645. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  646. goto err;
  647. }
  648. /* makes sure it gets freed. */
  649. router->cache_info.signing_key_cert = cert;
  650. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  651. ! cert->signing_key_included) {
  652. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  653. goto err;
  654. }
  655. if (master_key_tok) {
  656. /* This token is optional, but if it's present, it must match
  657. * the signature in the signing cert, or supplant it. */
  658. tor_assert(master_key_tok->n_args >= 1);
  659. ed25519_public_key_t pkey;
  660. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  661. log_warn(LD_DIR, "Can't parse ed25519 master key");
  662. goto err;
  663. }
  664. if (fast_memneq(&cert->signing_key.pubkey,
  665. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  666. log_warn(LD_DIR, "Ed25519 master key does not match "
  667. "key in certificate");
  668. goto err;
  669. }
  670. }
  671. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  672. cc_ntor_tok->object_size);
  673. if (!ntor_cc_cert) {
  674. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  675. goto err;
  676. }
  677. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  678. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  679. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  680. goto err;
  681. }
  682. ed25519_public_key_t ntor_cc_pk;
  683. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  684. router->onion_curve25519_pkey,
  685. ntor_cc_sign_bit)<0) {
  686. log_warn(LD_DIR, "Error converting onion key to ed25519");
  687. goto err;
  688. }
  689. if (router_get_hash_impl_helper(s, end-s, "router ",
  690. "\nrouter-sig-ed25519",
  691. ' ', LOG_WARN,
  692. &signed_start, &signed_end) < 0) {
  693. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  694. goto err;
  695. }
  696. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  697. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  698. strlen(ED_DESC_SIGNATURE_PREFIX));
  699. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  700. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  701. crypto_digest_free(d);
  702. ed25519_checkable_t check[3];
  703. int check_ok[3];
  704. time_t expires = TIME_MAX;
  705. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  706. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  707. goto err;
  708. }
  709. if (tor_cert_get_checkable_sig(&check[1],
  710. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  711. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  712. goto err;
  713. }
  714. if (ed25519_signature_from_base64(&check[2].signature,
  715. ed_sig_tok->args[0])<0) {
  716. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  717. goto err;
  718. }
  719. check[2].pubkey = &cert->signed_key;
  720. check[2].msg = d256;
  721. check[2].len = DIGEST256_LEN;
  722. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  723. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  724. goto err;
  725. }
  726. rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
  727. router->onion_pkey_len);
  728. if (check_tap_onion_key_crosscert(
  729. (const uint8_t*)cc_tap_tok->object_body,
  730. (int)cc_tap_tok->object_size,
  731. rsa_pubkey,
  732. &cert->signing_key,
  733. (const uint8_t*)router->cache_info.identity_digest)<0) {
  734. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  735. goto err;
  736. }
  737. /* We check this before adding it to the routerlist. */
  738. router->cert_expiration_time = expires;
  739. }
  740. }
  741. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  742. /* If there's a fingerprint line, it must match the identity digest. */
  743. char d[DIGEST_LEN];
  744. tor_assert(tok->n_args == 1);
  745. tor_strstrip(tok->args[0], " ");
  746. if (base16_decode(d, DIGEST_LEN,
  747. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  748. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  749. escaped(tok->args[0]));
  750. goto err;
  751. }
  752. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  753. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  754. tok->args[0]);
  755. goto err;
  756. }
  757. }
  758. {
  759. const char *version = NULL, *protocols = NULL;
  760. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  761. router->platform = tor_strdup(tok->args[0]);
  762. version = tok->args[0];
  763. }
  764. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  765. router->protocol_list = tor_strdup(tok->args[0]);
  766. protocols = tok->args[0];
  767. }
  768. summarize_protover_flags(&router->pv, protocols, version);
  769. }
  770. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  771. router->contact_info = tor_strdup(tok->args[0]);
  772. }
  773. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  774. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  775. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  776. "older Tors.");
  777. goto err;
  778. }
  779. {
  780. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  781. if (or_addresses) {
  782. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  783. &router->ipv6_orport);
  784. smartlist_free(or_addresses);
  785. }
  786. }
  787. exit_policy_tokens = find_all_exitpolicy(tokens);
  788. if (!smartlist_len(exit_policy_tokens)) {
  789. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  790. goto err;
  791. }
  792. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  793. if (router_add_exit_policy(router,t)<0) {
  794. log_warn(LD_DIR,"Error in exit policy");
  795. goto err;
  796. });
  797. policy_expand_private(&router->exit_policy);
  798. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  799. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  800. if (! router->ipv6_exit_policy) {
  801. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  802. goto err;
  803. }
  804. }
  805. if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
  806. (!router->ipv6_exit_policy ||
  807. short_policy_is_reject_star(router->ipv6_exit_policy)))
  808. router->policy_is_reject_star = 1;
  809. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  810. int i;
  811. router->declared_family = smartlist_new();
  812. for (i=0;i<tok->n_args;++i) {
  813. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  814. log_warn(LD_DIR, "Illegal nickname %s in family line",
  815. escaped(tok->args[i]));
  816. goto err;
  817. }
  818. smartlist_add_strdup(router->declared_family, tok->args[i]);
  819. }
  820. }
  821. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  822. router->caches_extra_info = 1;
  823. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  824. router->allow_single_hop_exits = 1;
  825. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  826. tor_assert(tok->n_args >= 1);
  827. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  828. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  829. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  830. log_warn(LD_DIR,"Invalid extra info digest");
  831. }
  832. } else {
  833. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  834. }
  835. if (tok->n_args >= 2) {
  836. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  837. tok->args[1]) < 0) {
  838. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  839. escaped(tok->args[1]));
  840. }
  841. }
  842. }
  843. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  844. router->wants_to_be_hs_dir = 1;
  845. }
  846. /* This router accepts tunnelled directory requests via begindir if it has
  847. * an open dirport or it included "tunnelled-dir-server". */
  848. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  849. router->supports_tunnelled_dir_requests = 1;
  850. }
  851. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  852. if (!router->or_port) {
  853. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  854. goto err;
  855. }
  856. /* We've checked everything that's covered by the hash. */
  857. can_dl_again = 1;
  858. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  859. "router descriptor") < 0)
  860. goto err;
  861. if (!router->platform) {
  862. router->platform = tor_strdup("<unknown>");
  863. }
  864. goto done;
  865. err:
  866. dump_desc(s_dup, "router descriptor");
  867. routerinfo_free(router);
  868. router = NULL;
  869. done:
  870. crypto_pk_free(rsa_pubkey);
  871. tor_cert_free(ntor_cc_cert);
  872. if (tokens) {
  873. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  874. smartlist_free(tokens);
  875. }
  876. smartlist_free(exit_policy_tokens);
  877. if (area) {
  878. DUMP_AREA(area, "routerinfo");
  879. memarea_drop_all(area);
  880. }
  881. if (can_dl_again_out)
  882. *can_dl_again_out = can_dl_again;
  883. return router;
  884. }
  885. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  886. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  887. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  888. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  889. * as a map from router identity to routerinfo_t when looking up signing keys.
  890. *
  891. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  892. * if it's okay to try to download an extrainfo with this same digest again,
  893. * and 0 if it isn't. (It might not be okay to download it again if part of
  894. * the part covered by the digest is invalid.)
  895. */
  896. extrainfo_t *
  897. extrainfo_parse_entry_from_string(const char *s, const char *end,
  898. int cache_copy, struct digest_ri_map_t *routermap,
  899. int *can_dl_again_out)
  900. {
  901. extrainfo_t *extrainfo = NULL;
  902. char digest[128];
  903. smartlist_t *tokens = NULL;
  904. directory_token_t *tok;
  905. crypto_pk_t *key = NULL;
  906. routerinfo_t *router = NULL;
  907. memarea_t *area = NULL;
  908. const char *s_dup = s;
  909. /* Do not set this to '1' until we have parsed everything that we intend to
  910. * parse that's covered by the hash. */
  911. int can_dl_again = 0;
  912. if (BUG(s == NULL))
  913. return NULL;
  914. if (!end) {
  915. end = s + strlen(s);
  916. }
  917. /* point 'end' to a point immediately after the final newline. */
  918. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  919. --end;
  920. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  921. log_warn(LD_DIR, "Couldn't compute router hash.");
  922. goto err;
  923. }
  924. tokens = smartlist_new();
  925. area = memarea_new();
  926. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  927. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  928. goto err;
  929. }
  930. if (smartlist_len(tokens) < 2) {
  931. log_warn(LD_DIR, "Impossibly short extra-info document.");
  932. goto err;
  933. }
  934. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  935. tok = smartlist_get(tokens,0);
  936. if (tok->tp != K_EXTRA_INFO) {
  937. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  938. goto err;
  939. }
  940. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  941. extrainfo->cache_info.is_extrainfo = 1;
  942. if (cache_copy)
  943. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  944. extrainfo->cache_info.signed_descriptor_len = end-s;
  945. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  946. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  947. tor_assert(tok->n_args >= 2);
  948. if (!is_legal_nickname(tok->args[0])) {
  949. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  950. goto err;
  951. }
  952. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  953. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  954. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  955. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  956. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  957. escaped(tok->args[1]));
  958. goto err;
  959. }
  960. tok = find_by_keyword(tokens, K_PUBLISHED);
  961. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  962. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  963. escaped(tok->args[0]));
  964. goto err;
  965. }
  966. {
  967. directory_token_t *ed_sig_tok, *ed_cert_tok;
  968. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  969. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  970. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  971. if (n_ed_toks != 0 && n_ed_toks != 2) {
  972. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  973. "cross-certification support");
  974. goto err;
  975. }
  976. if (ed_sig_tok) {
  977. tor_assert(ed_cert_tok);
  978. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  979. if (ed_cert_token_pos != 1) {
  980. /* Accept this in position 0 XXXX */
  981. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  982. goto err;
  983. }
  984. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  985. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  986. goto err;
  987. }
  988. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  989. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  990. goto err;
  991. }
  992. uint8_t d256[DIGEST256_LEN];
  993. const char *signed_start, *signed_end;
  994. tor_cert_t *cert = tor_cert_parse(
  995. (const uint8_t*)ed_cert_tok->object_body,
  996. ed_cert_tok->object_size);
  997. if (! cert) {
  998. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  999. goto err;
  1000. }
  1001. /* makes sure it gets freed. */
  1002. extrainfo->cache_info.signing_key_cert = cert;
  1003. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1004. ! cert->signing_key_included) {
  1005. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1006. goto err;
  1007. }
  1008. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1009. "\nrouter-sig-ed25519",
  1010. ' ', LOG_WARN,
  1011. &signed_start, &signed_end) < 0) {
  1012. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1013. goto err;
  1014. }
  1015. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1016. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1017. strlen(ED_DESC_SIGNATURE_PREFIX));
  1018. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1019. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1020. crypto_digest_free(d);
  1021. ed25519_checkable_t check[2];
  1022. int check_ok[2];
  1023. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  1024. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1025. goto err;
  1026. }
  1027. if (ed25519_signature_from_base64(&check[1].signature,
  1028. ed_sig_tok->args[0])<0) {
  1029. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1030. goto err;
  1031. }
  1032. check[1].pubkey = &cert->signed_key;
  1033. check[1].msg = d256;
  1034. check[1].len = DIGEST256_LEN;
  1035. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1036. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1037. goto err;
  1038. }
  1039. /* We don't check the certificate expiration time: checking that it
  1040. * matches the cert in the router descriptor is adequate. */
  1041. }
  1042. }
  1043. /* We've checked everything that's covered by the hash. */
  1044. can_dl_again = 1;
  1045. if (routermap &&
  1046. (router = digestmap_get((digestmap_t*)routermap,
  1047. extrainfo->cache_info.identity_digest))) {
  1048. key = router->identity_pkey;
  1049. }
  1050. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1051. if (strcmp(tok->object_type, "SIGNATURE") ||
  1052. tok->object_size < 128 || tok->object_size > 512) {
  1053. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1054. goto err;
  1055. }
  1056. if (key) {
  1057. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1058. "extra-info") < 0)
  1059. goto err;
  1060. if (router)
  1061. extrainfo->cache_info.send_unencrypted =
  1062. router->cache_info.send_unencrypted;
  1063. } else {
  1064. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1065. tok->object_size);
  1066. extrainfo->pending_sig_len = tok->object_size;
  1067. }
  1068. goto done;
  1069. err:
  1070. dump_desc(s_dup, "extra-info descriptor");
  1071. extrainfo_free(extrainfo);
  1072. extrainfo = NULL;
  1073. done:
  1074. if (tokens) {
  1075. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1076. smartlist_free(tokens);
  1077. }
  1078. if (area) {
  1079. DUMP_AREA(area, "extrainfo");
  1080. memarea_drop_all(area);
  1081. }
  1082. if (can_dl_again_out)
  1083. *can_dl_again_out = can_dl_again;
  1084. return extrainfo;
  1085. }
  1086. /** Summarize the protocols listed in <b>protocols</b> into <b>out</b>,
  1087. * falling back or correcting them based on <b>version</b> as appropriate.
  1088. */
  1089. void
  1090. summarize_protover_flags(protover_summary_flags_t *out,
  1091. const char *protocols,
  1092. const char *version)
  1093. {
  1094. tor_assert(out);
  1095. memset(out, 0, sizeof(*out));
  1096. if (protocols) {
  1097. out->protocols_known = 1;
  1098. out->supports_extend2_cells =
  1099. protocol_list_supports_protocol(protocols, PRT_RELAY, 2);
  1100. out->supports_ed25519_link_handshake_compat =
  1101. protocol_list_supports_protocol(protocols, PRT_LINKAUTH, 3);
  1102. out->supports_ed25519_link_handshake_any =
  1103. protocol_list_supports_protocol_or_later(protocols, PRT_LINKAUTH, 3);
  1104. out->supports_ed25519_hs_intro =
  1105. protocol_list_supports_protocol(protocols, PRT_HSINTRO, 4);
  1106. out->supports_v3_hsdir =
  1107. protocol_list_supports_protocol(protocols, PRT_HSDIR,
  1108. PROTOVER_HSDIR_V3);
  1109. out->supports_v3_rendezvous_point =
  1110. protocol_list_supports_protocol(protocols, PRT_HSREND,
  1111. PROTOVER_HS_RENDEZVOUS_POINT_V3);
  1112. }
  1113. if (version && !strcmpstart(version, "Tor ")) {
  1114. if (!out->protocols_known) {
  1115. /* The version is a "Tor" version, and where there is no
  1116. * list of protocol versions that we should be looking at instead. */
  1117. out->supports_extend2_cells =
  1118. tor_version_as_new_as(version, "0.2.4.8-alpha");
  1119. out->protocols_known = 1;
  1120. } else {
  1121. /* Bug #22447 forces us to filter on this version. */
  1122. if (!tor_version_as_new_as(version, "0.3.0.8")) {
  1123. out->supports_v3_hsdir = 0;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. /** Parse the addr policy in the string <b>s</b> and return it. If
  1129. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1130. * ADDR_POLICY_REJECT) for items that specify no action.
  1131. *
  1132. * Returns NULL on policy errors.
  1133. *
  1134. * Set *<b>malformed_list</b> to true if the entire policy list should be
  1135. * discarded. Otherwise, set it to false, and only this item should be ignored
  1136. * on error - the rest of the policy list can continue to be processed and
  1137. * used.
  1138. *
  1139. * The addr_policy_t returned by this function can have its address set to
  1140. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  1141. * of AF_INET and AF_INET6 items.
  1142. */
  1143. MOCK_IMPL(addr_policy_t *,
  1144. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  1145. int *malformed_list))
  1146. {
  1147. directory_token_t *tok = NULL;
  1148. const char *cp, *eos;
  1149. /* Longest possible policy is
  1150. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  1151. * which contains a max-length IPv6 address, plus 26 characters.
  1152. * But note that there can be an arbitrary amount of space between the
  1153. * accept and the address:mask/port element.
  1154. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  1155. * IPv6 address. But making the buffer shorter might cause valid long lines,
  1156. * which parsed in previous versions, to fail to parse in new versions.
  1157. * (These lines would have to have excessive amounts of whitespace.) */
  1158. char line[TOR_ADDR_BUF_LEN*2 + 32];
  1159. addr_policy_t *r;
  1160. memarea_t *area = NULL;
  1161. tor_assert(malformed_list);
  1162. *malformed_list = 0;
  1163. s = eat_whitespace(s);
  1164. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  1165. * and ":" (port separator) are ambiguous */
  1166. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  1167. if (tor_snprintf(line, sizeof(line), "%s %s",
  1168. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  1169. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  1170. return NULL;
  1171. }
  1172. cp = line;
  1173. tor_strlower(line);
  1174. } else { /* assume an already well-formed address policy line */
  1175. cp = s;
  1176. }
  1177. eos = cp + strlen(cp);
  1178. area = memarea_new();
  1179. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  1180. if (tok->tp == ERR_) {
  1181. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1182. goto err;
  1183. }
  1184. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  1185. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  1186. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1187. goto err;
  1188. }
  1189. /* Use the extended interpretation of accept/reject *,
  1190. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  1191. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  1192. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  1193. if (!r) {
  1194. goto err;
  1195. }
  1196. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  1197. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  1198. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  1199. * either an IPv4 or IPv6 address. */
  1200. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  1201. tor_addr_family(&r->addr) != AF_INET6) {
  1202. /* This is a non-fatal error, just ignore this one entry. */
  1203. *malformed_list = 0;
  1204. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  1205. "exit policy. Ignoring, but continuing to parse rules. (Use "
  1206. "accept/reject with IPv4 addresses.)",
  1207. tok->n_args == 1 ? tok->args[0] : "");
  1208. addr_policy_free(r);
  1209. r = NULL;
  1210. goto done;
  1211. }
  1212. goto done;
  1213. err:
  1214. *malformed_list = 1;
  1215. r = NULL;
  1216. done:
  1217. token_clear(tok);
  1218. if (area) {
  1219. DUMP_AREA(area, "policy item");
  1220. memarea_drop_all(area);
  1221. }
  1222. return r;
  1223. }
  1224. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1225. * <b>router</b>. Return 0 on success, -1 on failure. */
  1226. static int
  1227. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1228. {
  1229. addr_policy_t *newe;
  1230. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  1231. newe = router_parse_addr_policy(tok, 0);
  1232. if (!newe)
  1233. return -1;
  1234. if (! router->exit_policy)
  1235. router->exit_policy = smartlist_new();
  1236. /* Ensure that in descriptors, accept/reject fields are followed by
  1237. * IPv4 addresses, and accept6/reject6 fields are followed by
  1238. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  1239. * accept/reject followed by IPv6. */
  1240. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  1241. tor_addr_family(&newe->addr) == AF_INET)
  1242. ||
  1243. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  1244. tor_addr_family(&newe->addr) == AF_INET6)) {
  1245. /* There's nothing the user can do about other relays' descriptors,
  1246. * so we don't provide usage advice here. */
  1247. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  1248. "policy '%s'. Discarding entire router descriptor.",
  1249. tok->n_args == 1 ? tok->args[0] : "");
  1250. addr_policy_free(newe);
  1251. return -1;
  1252. }
  1253. smartlist_add(router->exit_policy, newe);
  1254. return 0;
  1255. }
  1256. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  1257. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  1258. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  1259. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  1260. * policies */
  1261. static addr_policy_t *
  1262. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  1263. {
  1264. addr_policy_t newe;
  1265. char *arg;
  1266. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  1267. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  1268. if (tok->n_args != 1)
  1269. return NULL;
  1270. arg = tok->args[0];
  1271. if (!strcmpstart(arg,"private"))
  1272. return router_parse_addr_policy_private(tok);
  1273. memset(&newe, 0, sizeof(newe));
  1274. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  1275. newe.policy_type = ADDR_POLICY_REJECT;
  1276. else
  1277. newe.policy_type = ADDR_POLICY_ACCEPT;
  1278. /* accept6/reject6 * produces an IPv6 wildcard address only.
  1279. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  1280. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  1281. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  1282. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  1283. }
  1284. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  1285. &newe.prt_min, &newe.prt_max) < 0) {
  1286. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1287. return NULL;
  1288. }
  1289. return addr_policy_get_canonical_entry(&newe);
  1290. }
  1291. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  1292. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1293. * router descriptors until earlier versions are obsolete.
  1294. *
  1295. * accept/reject and accept6/reject6 private all produce rules for both
  1296. * IPv4 and IPv6 addresses.
  1297. */
  1298. static addr_policy_t *
  1299. router_parse_addr_policy_private(directory_token_t *tok)
  1300. {
  1301. const char *arg;
  1302. uint16_t port_min, port_max;
  1303. addr_policy_t result;
  1304. arg = tok->args[0];
  1305. if (strcmpstart(arg, "private"))
  1306. return NULL;
  1307. arg += strlen("private");
  1308. arg = (char*) eat_whitespace(arg);
  1309. if (!arg || *arg != ':')
  1310. return NULL;
  1311. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1312. return NULL;
  1313. memset(&result, 0, sizeof(result));
  1314. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  1315. result.policy_type = ADDR_POLICY_REJECT;
  1316. else
  1317. result.policy_type = ADDR_POLICY_ACCEPT;
  1318. result.is_private = 1;
  1319. result.prt_min = port_min;
  1320. result.prt_max = port_max;
  1321. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  1322. log_warn(LD_GENERAL,
  1323. "'%s' expands into rules which apply to all private IPv4 and "
  1324. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  1325. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  1326. }
  1327. return addr_policy_get_canonical_entry(&result);
  1328. }
  1329. /** Return a newly allocated smartlist of all accept or reject tokens in
  1330. * <b>s</b>.
  1331. */
  1332. static smartlist_t *
  1333. find_all_exitpolicy(smartlist_t *s)
  1334. {
  1335. smartlist_t *out = smartlist_new();
  1336. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1337. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  1338. t->tp == K_REJECT || t->tp == K_REJECT6)
  1339. smartlist_add(out,t));
  1340. return out;
  1341. }
  1342. /** Called on startup; right now we just handle scanning the unparseable
  1343. * descriptor dumps, but hang anything else we might need to do in the
  1344. * future here as well.
  1345. */
  1346. void
  1347. routerparse_init(void)
  1348. {
  1349. /*
  1350. * Check both if the sandbox is active and whether it's configured; no
  1351. * point in loading all that if we won't be able to use it after the
  1352. * sandbox becomes active.
  1353. */
  1354. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  1355. dump_desc_init();
  1356. }
  1357. }
  1358. /** Clean up all data structures used by routerparse.c at exit */
  1359. void
  1360. routerparse_free_all(void)
  1361. {
  1362. dump_desc_fifo_cleanup();
  1363. }