addressmap.c 37 KB

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