routerparse.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. #define EXPOSE_ROUTERDESC_TOKEN_TABLE
  53. #include "core/or/or.h"
  54. #include "app/config/config.h"
  55. #include "core/or/circuitstats.h"
  56. #include "core/or/policies.h"
  57. #include "core/or/protover.h"
  58. #include "feature/client/entrynodes.h"
  59. #include "feature/dirauth/shared_random.h"
  60. #include "feature/dircommon/voting_schedule.h"
  61. #include "feature/dirparse/parsecommon.h"
  62. #include "feature/dirparse/policy_parse.h"
  63. #include "feature/dirparse/routerparse.h"
  64. #include "feature/hs_common/shared_random_client.h"
  65. #include "feature/nodelist/authcert.h"
  66. #include "feature/nodelist/describe.h"
  67. #include "feature/nodelist/microdesc.h"
  68. #include "feature/nodelist/networkstatus.h"
  69. #include "feature/nodelist/nickname.h"
  70. #include "feature/nodelist/routerinfo.h"
  71. #include "feature/nodelist/routerlist.h"
  72. #include "feature/nodelist/torcert.h"
  73. #include "feature/relay/router.h"
  74. #include "feature/relay/routerkeys.h"
  75. #include "feature/rend/rendcommon.h"
  76. #include "feature/stats/rephist.h"
  77. #include "lib/crypt_ops/crypto_format.h"
  78. #include "lib/crypt_ops/crypto_util.h"
  79. #include "lib/memarea/memarea.h"
  80. #include "lib/sandbox/sandbox.h"
  81. #include "feature/dirparse/authcert_parse.h"
  82. #include "feature/dirparse/sigcommon.h"
  83. #include "feature/dirparse/unparseable.h"
  84. #include "feature/dirauth/dirvote.h"
  85. #include "core/or/addr_policy_st.h"
  86. #include "feature/nodelist/authority_cert_st.h"
  87. #include "feature/nodelist/document_signature_st.h"
  88. #include "core/or/extend_info_st.h"
  89. #include "feature/nodelist/extrainfo_st.h"
  90. #include "feature/nodelist/microdesc_st.h"
  91. #include "feature/nodelist/networkstatus_st.h"
  92. #include "feature/nodelist/networkstatus_voter_info_st.h"
  93. #include "feature/dirauth/ns_detached_signatures_st.h"
  94. #include "feature/rend/rend_authorized_client_st.h"
  95. #include "feature/rend/rend_intro_point_st.h"
  96. #include "feature/rend/rend_service_descriptor_st.h"
  97. #include "feature/nodelist/routerinfo_st.h"
  98. #include "feature/nodelist/routerlist_st.h"
  99. #include "core/or/tor_version_st.h"
  100. #include "feature/dirauth/vote_microdesc_hash_st.h"
  101. #include "feature/nodelist/vote_routerstatus_st.h"
  102. #include "lib/container/bloomfilt.h"
  103. #undef log
  104. #include <math.h>
  105. /****************************************************************************/
  106. /** List of tokens recognized in router descriptors */
  107. const token_rule_t routerdesc_token_table[] = {
  108. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  109. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  110. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  111. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  112. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  113. T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
  114. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  115. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  116. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  117. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  118. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  119. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  120. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  121. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  122. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  123. T01("proto", K_PROTO, CONCAT_ARGS, NO_OBJ ),
  124. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  125. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  126. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  127. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  128. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  129. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  130. T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
  131. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  132. T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
  133. T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
  134. EQ(1), NEED_OBJ ),
  135. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  136. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  137. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  138. T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
  139. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  140. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  141. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  142. T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
  143. END_OF_TABLE
  144. };
  145. /** List of tokens recognized in extra-info documents. */
  146. static token_rule_t extrainfo_token_table[] = {
  147. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  148. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  149. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  150. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  151. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  152. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  153. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  154. T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
  155. T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
  156. T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
  157. T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
  158. T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
  159. T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
  160. T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
  161. T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
  162. T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
  163. T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
  164. T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
  165. T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
  166. T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
  167. T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
  168. T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
  169. T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
  170. T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
  171. T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
  172. T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
  173. T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
  174. T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
  175. T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
  176. T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
  177. T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
  178. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  179. END_OF_TABLE
  180. };
  181. #undef T
  182. /* static function prototypes */
  183. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  184. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  185. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  186. * <b>s</b>. Return 0 on success, -1 on failure.
  187. */
  188. int
  189. router_get_router_hash(const char *s, size_t s_len, char *digest)
  190. {
  191. return router_get_hash_impl(s, s_len, digest,
  192. "router ","\nrouter-signature", '\n',
  193. DIGEST_SHA1);
  194. }
  195. /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
  196. * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
  197. int
  198. router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
  199. {
  200. return router_get_hash_impl(s, s_len, digest, "extra-info",
  201. "\nrouter-signature",'\n', DIGEST_SHA1);
  202. }
  203. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  204. * or to the first of the annotations proceeding the next router or
  205. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  206. * we found an extrainfo, or false if found a router. Do not scan beyond
  207. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  208. static int
  209. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  210. const char *eos,
  211. int *is_extrainfo_out)
  212. {
  213. const char *annotations = NULL;
  214. const char *s = *s_ptr;
  215. s = eat_whitespace_eos(s, eos);
  216. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  217. /* We're at the start of a line. */
  218. tor_assert(*s != '\n');
  219. if (*s == '@' && !annotations) {
  220. annotations = s;
  221. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  222. *s_ptr = annotations ? annotations : s;
  223. *is_extrainfo_out = 0;
  224. return 0;
  225. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  226. *s_ptr = annotations ? annotations : s;
  227. *is_extrainfo_out = 1;
  228. return 0;
  229. }
  230. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  231. break;
  232. s = eat_whitespace_eos(s, eos);
  233. }
  234. return -1;
  235. }
  236. /** Given a string *<b>s</b> containing a concatenated sequence of router
  237. * descriptors (or extra-info documents if <b>want_extrainfo</b> is set),
  238. * parses them and stores the result in <b>dest</b>. All routers are marked
  239. * running and valid. Advances *s to a point immediately following the last
  240. * router entry. Ignore any trailing router entries that are not complete.
  241. *
  242. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  243. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  244. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  245. *
  246. * Returns 0 on success and -1 on failure. Adds a digest to
  247. * <b>invalid_digests_out</b> for every entry that was unparseable or
  248. * invalid. (This may cause duplicate entries.)
  249. */
  250. int
  251. router_parse_list_from_string(const char **s, const char *eos,
  252. smartlist_t *dest,
  253. saved_location_t saved_location,
  254. int want_extrainfo,
  255. int allow_annotations,
  256. const char *prepend_annotations,
  257. smartlist_t *invalid_digests_out)
  258. {
  259. routerinfo_t *router;
  260. extrainfo_t *extrainfo;
  261. signed_descriptor_t *signed_desc = NULL;
  262. void *elt;
  263. const char *end, *start;
  264. int have_extrainfo;
  265. tor_assert(s);
  266. tor_assert(*s);
  267. tor_assert(dest);
  268. start = *s;
  269. if (!eos)
  270. eos = *s + strlen(*s);
  271. tor_assert(eos >= *s);
  272. while (1) {
  273. char raw_digest[DIGEST_LEN];
  274. int have_raw_digest = 0;
  275. int dl_again = 0;
  276. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  277. break;
  278. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  279. if (end)
  280. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  281. if (end)
  282. end += strlen("\n-----END SIGNATURE-----\n");
  283. if (!end)
  284. break;
  285. elt = NULL;
  286. if (have_extrainfo && want_extrainfo) {
  287. routerlist_t *rl = router_get_routerlist();
  288. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  289. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  290. saved_location != SAVED_IN_CACHE,
  291. rl->identity_map, &dl_again);
  292. if (extrainfo) {
  293. signed_desc = &extrainfo->cache_info;
  294. elt = extrainfo;
  295. }
  296. } else if (!have_extrainfo && !want_extrainfo) {
  297. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  298. router = router_parse_entry_from_string(*s, end,
  299. saved_location != SAVED_IN_CACHE,
  300. allow_annotations,
  301. prepend_annotations, &dl_again);
  302. if (router) {
  303. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  304. router_describe(router),
  305. router_purpose_to_string(router->purpose));
  306. signed_desc = &router->cache_info;
  307. elt = router;
  308. }
  309. }
  310. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  311. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  312. }
  313. if (!elt) {
  314. *s = end;
  315. continue;
  316. }
  317. if (saved_location != SAVED_NOWHERE) {
  318. tor_assert(signed_desc);
  319. signed_desc->saved_location = saved_location;
  320. signed_desc->saved_offset = *s - start;
  321. }
  322. *s = end;
  323. smartlist_add(dest, elt);
  324. }
  325. return 0;
  326. }
  327. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  328. * with at least one argument (use GE(1) in setup). If found, store
  329. * address and port number to <b>addr_out</b> and
  330. * <b>port_out</b>. Return number of OR ports found. */
  331. int
  332. find_single_ipv6_orport(const smartlist_t *list,
  333. tor_addr_t *addr_out,
  334. uint16_t *port_out)
  335. {
  336. int ret = 0;
  337. tor_assert(list != NULL);
  338. tor_assert(addr_out != NULL);
  339. tor_assert(port_out != NULL);
  340. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  341. tor_addr_t a;
  342. maskbits_t bits;
  343. uint16_t port_min, port_max;
  344. tor_assert(t->n_args >= 1);
  345. /* XXXX Prop186 the full spec allows much more than this. */
  346. if (tor_addr_parse_mask_ports(t->args[0], 0,
  347. &a, &bits, &port_min,
  348. &port_max) == AF_INET6 &&
  349. bits == 128 &&
  350. port_min == port_max) {
  351. /* Okay, this is one we can understand. Use it and ignore
  352. any potential more addresses in list. */
  353. tor_addr_copy(addr_out, &a);
  354. *port_out = port_min;
  355. ret = 1;
  356. break;
  357. }
  358. } SMARTLIST_FOREACH_END(t);
  359. return ret;
  360. }
  361. /** Helper function: reads a single router entry from *<b>s</b> ...
  362. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  363. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  364. * s through end into the signed_descriptor_body of the resulting
  365. * routerinfo_t.
  366. *
  367. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  368. *
  369. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  370. * before the router; if it's false, reject the router if it's annotated. If
  371. * <b>prepend_annotations</b> is set, it should contain some annotations:
  372. * append them to the front of the router before parsing it, and keep them
  373. * around when caching the router.
  374. *
  375. * Only one of allow_annotations and prepend_annotations may be set.
  376. *
  377. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  378. * if it's okay to try to download a descriptor with this same digest again,
  379. * and 0 if it isn't. (It might not be okay to download it again if part of
  380. * the part covered by the digest is invalid.)
  381. */
  382. routerinfo_t *
  383. router_parse_entry_from_string(const char *s, const char *end,
  384. int cache_copy, int allow_annotations,
  385. const char *prepend_annotations,
  386. int *can_dl_again_out)
  387. {
  388. routerinfo_t *router = NULL;
  389. char digest[128];
  390. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  391. directory_token_t *tok;
  392. struct in_addr in;
  393. const char *start_of_annotations, *cp, *s_dup = s;
  394. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  395. int ok = 1;
  396. memarea_t *area = NULL;
  397. tor_cert_t *ntor_cc_cert = NULL;
  398. /* Do not set this to '1' until we have parsed everything that we intend to
  399. * parse that's covered by the hash. */
  400. int can_dl_again = 0;
  401. crypto_pk_t *rsa_pubkey = NULL;
  402. tor_assert(!allow_annotations || !prepend_annotations);
  403. if (!end) {
  404. end = s + strlen(s);
  405. }
  406. /* point 'end' to a point immediately after the final newline. */
  407. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  408. --end;
  409. area = memarea_new();
  410. tokens = smartlist_new();
  411. if (prepend_annotations) {
  412. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  413. routerdesc_token_table,TS_NOCHECK)) {
  414. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  415. goto err;
  416. }
  417. }
  418. start_of_annotations = s;
  419. cp = tor_memstr(s, end-s, "\nrouter ");
  420. if (!cp) {
  421. if (end-s < 7 || strcmpstart(s, "router ")) {
  422. log_warn(LD_DIR, "No router keyword found.");
  423. goto err;
  424. }
  425. } else {
  426. s = cp+1;
  427. }
  428. if (start_of_annotations != s) { /* We have annotations */
  429. if (allow_annotations) {
  430. if (tokenize_string(area,start_of_annotations,s,tokens,
  431. routerdesc_token_table,TS_NOCHECK)) {
  432. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  433. goto err;
  434. }
  435. } else {
  436. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  437. "loaded from disk. Dropping it.");
  438. goto err;
  439. }
  440. }
  441. if (router_get_router_hash(s, end - s, digest) < 0) {
  442. log_warn(LD_DIR, "Couldn't compute router hash.");
  443. goto err;
  444. }
  445. {
  446. int flags = 0;
  447. if (allow_annotations)
  448. flags |= TS_ANNOTATIONS_OK;
  449. if (prepend_annotations)
  450. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  451. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  452. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  453. goto err;
  454. }
  455. }
  456. if (smartlist_len(tokens) < 2) {
  457. log_warn(LD_DIR, "Impossibly short router descriptor.");
  458. goto err;
  459. }
  460. tok = find_by_keyword(tokens, K_ROUTER);
  461. const int router_token_pos = smartlist_pos(tokens, tok);
  462. tor_assert(tok->n_args >= 5);
  463. router = tor_malloc_zero(sizeof(routerinfo_t));
  464. router->cert_expiration_time = TIME_MAX;
  465. router->cache_info.routerlist_index = -1;
  466. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  467. router->cache_info.signed_descriptor_len = end-s;
  468. if (cache_copy) {
  469. size_t len = router->cache_info.signed_descriptor_len +
  470. router->cache_info.annotations_len;
  471. char *signed_body =
  472. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  473. if (prepend_annotations) {
  474. memcpy(signed_body, prepend_annotations, prepend_len);
  475. signed_body += prepend_len;
  476. }
  477. /* This assertion will always succeed.
  478. * len == signed_desc_len + annotations_len
  479. * == end-s + s-start_of_annotations + prepend_len
  480. * == end-start_of_annotations + prepend_len
  481. * We already wrote prepend_len bytes into the buffer; now we're
  482. * writing end-start_of_annotations -NM. */
  483. tor_assert(signed_body+(end-start_of_annotations) ==
  484. router->cache_info.signed_descriptor_body+len);
  485. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  486. router->cache_info.signed_descriptor_body[len] = '\0';
  487. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  488. }
  489. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  490. router->nickname = tor_strdup(tok->args[0]);
  491. if (!is_legal_nickname(router->nickname)) {
  492. log_warn(LD_DIR,"Router nickname is invalid");
  493. goto err;
  494. }
  495. if (!tor_inet_aton(tok->args[1], &in)) {
  496. log_warn(LD_DIR,"Router address is not an IP address.");
  497. goto err;
  498. }
  499. router->addr = ntohl(in.s_addr);
  500. router->or_port =
  501. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  502. if (!ok) {
  503. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  504. goto err;
  505. }
  506. router->dir_port =
  507. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  508. if (!ok) {
  509. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  510. goto err;
  511. }
  512. tok = find_by_keyword(tokens, K_BANDWIDTH);
  513. tor_assert(tok->n_args >= 3);
  514. router->bandwidthrate = (int)
  515. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  516. if (!ok) {
  517. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  518. escaped(tok->args[0]));
  519. goto err;
  520. }
  521. router->bandwidthburst =
  522. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  523. if (!ok) {
  524. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  525. goto err;
  526. }
  527. router->bandwidthcapacity = (int)
  528. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  529. if (!ok) {
  530. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  531. goto err;
  532. }
  533. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  534. tor_assert(tok->n_args);
  535. router->purpose = router_purpose_from_string(tok->args[0]);
  536. } else {
  537. router->purpose = ROUTER_PURPOSE_GENERAL;
  538. }
  539. router->cache_info.send_unencrypted =
  540. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  541. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  542. tor_assert(tok->n_args >= 1);
  543. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  544. if (!ok) {
  545. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  546. goto err;
  547. }
  548. }
  549. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  550. tor_assert(tok->n_args >= 1);
  551. router->is_hibernating
  552. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  553. }
  554. tok = find_by_keyword(tokens, K_PUBLISHED);
  555. tor_assert(tok->n_args == 1);
  556. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  557. goto err;
  558. tok = find_by_keyword(tokens, K_ONION_KEY);
  559. if (!crypto_pk_public_exponent_ok(tok->key)) {
  560. log_warn(LD_DIR,
  561. "Relay's onion key had invalid exponent.");
  562. goto err;
  563. }
  564. router_set_rsa_onion_pkey(tok->key, &router->onion_pkey,
  565. &router->onion_pkey_len);
  566. crypto_pk_free(tok->key);
  567. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  568. curve25519_public_key_t k;
  569. tor_assert(tok->n_args >= 1);
  570. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  571. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  572. goto err;
  573. }
  574. router->onion_curve25519_pkey =
  575. tor_memdup(&k, sizeof(curve25519_public_key_t));
  576. }
  577. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  578. router->identity_pkey = tok->key;
  579. tok->key = NULL; /* Prevent free */
  580. if (crypto_pk_get_digest(router->identity_pkey,
  581. router->cache_info.identity_digest)) {
  582. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  583. }
  584. {
  585. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  586. *master_key_tok;
  587. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  588. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  589. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  590. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  591. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  592. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  593. !!cc_tap_tok + !!cc_ntor_tok;
  594. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  595. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  596. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  597. "cross-certification support");
  598. goto err;
  599. }
  600. if (master_key_tok && !ed_sig_tok) {
  601. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  602. "certificate");
  603. goto err;
  604. }
  605. if (ed_sig_tok) {
  606. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  607. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  608. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  609. (ed_cert_token_pos != router_token_pos + 1 &&
  610. ed_cert_token_pos != router_token_pos - 1)) {
  611. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  612. goto err;
  613. }
  614. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  615. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  616. goto err;
  617. }
  618. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  619. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  620. goto err;
  621. }
  622. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  623. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  624. "in decriptor");
  625. goto err;
  626. }
  627. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  628. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  629. "in decriptor");
  630. goto err;
  631. }
  632. if (strcmp(cc_ntor_tok->args[0], "0") &&
  633. strcmp(cc_ntor_tok->args[0], "1")) {
  634. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  635. goto err;
  636. }
  637. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  638. uint8_t d256[DIGEST256_LEN];
  639. const char *signed_start, *signed_end;
  640. tor_cert_t *cert = tor_cert_parse(
  641. (const uint8_t*)ed_cert_tok->object_body,
  642. ed_cert_tok->object_size);
  643. if (! cert) {
  644. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  645. goto err;
  646. }
  647. /* makes sure it gets freed. */
  648. router->cache_info.signing_key_cert = cert;
  649. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  650. ! cert->signing_key_included) {
  651. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  652. goto err;
  653. }
  654. if (master_key_tok) {
  655. /* This token is optional, but if it's present, it must match
  656. * the signature in the signing cert, or supplant it. */
  657. tor_assert(master_key_tok->n_args >= 1);
  658. ed25519_public_key_t pkey;
  659. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  660. log_warn(LD_DIR, "Can't parse ed25519 master key");
  661. goto err;
  662. }
  663. if (fast_memneq(&cert->signing_key.pubkey,
  664. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  665. log_warn(LD_DIR, "Ed25519 master key does not match "
  666. "key in certificate");
  667. goto err;
  668. }
  669. }
  670. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  671. cc_ntor_tok->object_size);
  672. if (!ntor_cc_cert) {
  673. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  674. goto err;
  675. }
  676. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  677. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  678. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  679. goto err;
  680. }
  681. ed25519_public_key_t ntor_cc_pk;
  682. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  683. router->onion_curve25519_pkey,
  684. ntor_cc_sign_bit)<0) {
  685. log_warn(LD_DIR, "Error converting onion key to ed25519");
  686. goto err;
  687. }
  688. if (router_get_hash_impl_helper(s, end-s, "router ",
  689. "\nrouter-sig-ed25519",
  690. ' ', LOG_WARN,
  691. &signed_start, &signed_end) < 0) {
  692. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  693. goto err;
  694. }
  695. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  696. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  697. strlen(ED_DESC_SIGNATURE_PREFIX));
  698. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  699. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  700. crypto_digest_free(d);
  701. ed25519_checkable_t check[3];
  702. int check_ok[3];
  703. time_t expires = TIME_MAX;
  704. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  705. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  706. goto err;
  707. }
  708. if (tor_cert_get_checkable_sig(&check[1],
  709. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  710. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  711. goto err;
  712. }
  713. if (ed25519_signature_from_base64(&check[2].signature,
  714. ed_sig_tok->args[0])<0) {
  715. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  716. goto err;
  717. }
  718. check[2].pubkey = &cert->signed_key;
  719. check[2].msg = d256;
  720. check[2].len = DIGEST256_LEN;
  721. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  722. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  723. goto err;
  724. }
  725. rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
  726. router->onion_pkey_len);
  727. if (check_tap_onion_key_crosscert(
  728. (const uint8_t*)cc_tap_tok->object_body,
  729. (int)cc_tap_tok->object_size,
  730. rsa_pubkey,
  731. &cert->signing_key,
  732. (const uint8_t*)router->cache_info.identity_digest)<0) {
  733. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  734. goto err;
  735. }
  736. /* We check this before adding it to the routerlist. */
  737. router->cert_expiration_time = expires;
  738. }
  739. }
  740. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  741. /* If there's a fingerprint line, it must match the identity digest. */
  742. char d[DIGEST_LEN];
  743. tor_assert(tok->n_args == 1);
  744. tor_strstrip(tok->args[0], " ");
  745. if (base16_decode(d, DIGEST_LEN,
  746. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  747. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  748. escaped(tok->args[0]));
  749. goto err;
  750. }
  751. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  752. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  753. tok->args[0]);
  754. goto err;
  755. }
  756. }
  757. {
  758. const char *version = NULL, *protocols = NULL;
  759. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  760. router->platform = tor_strdup(tok->args[0]);
  761. version = tok->args[0];
  762. }
  763. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  764. router->protocol_list = tor_strdup(tok->args[0]);
  765. protocols = tok->args[0];
  766. }
  767. summarize_protover_flags(&router->pv, protocols, version);
  768. }
  769. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  770. router->contact_info = tor_strdup(tok->args[0]);
  771. }
  772. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  773. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  774. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  775. "older Tors.");
  776. goto err;
  777. }
  778. {
  779. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  780. if (or_addresses) {
  781. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  782. &router->ipv6_orport);
  783. smartlist_free(or_addresses);
  784. }
  785. }
  786. exit_policy_tokens = find_all_exitpolicy(tokens);
  787. if (!smartlist_len(exit_policy_tokens)) {
  788. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  789. goto err;
  790. }
  791. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  792. if (router_add_exit_policy(router,t)<0) {
  793. log_warn(LD_DIR,"Error in exit policy");
  794. goto err;
  795. });
  796. policy_expand_private(&router->exit_policy);
  797. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  798. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  799. if (! router->ipv6_exit_policy) {
  800. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  801. goto err;
  802. }
  803. }
  804. if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
  805. (!router->ipv6_exit_policy ||
  806. short_policy_is_reject_star(router->ipv6_exit_policy)))
  807. router->policy_is_reject_star = 1;
  808. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  809. int i;
  810. router->declared_family = smartlist_new();
  811. for (i=0;i<tok->n_args;++i) {
  812. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  813. log_warn(LD_DIR, "Illegal nickname %s in family line",
  814. escaped(tok->args[i]));
  815. goto err;
  816. }
  817. smartlist_add_strdup(router->declared_family, tok->args[i]);
  818. }
  819. }
  820. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  821. router->caches_extra_info = 1;
  822. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  823. router->allow_single_hop_exits = 1;
  824. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  825. tor_assert(tok->n_args >= 1);
  826. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  827. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  828. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  829. log_warn(LD_DIR,"Invalid extra info digest");
  830. }
  831. } else {
  832. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  833. }
  834. if (tok->n_args >= 2) {
  835. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  836. tok->args[1]) < 0) {
  837. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  838. escaped(tok->args[1]));
  839. }
  840. }
  841. }
  842. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  843. router->wants_to_be_hs_dir = 1;
  844. }
  845. /* This router accepts tunnelled directory requests via begindir if it has
  846. * an open dirport or it included "tunnelled-dir-server". */
  847. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  848. router->supports_tunnelled_dir_requests = 1;
  849. }
  850. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  851. if (!router->or_port) {
  852. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  853. goto err;
  854. }
  855. /* We've checked everything that's covered by the hash. */
  856. can_dl_again = 1;
  857. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  858. "router descriptor") < 0)
  859. goto err;
  860. if (!router->platform) {
  861. router->platform = tor_strdup("<unknown>");
  862. }
  863. goto done;
  864. err:
  865. dump_desc(s_dup, "router descriptor");
  866. routerinfo_free(router);
  867. router = NULL;
  868. done:
  869. crypto_pk_free(rsa_pubkey);
  870. tor_cert_free(ntor_cc_cert);
  871. if (tokens) {
  872. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  873. smartlist_free(tokens);
  874. }
  875. smartlist_free(exit_policy_tokens);
  876. if (area) {
  877. DUMP_AREA(area, "routerinfo");
  878. memarea_drop_all(area);
  879. }
  880. if (can_dl_again_out)
  881. *can_dl_again_out = can_dl_again;
  882. return router;
  883. }
  884. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  885. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  886. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  887. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  888. * as a map from router identity to routerinfo_t when looking up signing keys.
  889. *
  890. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  891. * if it's okay to try to download an extrainfo with this same digest again,
  892. * and 0 if it isn't. (It might not be okay to download it again if part of
  893. * the part covered by the digest is invalid.)
  894. */
  895. extrainfo_t *
  896. extrainfo_parse_entry_from_string(const char *s, const char *end,
  897. int cache_copy, struct digest_ri_map_t *routermap,
  898. int *can_dl_again_out)
  899. {
  900. extrainfo_t *extrainfo = NULL;
  901. char digest[128];
  902. smartlist_t *tokens = NULL;
  903. directory_token_t *tok;
  904. crypto_pk_t *key = NULL;
  905. routerinfo_t *router = NULL;
  906. memarea_t *area = NULL;
  907. const char *s_dup = s;
  908. /* Do not set this to '1' until we have parsed everything that we intend to
  909. * parse that's covered by the hash. */
  910. int can_dl_again = 0;
  911. if (BUG(s == NULL))
  912. return NULL;
  913. if (!end) {
  914. end = s + strlen(s);
  915. }
  916. /* point 'end' to a point immediately after the final newline. */
  917. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  918. --end;
  919. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  920. log_warn(LD_DIR, "Couldn't compute router hash.");
  921. goto err;
  922. }
  923. tokens = smartlist_new();
  924. area = memarea_new();
  925. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  926. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  927. goto err;
  928. }
  929. if (smartlist_len(tokens) < 2) {
  930. log_warn(LD_DIR, "Impossibly short extra-info document.");
  931. goto err;
  932. }
  933. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  934. tok = smartlist_get(tokens,0);
  935. if (tok->tp != K_EXTRA_INFO) {
  936. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  937. goto err;
  938. }
  939. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  940. extrainfo->cache_info.is_extrainfo = 1;
  941. if (cache_copy)
  942. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  943. extrainfo->cache_info.signed_descriptor_len = end-s;
  944. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  945. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  946. tor_assert(tok->n_args >= 2);
  947. if (!is_legal_nickname(tok->args[0])) {
  948. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  949. goto err;
  950. }
  951. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  952. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  953. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  954. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  955. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  956. escaped(tok->args[1]));
  957. goto err;
  958. }
  959. tok = find_by_keyword(tokens, K_PUBLISHED);
  960. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  961. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  962. escaped(tok->args[0]));
  963. goto err;
  964. }
  965. {
  966. directory_token_t *ed_sig_tok, *ed_cert_tok;
  967. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  968. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  969. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  970. if (n_ed_toks != 0 && n_ed_toks != 2) {
  971. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  972. "cross-certification support");
  973. goto err;
  974. }
  975. if (ed_sig_tok) {
  976. tor_assert(ed_cert_tok);
  977. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  978. if (ed_cert_token_pos != 1) {
  979. /* Accept this in position 0 XXXX */
  980. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  981. goto err;
  982. }
  983. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  984. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  985. goto err;
  986. }
  987. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  988. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  989. goto err;
  990. }
  991. uint8_t d256[DIGEST256_LEN];
  992. const char *signed_start, *signed_end;
  993. tor_cert_t *cert = tor_cert_parse(
  994. (const uint8_t*)ed_cert_tok->object_body,
  995. ed_cert_tok->object_size);
  996. if (! cert) {
  997. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  998. goto err;
  999. }
  1000. /* makes sure it gets freed. */
  1001. extrainfo->cache_info.signing_key_cert = cert;
  1002. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1003. ! cert->signing_key_included) {
  1004. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1005. goto err;
  1006. }
  1007. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1008. "\nrouter-sig-ed25519",
  1009. ' ', LOG_WARN,
  1010. &signed_start, &signed_end) < 0) {
  1011. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1012. goto err;
  1013. }
  1014. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1015. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1016. strlen(ED_DESC_SIGNATURE_PREFIX));
  1017. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1018. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1019. crypto_digest_free(d);
  1020. ed25519_checkable_t check[2];
  1021. int check_ok[2];
  1022. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  1023. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1024. goto err;
  1025. }
  1026. if (ed25519_signature_from_base64(&check[1].signature,
  1027. ed_sig_tok->args[0])<0) {
  1028. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1029. goto err;
  1030. }
  1031. check[1].pubkey = &cert->signed_key;
  1032. check[1].msg = d256;
  1033. check[1].len = DIGEST256_LEN;
  1034. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1035. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1036. goto err;
  1037. }
  1038. /* We don't check the certificate expiration time: checking that it
  1039. * matches the cert in the router descriptor is adequate. */
  1040. }
  1041. }
  1042. /* We've checked everything that's covered by the hash. */
  1043. can_dl_again = 1;
  1044. if (routermap &&
  1045. (router = digestmap_get((digestmap_t*)routermap,
  1046. extrainfo->cache_info.identity_digest))) {
  1047. key = router->identity_pkey;
  1048. }
  1049. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1050. if (strcmp(tok->object_type, "SIGNATURE") ||
  1051. tok->object_size < 128 || tok->object_size > 512) {
  1052. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1053. goto err;
  1054. }
  1055. if (key) {
  1056. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1057. "extra-info") < 0)
  1058. goto err;
  1059. if (router)
  1060. extrainfo->cache_info.send_unencrypted =
  1061. router->cache_info.send_unencrypted;
  1062. } else {
  1063. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1064. tok->object_size);
  1065. extrainfo->pending_sig_len = tok->object_size;
  1066. }
  1067. goto done;
  1068. err:
  1069. dump_desc(s_dup, "extra-info descriptor");
  1070. extrainfo_free(extrainfo);
  1071. extrainfo = NULL;
  1072. done:
  1073. if (tokens) {
  1074. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1075. smartlist_free(tokens);
  1076. }
  1077. if (area) {
  1078. DUMP_AREA(area, "extrainfo");
  1079. memarea_drop_all(area);
  1080. }
  1081. if (can_dl_again_out)
  1082. *can_dl_again_out = can_dl_again;
  1083. return extrainfo;
  1084. }
  1085. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1086. * <b>router</b>. Return 0 on success, -1 on failure. */
  1087. static int
  1088. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1089. {
  1090. addr_policy_t *newe;
  1091. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  1092. newe = router_parse_addr_policy(tok, 0);
  1093. if (!newe)
  1094. return -1;
  1095. if (! router->exit_policy)
  1096. router->exit_policy = smartlist_new();
  1097. /* Ensure that in descriptors, accept/reject fields are followed by
  1098. * IPv4 addresses, and accept6/reject6 fields are followed by
  1099. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  1100. * accept/reject followed by IPv6. */
  1101. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  1102. tor_addr_family(&newe->addr) == AF_INET)
  1103. ||
  1104. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  1105. tor_addr_family(&newe->addr) == AF_INET6)) {
  1106. /* There's nothing the user can do about other relays' descriptors,
  1107. * so we don't provide usage advice here. */
  1108. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  1109. "policy '%s'. Discarding entire router descriptor.",
  1110. tok->n_args == 1 ? tok->args[0] : "");
  1111. addr_policy_free(newe);
  1112. return -1;
  1113. }
  1114. smartlist_add(router->exit_policy, newe);
  1115. return 0;
  1116. }
  1117. /** Return a newly allocated smartlist of all accept or reject tokens in
  1118. * <b>s</b>.
  1119. */
  1120. static smartlist_t *
  1121. find_all_exitpolicy(smartlist_t *s)
  1122. {
  1123. smartlist_t *out = smartlist_new();
  1124. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1125. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  1126. t->tp == K_REJECT || t->tp == K_REJECT6)
  1127. smartlist_add(out,t));
  1128. return out;
  1129. }
  1130. /** Called on startup; right now we just handle scanning the unparseable
  1131. * descriptor dumps, but hang anything else we might need to do in the
  1132. * future here as well.
  1133. */
  1134. void
  1135. routerparse_init(void)
  1136. {
  1137. /*
  1138. * Check both if the sandbox is active and whether it's configured; no
  1139. * point in loading all that if we won't be able to use it after the
  1140. * sandbox becomes active.
  1141. */
  1142. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  1143. dump_desc_init();
  1144. }
  1145. }
  1146. /** Clean up all data structures used by routerparse.c at exit */
  1147. void
  1148. routerparse_free_all(void)
  1149. {
  1150. dump_desc_fifo_cleanup();
  1151. }