addressmap.c 37 KB

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