routerparse.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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. /** Parse the addr policy in the string <b>s</b> and return it. If
  1087. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1088. * ADDR_POLICY_REJECT) for items that specify no action.
  1089. *
  1090. * Returns NULL on policy errors.
  1091. *
  1092. * Set *<b>malformed_list</b> to true if the entire policy list should be
  1093. * discarded. Otherwise, set it to false, and only this item should be ignored
  1094. * on error - the rest of the policy list can continue to be processed and
  1095. * used.
  1096. *
  1097. * The addr_policy_t returned by this function can have its address set to
  1098. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  1099. * of AF_INET and AF_INET6 items.
  1100. */
  1101. MOCK_IMPL(addr_policy_t *,
  1102. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  1103. int *malformed_list))
  1104. {
  1105. directory_token_t *tok = NULL;
  1106. const char *cp, *eos;
  1107. /* Longest possible policy is
  1108. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  1109. * which contains a max-length IPv6 address, plus 26 characters.
  1110. * But note that there can be an arbitrary amount of space between the
  1111. * accept and the address:mask/port element.
  1112. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  1113. * IPv6 address. But making the buffer shorter might cause valid long lines,
  1114. * which parsed in previous versions, to fail to parse in new versions.
  1115. * (These lines would have to have excessive amounts of whitespace.) */
  1116. char line[TOR_ADDR_BUF_LEN*2 + 32];
  1117. addr_policy_t *r;
  1118. memarea_t *area = NULL;
  1119. tor_assert(malformed_list);
  1120. *malformed_list = 0;
  1121. s = eat_whitespace(s);
  1122. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  1123. * and ":" (port separator) are ambiguous */
  1124. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  1125. if (tor_snprintf(line, sizeof(line), "%s %s",
  1126. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  1127. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  1128. return NULL;
  1129. }
  1130. cp = line;
  1131. tor_strlower(line);
  1132. } else { /* assume an already well-formed address policy line */
  1133. cp = s;
  1134. }
  1135. eos = cp + strlen(cp);
  1136. area = memarea_new();
  1137. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  1138. if (tok->tp == ERR_) {
  1139. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1140. goto err;
  1141. }
  1142. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  1143. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  1144. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1145. goto err;
  1146. }
  1147. /* Use the extended interpretation of accept/reject *,
  1148. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  1149. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  1150. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  1151. if (!r) {
  1152. goto err;
  1153. }
  1154. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  1155. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  1156. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  1157. * either an IPv4 or IPv6 address. */
  1158. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  1159. tor_addr_family(&r->addr) != AF_INET6) {
  1160. /* This is a non-fatal error, just ignore this one entry. */
  1161. *malformed_list = 0;
  1162. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  1163. "exit policy. Ignoring, but continuing to parse rules. (Use "
  1164. "accept/reject with IPv4 addresses.)",
  1165. tok->n_args == 1 ? tok->args[0] : "");
  1166. addr_policy_free(r);
  1167. r = NULL;
  1168. goto done;
  1169. }
  1170. goto done;
  1171. err:
  1172. *malformed_list = 1;
  1173. r = NULL;
  1174. done:
  1175. token_clear(tok);
  1176. if (area) {
  1177. DUMP_AREA(area, "policy item");
  1178. memarea_drop_all(area);
  1179. }
  1180. return r;
  1181. }
  1182. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1183. * <b>router</b>. Return 0 on success, -1 on failure. */
  1184. static int
  1185. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1186. {
  1187. addr_policy_t *newe;
  1188. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  1189. newe = router_parse_addr_policy(tok, 0);
  1190. if (!newe)
  1191. return -1;
  1192. if (! router->exit_policy)
  1193. router->exit_policy = smartlist_new();
  1194. /* Ensure that in descriptors, accept/reject fields are followed by
  1195. * IPv4 addresses, and accept6/reject6 fields are followed by
  1196. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  1197. * accept/reject followed by IPv6. */
  1198. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  1199. tor_addr_family(&newe->addr) == AF_INET)
  1200. ||
  1201. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  1202. tor_addr_family(&newe->addr) == AF_INET6)) {
  1203. /* There's nothing the user can do about other relays' descriptors,
  1204. * so we don't provide usage advice here. */
  1205. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  1206. "policy '%s'. Discarding entire router descriptor.",
  1207. tok->n_args == 1 ? tok->args[0] : "");
  1208. addr_policy_free(newe);
  1209. return -1;
  1210. }
  1211. smartlist_add(router->exit_policy, newe);
  1212. return 0;
  1213. }
  1214. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  1215. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  1216. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  1217. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  1218. * policies */
  1219. static addr_policy_t *
  1220. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  1221. {
  1222. addr_policy_t newe;
  1223. char *arg;
  1224. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  1225. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  1226. if (tok->n_args != 1)
  1227. return NULL;
  1228. arg = tok->args[0];
  1229. if (!strcmpstart(arg,"private"))
  1230. return router_parse_addr_policy_private(tok);
  1231. memset(&newe, 0, sizeof(newe));
  1232. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  1233. newe.policy_type = ADDR_POLICY_REJECT;
  1234. else
  1235. newe.policy_type = ADDR_POLICY_ACCEPT;
  1236. /* accept6/reject6 * produces an IPv6 wildcard address only.
  1237. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  1238. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  1239. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  1240. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  1241. }
  1242. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  1243. &newe.prt_min, &newe.prt_max) < 0) {
  1244. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1245. return NULL;
  1246. }
  1247. return addr_policy_get_canonical_entry(&newe);
  1248. }
  1249. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  1250. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1251. * router descriptors until earlier versions are obsolete.
  1252. *
  1253. * accept/reject and accept6/reject6 private all produce rules for both
  1254. * IPv4 and IPv6 addresses.
  1255. */
  1256. static addr_policy_t *
  1257. router_parse_addr_policy_private(directory_token_t *tok)
  1258. {
  1259. const char *arg;
  1260. uint16_t port_min, port_max;
  1261. addr_policy_t result;
  1262. arg = tok->args[0];
  1263. if (strcmpstart(arg, "private"))
  1264. return NULL;
  1265. arg += strlen("private");
  1266. arg = (char*) eat_whitespace(arg);
  1267. if (!arg || *arg != ':')
  1268. return NULL;
  1269. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1270. return NULL;
  1271. memset(&result, 0, sizeof(result));
  1272. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  1273. result.policy_type = ADDR_POLICY_REJECT;
  1274. else
  1275. result.policy_type = ADDR_POLICY_ACCEPT;
  1276. result.is_private = 1;
  1277. result.prt_min = port_min;
  1278. result.prt_max = port_max;
  1279. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  1280. log_warn(LD_GENERAL,
  1281. "'%s' expands into rules which apply to all private IPv4 and "
  1282. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  1283. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  1284. }
  1285. return addr_policy_get_canonical_entry(&result);
  1286. }
  1287. /** Return a newly allocated smartlist of all accept or reject tokens in
  1288. * <b>s</b>.
  1289. */
  1290. static smartlist_t *
  1291. find_all_exitpolicy(smartlist_t *s)
  1292. {
  1293. smartlist_t *out = smartlist_new();
  1294. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1295. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  1296. t->tp == K_REJECT || t->tp == K_REJECT6)
  1297. smartlist_add(out,t));
  1298. return out;
  1299. }
  1300. /** Called on startup; right now we just handle scanning the unparseable
  1301. * descriptor dumps, but hang anything else we might need to do in the
  1302. * future here as well.
  1303. */
  1304. void
  1305. routerparse_init(void)
  1306. {
  1307. /*
  1308. * Check both if the sandbox is active and whether it's configured; no
  1309. * point in loading all that if we won't be able to use it after the
  1310. * sandbox becomes active.
  1311. */
  1312. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  1313. dump_desc_init();
  1314. }
  1315. }
  1316. /** Clean up all data structures used by routerparse.c at exit */
  1317. void
  1318. routerparse_free_all(void)
  1319. {
  1320. dump_desc_fifo_cleanup();
  1321. }