addressmap.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file addressmap.c
  8. *
  9. * \brief The addressmap module manages the processes by which we rewrite
  10. * addresses in client requess. It handles the MapAddress controller and
  11. * torrc commands, and the TrackHostExits feature, and the client-side DNS
  12. * cache (deprecated).
  13. */
  14. #define ADDRESSMAP_PRIVATE
  15. #include "or.h"
  16. #include "addressmap.h"
  17. #include "circuituse.h"
  18. #include "config.h"
  19. #include "connection_edge.h"
  20. #include "control.h"
  21. #include "dns.h"
  22. #include "routerset.h"
  23. #include "nodelist.h"
  24. /** A client-side struct to remember requests to rewrite addresses
  25. * to new addresses. These structs are stored in the hash table
  26. * "addressmap" below.
  27. *
  28. * There are 5 ways to set an address mapping:
  29. * - A MapAddress command from the controller [permanent]
  30. * - An AddressMap directive in the torrc [permanent]
  31. * - When a TrackHostExits torrc directive is triggered [temporary]
  32. * - When a DNS resolve succeeds [temporary]
  33. * - When a DNS resolve fails [temporary]
  34. *
  35. * When an addressmap request is made but one is already registered,
  36. * the new one is replaced only if the currently registered one has
  37. * no "new_address" (that is, it's in the process of DNS resolve),
  38. * or if the new one is permanent (expires==0 or 1).
  39. *
  40. * (We overload the 'expires' field, using "0" for mappings set via
  41. * the configuration file, "1" for mappings set from the control
  42. * interface, and other values for DNS and TrackHostExit mappings that can
  43. * expire.)
  44. *
  45. * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
  46. * any address that ends with a . followed by the key for this entry will
  47. * get remapped by it. If "dst_wildcard" is also true, then only the
  48. * matching suffix of such addresses will get replaced by new_address.
  49. */
  50. typedef struct {
  51. char *new_address;
  52. time_t expires;
  53. addressmap_entry_source_bitfield_t source:3;
  54. unsigned src_wildcard:1;
  55. unsigned dst_wildcard:1;
  56. short num_resolve_failures;
  57. } addressmap_entry_t;
  58. /** Entry for mapping addresses to which virtual address we mapped them to. */
  59. typedef struct {
  60. char *ipv4_address;
  61. char *ipv6_address;
  62. char *hostname_address;
  63. } virtaddress_entry_t;
  64. /** A hash table to store client-side address rewrite instructions. */
  65. static strmap_t *addressmap=NULL;
  66. /**
  67. * Table mapping addresses to which virtual address, if any, we
  68. * assigned them to.
  69. *
  70. * We maintain the following invariant: if [A,B] is in
  71. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  72. * must be in addressmap. We do not require that the converse hold:
  73. * if it fails, then we could end up mapping two virtual addresses to
  74. * the same address, which is no disaster.
  75. **/
  76. static strmap_t *virtaddress_reversemap=NULL;
  77. /** Initialize addressmap. */
  78. void
  79. addressmap_init(void)
  80. {
  81. addressmap = strmap_new();
  82. virtaddress_reversemap = strmap_new();
  83. }
  84. #define addressmap_ent_free(ent) \
  85. FREE_AND_NULL(addressmap_entry_t, addressmap_ent_free_, (ent))
  86. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  87. static void
  88. addressmap_ent_free_(addressmap_entry_t *ent)
  89. {
  90. if (!ent)
  91. return;
  92. tor_free(ent->new_address);
  93. tor_free(ent);
  94. }
  95. static void
  96. addressmap_ent_free_void(void *ent)
  97. {
  98. addressmap_ent_free_(ent);
  99. }
  100. #define addressmap_virtaddress_ent_free(ent) \
  101. FREE_AND_NULL(virtaddress_entry_t, addressmap_virtaddress_ent_free_, (ent))
  102. /** Free storage held by a virtaddress_entry_t* entry in <b>_ent</b>. */
  103. static void
  104. addressmap_virtaddress_ent_free_(virtaddress_entry_t *ent)
  105. {
  106. if (!ent)
  107. return;
  108. tor_free(ent->ipv4_address);
  109. tor_free(ent->ipv6_address);
  110. tor_free(ent->hostname_address);
  111. tor_free(ent);
  112. }
  113. static void
  114. addressmap_virtaddress_ent_free_void(void *ent)
  115. {
  116. addressmap_virtaddress_ent_free_(ent);
  117. }
  118. /** Remove <b>address</b> (which must map to <b>ent</b>) from the
  119. * virtual address map. */
  120. static void
  121. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  122. {
  123. if (ent && ent->new_address &&
  124. address_is_in_virtual_range(ent->new_address)) {
  125. virtaddress_entry_t *ve =
  126. strmap_get(virtaddress_reversemap, ent->new_address);
  127. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  128. if (ve) {
  129. if (!strcmp(address, ve->ipv4_address))
  130. tor_free(ve->ipv4_address);
  131. if (!strcmp(address, ve->ipv6_address))
  132. tor_free(ve->ipv6_address);
  133. if (!strcmp(address, ve->hostname_address))
  134. tor_free(ve->hostname_address);
  135. if (!ve->ipv4_address && !ve->ipv6_address && !ve->hostname_address) {
  136. tor_free(ve);
  137. strmap_remove(virtaddress_reversemap, ent->new_address);
  138. }
  139. }
  140. }
  141. }
  142. /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
  143. * client address maps, and then free it. */
  144. static void
  145. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  146. {
  147. addressmap_virtaddress_remove(address, ent);
  148. addressmap_ent_free(ent);
  149. }
  150. /** Unregister all TrackHostExits mappings from any address to
  151. * *.exitname.exit. */
  152. void
  153. clear_trackexithost_mappings(const char *exitname)
  154. {
  155. char *suffix = NULL;
  156. if (!addressmap || !exitname)
  157. return;
  158. tor_asprintf(&suffix, ".%s.exit", exitname);
  159. tor_strlower(suffix);
  160. STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
  161. if (ent->source == ADDRMAPSRC_TRACKEXIT &&
  162. !strcmpend(ent->new_address, suffix)) {
  163. addressmap_ent_remove(address, ent);
  164. MAP_DEL_CURRENT(address);
  165. }
  166. } STRMAP_FOREACH_END;
  167. tor_free(suffix);
  168. }
  169. /** Remove all TRACKEXIT mappings from the addressmap for which the target
  170. * host is unknown or no longer allowed, or for which the source address
  171. * is no longer in trackexithosts. */
  172. void
  173. addressmap_clear_excluded_trackexithosts(const or_options_t *options)
  174. {
  175. const routerset_t *allow_nodes = options->ExitNodes;
  176. const routerset_t *exclude_nodes = options->ExcludeExitNodesUnion_;
  177. if (!addressmap)
  178. return;
  179. if (routerset_is_empty(allow_nodes))
  180. allow_nodes = NULL;
  181. if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
  182. return;
  183. STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
  184. size_t len;
  185. const char *target = ent->new_address, *dot;
  186. char *nodename;
  187. const node_t *node;
  188. if (!target) {
  189. /* DNS resolving in progress */
  190. continue;
  191. } else if (strcmpend(target, ".exit")) {
  192. /* Not a .exit mapping */
  193. continue;
  194. } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
  195. /* Not a trackexit mapping. */
  196. continue;
  197. }
  198. len = strlen(target);
  199. if (len < 6)
  200. continue; /* malformed. */
  201. dot = target + len - 6; /* dot now points to just before .exit */
  202. while (dot > target && *dot != '.')
  203. dot--;
  204. if (*dot == '.') dot++;
  205. nodename = tor_strndup(dot, len-5-(dot-target));
  206. node = node_get_by_nickname(nodename, NNF_NO_WARN_UNNAMED);
  207. tor_free(nodename);
  208. if (!node ||
  209. (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
  210. routerset_contains_node(exclude_nodes, node) ||
  211. !hostname_in_track_host_exits(options, address)) {
  212. /* We don't know this one, or we want to be rid of it. */
  213. addressmap_ent_remove(address, ent);
  214. MAP_DEL_CURRENT(address);
  215. }
  216. } STRMAP_FOREACH_END;
  217. }
  218. /** Return true iff <b>address</b> is one that we are configured to
  219. * automap on resolve according to <b>options</b>. */
  220. int
  221. addressmap_address_should_automap(const char *address,
  222. const or_options_t *options)
  223. {
  224. const smartlist_t *suffix_list = options->AutomapHostsSuffixes;
  225. if (!suffix_list)
  226. return 0;
  227. SMARTLIST_FOREACH_BEGIN(suffix_list, const char *, suffix) {
  228. if (!strcmp(suffix, "."))
  229. return 1;
  230. if (!strcasecmpend(address, suffix))
  231. return 1;
  232. } SMARTLIST_FOREACH_END(suffix);
  233. return 0;
  234. }
  235. /** Remove all AUTOMAP mappings from the addressmap for which the
  236. * source address no longer matches AutomapHostsSuffixes, which is
  237. * no longer allowed by AutomapHostsOnResolve, or for which the
  238. * target address is no longer in the virtual network. */
  239. void
  240. addressmap_clear_invalid_automaps(const or_options_t *options)
  241. {
  242. int clear_all = !options->AutomapHostsOnResolve;
  243. const smartlist_t *suffixes = options->AutomapHostsSuffixes;
  244. if (!addressmap)
  245. return;
  246. if (!suffixes)
  247. clear_all = 1; /* This should be impossible, but let's be sure. */
  248. STRMAP_FOREACH_MODIFY(addressmap, src_address, addressmap_entry_t *, ent) {
  249. int remove_this = clear_all;
  250. if (ent->source != ADDRMAPSRC_AUTOMAP)
  251. continue; /* not an automap mapping. */
  252. if (!remove_this) {
  253. remove_this = ! addressmap_address_should_automap(src_address, options);
  254. }
  255. if (!remove_this && ! address_is_in_virtual_range(ent->new_address))
  256. remove_this = 1;
  257. if (remove_this) {
  258. addressmap_ent_remove(src_address, ent);
  259. MAP_DEL_CURRENT(src_address);
  260. }
  261. } STRMAP_FOREACH_END;
  262. }
  263. /** Remove all entries from the addressmap that were set via the
  264. * configuration file or the command line. */
  265. void
  266. addressmap_clear_configured(void)
  267. {
  268. addressmap_get_mappings(NULL, 0, 0, 0);
  269. }
  270. /** Remove all entries from the addressmap that are set to expire, ever. */
  271. void
  272. addressmap_clear_transient(void)
  273. {
  274. addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
  275. }
  276. /** Clean out entries from the addressmap cache that were
  277. * added long enough ago that they are no longer valid.
  278. */
  279. void
  280. addressmap_clean(time_t now)
  281. {
  282. addressmap_get_mappings(NULL, 2, now, 0);
  283. }
  284. /** Free all the elements in the addressmap, and free the addressmap
  285. * itself. */
  286. void
  287. addressmap_free_all(void)
  288. {
  289. strmap_free(addressmap, addressmap_ent_free_void);
  290. addressmap = NULL;
  291. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free_void);
  292. virtaddress_reversemap = NULL;
  293. }
  294. /** Try to find a match for AddressMap expressions that use
  295. * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
  296. * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
  297. * Return the matching entry in AddressMap or NULL if no match is found.
  298. * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
  299. * to 'a' before we return the matching AddressMap entry.
  300. *
  301. * This function does not handle the case where a pattern of the form "*.c.d"
  302. * matches the address c.d -- that's done by the main addressmap_rewrite
  303. * function.
  304. */
  305. static addressmap_entry_t *
  306. addressmap_match_superdomains(char *address)
  307. {
  308. addressmap_entry_t *val;
  309. char *cp;
  310. cp = address;
  311. while ((cp = strchr(cp, '.'))) {
  312. /* cp now points to a suffix of address that begins with a . */
  313. val = strmap_get_lc(addressmap, cp+1);
  314. if (val && val->src_wildcard) {
  315. if (val->dst_wildcard)
  316. *cp = '\0';
  317. return val;
  318. }
  319. ++cp;
  320. }
  321. return NULL;
  322. }
  323. /** Look at address, and rewrite it until it doesn't want any
  324. * more rewrites; but don't get into an infinite loop.
  325. * Don't write more than maxlen chars into address. Return true if the
  326. * address changed; false otherwise. Set *<b>expires_out</b> to the
  327. * expiry time of the result, or to <b>time_max</b> if the result does
  328. * not expire.
  329. *
  330. * If <b>exit_source_out</b> is non-null, we set it as follows. If we the
  331. * address starts out as a non-exit address, and we remap it to an .exit
  332. * address at any point, then set *<b>exit_source_out</b> to the
  333. * address_entry_source_t of the first such rule. Set *<b>exit_source_out</b>
  334. * to ADDRMAPSRC_NONE if there is no such rewrite, or if the original address
  335. * was a .exit.
  336. */
  337. int
  338. addressmap_rewrite(char *address, size_t maxlen,
  339. unsigned flags,
  340. time_t *expires_out,
  341. addressmap_entry_source_t *exit_source_out)
  342. {
  343. addressmap_entry_t *ent;
  344. int rewrites;
  345. time_t expires = TIME_MAX;
  346. addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
  347. char *addr_orig = tor_strdup(address);
  348. char *log_addr_orig = NULL;
  349. /* We use a loop here to limit the total number of rewrites we do,
  350. * so that we can't hit an infinite loop. */
  351. for (rewrites = 0; rewrites < 16; rewrites++) {
  352. int exact_match = 0;
  353. log_addr_orig = tor_strdup(escaped_safe_str_client(address));
  354. /* First check to see if there's an exact match for this address */
  355. ent = strmap_get(addressmap, address);
  356. if (!ent || !ent->new_address) {
  357. /* And if we don't have an exact match, try to check whether
  358. * we have a pattern-based match.
  359. */
  360. ent = addressmap_match_superdomains(address);
  361. } else {
  362. if (ent->src_wildcard && !ent->dst_wildcard &&
  363. !strcasecmp(address, ent->new_address)) {
  364. /* This is a rule like "rewrite *.example.com to example.com", and we
  365. * just got "example.com". Instead of calling it an infinite loop,
  366. * call it complete. */
  367. goto done;
  368. }
  369. exact_match = 1;
  370. }
  371. if (!ent || !ent->new_address) {
  372. /* We still have no match at all. We're done! */
  373. goto done;
  374. }
  375. /* Check wither the flags we were passed tell us not to use this
  376. * mapping. */
  377. switch (ent->source) {
  378. case ADDRMAPSRC_DNS:
  379. {
  380. sa_family_t f;
  381. tor_addr_t tmp;
  382. f = tor_addr_parse(&tmp, ent->new_address);
  383. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  384. goto done;
  385. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  386. goto done;
  387. }
  388. break;
  389. case ADDRMAPSRC_CONTROLLER:
  390. case ADDRMAPSRC_TORRC:
  391. if (!(flags & AMR_FLAG_USE_MAPADDRESS))
  392. goto done;
  393. break;
  394. case ADDRMAPSRC_AUTOMAP:
  395. if (!(flags & AMR_FLAG_USE_AUTOMAP))
  396. goto done;
  397. break;
  398. case ADDRMAPSRC_TRACKEXIT:
  399. if (!(flags & AMR_FLAG_USE_TRACKEXIT))
  400. goto done;
  401. break;
  402. case ADDRMAPSRC_NONE:
  403. default:
  404. log_warn(LD_BUG, "Unknown addrmap source value %d. Ignoring it.",
  405. (int) ent->source);
  406. goto done;
  407. }
  408. /* Now fill in the address with the new address. That might be via
  409. * appending some new stuff to the end, or via just replacing it. */
  410. if (ent->dst_wildcard && !exact_match) {
  411. strlcat(address, ".", maxlen);
  412. strlcat(address, ent->new_address, maxlen);
  413. } else {
  414. strlcpy(address, ent->new_address, maxlen);
  415. }
  416. /* Is this now a .exit address? If so, remember where we got it.*/
  417. if (!strcmpend(address, ".exit") &&
  418. strcmpend(addr_orig, ".exit") &&
  419. exit_source == ADDRMAPSRC_NONE) {
  420. exit_source = ent->source;
  421. }
  422. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  423. log_addr_orig, escaped_safe_str_client(address));
  424. if (ent->expires > 1 && ent->expires < expires)
  425. expires = ent->expires;
  426. tor_free(log_addr_orig);
  427. }
  428. log_warn(LD_CONFIG,
  429. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  430. escaped_safe_str_client(address));
  431. /* it's fine to rewrite a rewrite, but don't loop forever */
  432. done:
  433. tor_free(addr_orig);
  434. tor_free(log_addr_orig);
  435. if (exit_source_out)
  436. *exit_source_out = exit_source;
  437. if (expires_out)
  438. *expires_out = expires;
  439. return (rewrites > 0);
  440. }
  441. /** If we have a cached reverse DNS entry for the address stored in the
  442. * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
  443. * rewrite to the cached value and return 1. Otherwise return 0. Set
  444. * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
  445. * if the result does not expire. */
  446. int
  447. addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags,
  448. time_t *expires_out)
  449. {
  450. char *s, *cp;
  451. addressmap_entry_t *ent;
  452. int r = 0;
  453. {
  454. sa_family_t f;
  455. tor_addr_t tmp;
  456. f = tor_addr_parse(&tmp, address);
  457. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  458. return 0;
  459. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  460. return 0;
  461. /* FFFF we should reverse-map virtual addresses even if we haven't
  462. * enabled DNS cacheing. */
  463. }
  464. tor_asprintf(&s, "REVERSE[%s]", address);
  465. ent = strmap_get(addressmap, s);
  466. if (ent) {
  467. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  468. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  469. escaped_safe_str_client(s), cp);
  470. tor_free(cp);
  471. strlcpy(address, ent->new_address, maxlen);
  472. r = 1;
  473. }
  474. if (expires_out)
  475. *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
  476. tor_free(s);
  477. return r;
  478. }
  479. /** Return 1 if <b>address</b> is already registered, else return 0. If address
  480. * is already registered, and <b>update_expires</b> is non-zero, then update
  481. * the expiry time on the mapping with update_expires if it is a
  482. * mapping created by TrackHostExits. */
  483. int
  484. addressmap_have_mapping(const char *address, int update_expiry)
  485. {
  486. addressmap_entry_t *ent;
  487. if (!(ent=strmap_get_lc(addressmap, address)))
  488. return 0;
  489. if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
  490. ent->expires=time(NULL) + update_expiry;
  491. return 1;
  492. }
  493. /** Register a request to map <b>address</b> to <b>new_address</b>,
  494. * which will expire on <b>expires</b> (or 0 if never expires from
  495. * config file, 1 if never expires from controller, 2 if never expires
  496. * (virtual address mapping) from the controller.)
  497. *
  498. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  499. * free as appropriate. We will leave <b>address</b> alone.
  500. *
  501. * If <b>wildcard_addr</b> is true, then the mapping will match any address
  502. * equal to <b>address</b>, or any address ending with a period followed by
  503. * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
  504. * both true, the mapping will rewrite addresses that end with
  505. * ".<b>address</b>" into ones that end with ".<b>new_address</b>".
  506. *
  507. * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
  508. * <b>address</b> and <b>wildcard_addr</b> is equal to
  509. * <b>wildcard_new_addr</b>, remove any mappings that exist from
  510. * <b>address</b>.
  511. *
  512. * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
  513. * not set. */
  514. void
  515. addressmap_register(const char *address, char *new_address, time_t expires,
  516. addressmap_entry_source_t source,
  517. const int wildcard_addr,
  518. const int wildcard_new_addr)
  519. {
  520. addressmap_entry_t *ent;
  521. if (wildcard_new_addr)
  522. tor_assert(wildcard_addr);
  523. ent = strmap_get(addressmap, address);
  524. if (!new_address || (!strcasecmp(address,new_address) &&
  525. wildcard_addr == wildcard_new_addr)) {
  526. /* Remove the mapping, if any. */
  527. tor_free(new_address);
  528. if (ent) {
  529. addressmap_ent_remove(address,ent);
  530. strmap_remove(addressmap, address);
  531. }
  532. return;
  533. }
  534. if (!ent) { /* make a new one and register it */
  535. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  536. strmap_set(addressmap, address, ent);
  537. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  538. if (expires > 1) {
  539. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  540. "since it's already mapped to '%s'",
  541. safe_str_client(address),
  542. safe_str_client(new_address),
  543. safe_str_client(ent->new_address));
  544. tor_free(new_address);
  545. return;
  546. }
  547. if (address_is_in_virtual_range(ent->new_address) &&
  548. expires != 2) {
  549. /* XXX This isn't the perfect test; we want to avoid removing
  550. * mappings set from the control interface _as virtual mapping */
  551. addressmap_virtaddress_remove(address, ent);
  552. }
  553. tor_free(ent->new_address);
  554. } /* else { we have an in-progress resolve with no mapping. } */
  555. ent->new_address = new_address;
  556. ent->expires = expires==2 ? 1 : expires;
  557. ent->num_resolve_failures = 0;
  558. ent->source = source;
  559. ent->src_wildcard = wildcard_addr ? 1 : 0;
  560. ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
  561. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  562. safe_str_client(address),
  563. safe_str_client(ent->new_address));
  564. control_event_address_mapped(address, ent->new_address, expires, NULL, 1);
  565. }
  566. /** An attempt to resolve <b>address</b> failed at some OR.
  567. * Increment the number of resolve failures we have on record
  568. * for it, and then return that number.
  569. */
  570. int
  571. client_dns_incr_failures(const char *address)
  572. {
  573. addressmap_entry_t *ent = strmap_get(addressmap, address);
  574. if (!ent) {
  575. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  576. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  577. strmap_set(addressmap,address,ent);
  578. }
  579. if (ent->num_resolve_failures < SHORT_MAX)
  580. ++ent->num_resolve_failures; /* don't overflow */
  581. log_info(LD_APP, "Address %s now has %d resolve failures.",
  582. safe_str_client(address),
  583. ent->num_resolve_failures);
  584. return ent->num_resolve_failures;
  585. }
  586. /** If <b>address</b> is in the client DNS addressmap, reset
  587. * the number of resolve failures we have on record for it.
  588. * This is used when we fail a stream because it won't resolve:
  589. * otherwise future attempts on that address will only try once.
  590. */
  591. void
  592. client_dns_clear_failures(const char *address)
  593. {
  594. addressmap_entry_t *ent = strmap_get(addressmap, address);
  595. if (ent)
  596. ent->num_resolve_failures = 0;
  597. }
  598. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  599. * We can now use this in subsequent streams via addressmap_rewrite()
  600. * so we can more correctly choose an exit that will allow <b>address</b>.
  601. *
  602. * If <b>exitname</b> is defined, then append the addresses with
  603. * ".exitname.exit" before registering the mapping.
  604. *
  605. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  606. * <b>ttl</b>seconds; otherwise, we use the default.
  607. */
  608. static void
  609. client_dns_set_addressmap_impl(entry_connection_t *for_conn,
  610. const char *address, const char *name,
  611. const char *exitname,
  612. int ttl)
  613. {
  614. char *extendedaddress=NULL, *extendedval=NULL;
  615. (void)for_conn;
  616. tor_assert(address);
  617. tor_assert(name);
  618. if (ttl<0)
  619. ttl = DEFAULT_DNS_TTL;
  620. else
  621. ttl = dns_clip_ttl(ttl);
  622. if (exitname) {
  623. /* XXXX fails to ever get attempts to get an exit address of
  624. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  625. * won't make strict RFC952-compliant applications (like us) barf. */
  626. tor_asprintf(&extendedaddress,
  627. "%s.%s.exit", address, exitname);
  628. tor_asprintf(&extendedval,
  629. "%s.%s.exit", name, exitname);
  630. } else {
  631. tor_asprintf(&extendedaddress,
  632. "%s", address);
  633. tor_asprintf(&extendedval,
  634. "%s", name);
  635. }
  636. addressmap_register(extendedaddress, extendedval,
  637. time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
  638. tor_free(extendedaddress);
  639. }
  640. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  641. * We can now use this in subsequent streams via addressmap_rewrite()
  642. * so we can more correctly choose an exit that will allow <b>address</b>.
  643. *
  644. * If <b>exitname</b> is defined, then append the addresses with
  645. * ".exitname.exit" before registering the mapping.
  646. *
  647. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  648. * <b>ttl</b>seconds; otherwise, we use the default.
  649. */
  650. void
  651. client_dns_set_addressmap(entry_connection_t *for_conn,
  652. const char *address,
  653. const tor_addr_t *val,
  654. const char *exitname,
  655. int ttl)
  656. {
  657. tor_addr_t addr_tmp;
  658. char valbuf[TOR_ADDR_BUF_LEN];
  659. tor_assert(address);
  660. tor_assert(val);
  661. if (tor_addr_parse(&addr_tmp, address) >= 0)
  662. return; /* If address was an IP address already, don't add a mapping. */
  663. if (tor_addr_family(val) == AF_INET) {
  664. if (! for_conn->entry_cfg.cache_ipv4_answers)
  665. return;
  666. } else if (tor_addr_family(val) == AF_INET6) {
  667. if (! for_conn->entry_cfg.cache_ipv6_answers)
  668. return;
  669. }
  670. if (! tor_addr_to_str(valbuf, val, sizeof(valbuf), 1))
  671. return;
  672. client_dns_set_addressmap_impl(for_conn, address, valbuf, exitname, ttl);
  673. }
  674. /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
  675. * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
  676. *
  677. * If <b>exitname</b> is defined, then append the addresses with
  678. * ".exitname.exit" before registering the mapping.
  679. *
  680. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  681. * <b>ttl</b>seconds; otherwise, we use the default.
  682. */
  683. void
  684. client_dns_set_reverse_addressmap(entry_connection_t *for_conn,
  685. const char *address, const char *v,
  686. const char *exitname,
  687. int ttl)
  688. {
  689. char *s = NULL;
  690. {
  691. tor_addr_t tmp_addr;
  692. sa_family_t f = tor_addr_parse(&tmp_addr, address);
  693. if ((f == AF_INET && ! for_conn->entry_cfg.cache_ipv4_answers) ||
  694. (f == AF_INET6 && ! for_conn->entry_cfg.cache_ipv6_answers))
  695. return;
  696. }
  697. tor_asprintf(&s, "REVERSE[%s]", address);
  698. client_dns_set_addressmap_impl(for_conn, s, v, exitname, ttl);
  699. tor_free(s);
  700. }
  701. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  702. * These addresses should map to localhost, so even if the
  703. * application accidentally tried to connect to them directly (not
  704. * via Tor), it wouldn't get too far astray.
  705. *
  706. * These options are configured by parse_virtual_addr_network().
  707. */
  708. static virtual_addr_conf_t virtaddr_conf_ipv4;
  709. static virtual_addr_conf_t virtaddr_conf_ipv6;
  710. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  711. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  712. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  713. * string and return -1 on failure. If validate_only is false, sets the
  714. * actual virtual address range to the parsed value. */
  715. int
  716. parse_virtual_addr_network(const char *val, sa_family_t family,
  717. int validate_only,
  718. char **msg)
  719. {
  720. const int ipv6 = (family == AF_INET6);
  721. tor_addr_t addr;
  722. maskbits_t bits;
  723. const int max_prefix_bits = ipv6 ? 104 : 16;
  724. virtual_addr_conf_t *conf = ipv6 ? &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  725. if (!val || val[0] == '\0') {
  726. if (msg)
  727. tor_asprintf(msg, "Value not present (%s) after VirtualAddressNetwork%s",
  728. val?"Empty":"NULL", ipv6?"IPv6":"");
  729. return -1;
  730. }
  731. if (tor_addr_parse_mask_ports(val, 0, &addr, &bits, NULL, NULL) < 0) {
  732. if (msg)
  733. tor_asprintf(msg, "Error parsing VirtualAddressNetwork%s %s",
  734. ipv6?"IPv6":"", val);
  735. return -1;
  736. }
  737. if (tor_addr_family(&addr) != family) {
  738. if (msg)
  739. tor_asprintf(msg, "Incorrect address type for VirtualAddressNetwork%s",
  740. ipv6?"IPv6":"");
  741. return -1;
  742. }
  743. #if 0
  744. if (port_min != 1 || port_max != 65535) {
  745. if (msg)
  746. tor_asprintf(msg, "Can't specify ports on VirtualAddressNetwork%s",
  747. ipv6?"IPv6":"");
  748. return -1;
  749. }
  750. #endif /* 0 */
  751. if (bits > max_prefix_bits) {
  752. if (msg)
  753. tor_asprintf(msg, "VirtualAddressNetwork%s expects a /%d "
  754. "network or larger",ipv6?"IPv6":"", max_prefix_bits);
  755. return -1;
  756. }
  757. if (validate_only)
  758. return 0;
  759. tor_addr_copy(&conf->addr, &addr);
  760. conf->bits = bits;
  761. return 0;
  762. }
  763. /**
  764. * Return true iff <b>addr</b> is likely to have been returned by
  765. * client_dns_get_unused_address.
  766. **/
  767. int
  768. address_is_in_virtual_range(const char *address)
  769. {
  770. tor_addr_t addr;
  771. tor_assert(address);
  772. if (!strcasecmpend(address, ".virtual")) {
  773. return 1;
  774. } else if (tor_addr_parse(&addr, address) >= 0) {
  775. const virtual_addr_conf_t *conf = (tor_addr_family(&addr) == AF_INET6) ?
  776. &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  777. if (tor_addr_compare_masked(&addr, &conf->addr, conf->bits, CMP_EXACT)==0)
  778. return 1;
  779. }
  780. return 0;
  781. }
  782. /** Return a random address conforming to the virtual address configuration
  783. * in <b>conf</b>.
  784. */
  785. STATIC void
  786. get_random_virtual_addr(const virtual_addr_conf_t *conf, tor_addr_t *addr_out)
  787. {
  788. uint8_t tmp[4];
  789. const uint8_t *addr_bytes;
  790. uint8_t bytes[16];
  791. const int ipv6 = tor_addr_family(&conf->addr) == AF_INET6;
  792. const int total_bytes = ipv6 ? 16 : 4;
  793. tor_assert(conf->bits <= total_bytes * 8);
  794. /* Set addr_bytes to the bytes of the virtual network, in host order */
  795. if (ipv6) {
  796. addr_bytes = tor_addr_to_in6_addr8(&conf->addr);
  797. } else {
  798. set_uint32(tmp, tor_addr_to_ipv4n(&conf->addr));
  799. addr_bytes = tmp;
  800. }
  801. /* Get an appropriate number of random bytes. */
  802. crypto_rand((char*)bytes, total_bytes);
  803. /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
  804. if (conf->bits >= 8)
  805. memcpy(bytes, addr_bytes, conf->bits / 8);
  806. if (conf->bits & 7) {
  807. uint8_t mask = 0xff >> (conf->bits & 7);
  808. bytes[conf->bits/8] &= mask;
  809. bytes[conf->bits/8] |= addr_bytes[conf->bits/8] & ~mask;
  810. }
  811. if (ipv6)
  812. tor_addr_from_ipv6_bytes(addr_out, (char*) bytes);
  813. else
  814. tor_addr_from_ipv4n(addr_out, get_uint32(bytes));
  815. tor_assert(tor_addr_compare_masked(addr_out, &conf->addr,
  816. conf->bits, CMP_EXACT)==0);
  817. }
  818. /** Return a newly allocated string holding an address of <b>type</b>
  819. * (one of RESOLVED_TYPE_{IPV4|IPV6|HOSTNAME}) that has not yet been
  820. * mapped, and that is very unlikely to be the address of any real host.
  821. *
  822. * May return NULL if we have run out of virtual addresses.
  823. */
  824. static char *
  825. addressmap_get_virtual_address(int type)
  826. {
  827. char buf[64];
  828. tor_assert(addressmap);
  829. if (type == RESOLVED_TYPE_HOSTNAME) {
  830. char rand_bytes[10];
  831. do {
  832. crypto_rand(rand_bytes, sizeof(rand_bytes));
  833. base32_encode(buf,sizeof(buf),rand_bytes,sizeof(rand_bytes));
  834. strlcat(buf, ".virtual", sizeof(buf));
  835. } while (strmap_get(addressmap, buf));
  836. return tor_strdup(buf);
  837. } else if (type == RESOLVED_TYPE_IPV4 || type == RESOLVED_TYPE_IPV6) {
  838. const int ipv6 = (type == RESOLVED_TYPE_IPV6);
  839. const virtual_addr_conf_t *conf = ipv6 ?
  840. &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  841. /* Don't try more than 1000 times. This gives us P < 1e-9 for
  842. * failing to get a good address so long as the address space is
  843. * less than ~97.95% full. That's always going to be true under
  844. * sensible circumstances for an IPv6 /10, and it's going to be
  845. * true for an IPv4 /10 as long as we've handed out less than
  846. * 4.08 million addresses. */
  847. uint32_t attempts = 1000;
  848. tor_addr_t addr;
  849. while (attempts--) {
  850. get_random_virtual_addr(conf, &addr);
  851. if (!ipv6) {
  852. /* Don't hand out any .0 or .255 address. */
  853. const uint32_t a = tor_addr_to_ipv4h(&addr);
  854. if ((a & 0xff) == 0 || (a & 0xff) == 0xff)
  855. continue;
  856. }
  857. tor_addr_to_str(buf, &addr, sizeof(buf), 1);
  858. if (!strmap_get(addressmap, buf)) {
  859. /* XXXX This code is to make sure I didn't add an undecorated version
  860. * by mistake. I hope it's needless. */
  861. char tmp[TOR_ADDR_BUF_LEN];
  862. tor_addr_to_str(tmp, &addr, sizeof(tmp), 0);
  863. if (strmap_get(addressmap, tmp)) {
  864. log_warn(LD_BUG, "%s wasn't in the addressmap, but %s was.",
  865. buf, tmp);
  866. continue;
  867. }
  868. return tor_strdup(buf);
  869. }
  870. }
  871. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  872. return NULL;
  873. } else {
  874. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  875. return NULL;
  876. }
  877. }
  878. /** A controller has requested that we map some address of type
  879. * <b>type</b> to the address <b>new_address</b>. Choose an address
  880. * that is unlikely to be used, and map it, and return it in a newly
  881. * allocated string. If another address of the same type is already
  882. * mapped to <b>new_address</b>, try to return a copy of that address.
  883. *
  884. * The string in <b>new_address</b> may be freed or inserted into a map
  885. * as appropriate. May return NULL if are out of virtual addresses.
  886. **/
  887. const char *
  888. addressmap_register_virtual_address(int type, char *new_address)
  889. {
  890. char **addrp;
  891. virtaddress_entry_t *vent;
  892. int vent_needs_to_be_added = 0;
  893. tor_assert(new_address);
  894. tor_assert(addressmap);
  895. tor_assert(virtaddress_reversemap);
  896. vent = strmap_get(virtaddress_reversemap, new_address);
  897. if (!vent) {
  898. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  899. vent_needs_to_be_added = 1;
  900. }
  901. if (type == RESOLVED_TYPE_IPV4)
  902. addrp = &vent->ipv4_address;
  903. else if (type == RESOLVED_TYPE_IPV6)
  904. addrp = &vent->ipv6_address;
  905. else
  906. addrp = &vent->hostname_address;
  907. if (*addrp) {
  908. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  909. if (ent && ent->new_address &&
  910. !strcasecmp(new_address, ent->new_address)) {
  911. tor_free(new_address);
  912. tor_assert(!vent_needs_to_be_added);
  913. return *addrp;
  914. } else {
  915. log_warn(LD_BUG,
  916. "Internal confusion: I thought that '%s' was mapped to by "
  917. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  918. safe_str_client(new_address),
  919. safe_str_client(*addrp),
  920. safe_str_client(*addrp),
  921. ent?safe_str_client(ent->new_address):"(nothing)");
  922. }
  923. }
  924. tor_free(*addrp);
  925. *addrp = addressmap_get_virtual_address(type);
  926. if (!*addrp) {
  927. tor_free(vent);
  928. tor_free(new_address);
  929. return NULL;
  930. }
  931. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  932. if (vent_needs_to_be_added)
  933. strmap_set(virtaddress_reversemap, new_address, vent);
  934. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
  935. /* FFFF register corresponding reverse mapping. */
  936. #if 0
  937. {
  938. /* Try to catch possible bugs */
  939. addressmap_entry_t *ent;
  940. ent = strmap_get(addressmap, *addrp);
  941. tor_assert(ent);
  942. tor_assert(!strcasecmp(ent->new_address,new_address));
  943. vent = strmap_get(virtaddress_reversemap, new_address);
  944. tor_assert(vent);
  945. tor_assert(!strcasecmp(*addrp,
  946. (type == RESOLVED_TYPE_IPV4) ?
  947. vent->ipv4_address : vent->hostname_address));
  948. log_info(LD_APP, "Map from %s to %s okay.",
  949. safe_str_client(*addrp),
  950. safe_str_client(new_address));
  951. }
  952. #endif /* 0 */
  953. return *addrp;
  954. }
  955. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  956. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  957. * should be true if we're using this address as a client; false if we're
  958. * using it as a server.
  959. */
  960. int
  961. address_is_invalid_destination(const char *address, int client)
  962. {
  963. if (client) {
  964. if (get_options()->AllowNonRFC953Hostnames)
  965. return 0;
  966. } else {
  967. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  968. return 0;
  969. }
  970. /* It might be an IPv6 address! */
  971. {
  972. tor_addr_t a;
  973. if (tor_addr_parse(&a, address) >= 0)
  974. return 0;
  975. }
  976. while (*address) {
  977. if (TOR_ISALNUM(*address) ||
  978. *address == '-' ||
  979. *address == '.' ||
  980. *address == '_') /* Underscore is not allowed, but Windows does it
  981. * sometimes, just to thumb its nose at the IETF. */
  982. ++address;
  983. else
  984. return 1;
  985. }
  986. return 0;
  987. }
  988. /** Iterate over all address mappings which have expiry times between
  989. * min_expires and max_expires, inclusive. If sl is provided, add an
  990. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  991. * the expiry time if want_expiry is false. If sl is NULL, remove the
  992. * mappings.
  993. */
  994. void
  995. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  996. time_t max_expires, int want_expiry)
  997. {
  998. strmap_iter_t *iter;
  999. const char *key;
  1000. void *val_;
  1001. addressmap_entry_t *val;
  1002. if (!addressmap)
  1003. addressmap_init();
  1004. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  1005. strmap_iter_get(iter, &key, &val_);
  1006. val = val_;
  1007. if (val->expires >= min_expires && val->expires <= max_expires) {
  1008. if (!sl) {
  1009. iter = strmap_iter_next_rmv(addressmap,iter);
  1010. addressmap_ent_remove(key, val);
  1011. continue;
  1012. } else if (val->new_address) {
  1013. const char *src_wc = val->src_wildcard ? "*." : "";
  1014. const char *dst_wc = val->dst_wildcard ? "*." : "";
  1015. if (want_expiry) {
  1016. if (val->expires < 3 || val->expires == TIME_MAX)
  1017. smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
  1018. src_wc, key, dst_wc, val->new_address);
  1019. else {
  1020. char isotime[ISO_TIME_LEN+1];
  1021. format_iso_time(isotime, val->expires);
  1022. smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
  1023. src_wc, key, dst_wc, val->new_address,
  1024. isotime);
  1025. }
  1026. } else {
  1027. smartlist_add_asprintf(sl, "%s%s %s%s",
  1028. src_wc, key, dst_wc, val->new_address);
  1029. }
  1030. }
  1031. }
  1032. iter = strmap_iter_next(addressmap,iter);
  1033. }
  1034. }