addressmap.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. // LCOV_EXCL_START
  865. log_warn(LD_BUG, "%s wasn't in the addressmap, but %s was.",
  866. buf, tmp);
  867. continue;
  868. // LCOV_EXCL_STOP
  869. }
  870. return tor_strdup(buf);
  871. }
  872. }
  873. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  874. return NULL;
  875. } else {
  876. // LCOV_EXCL_START
  877. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  878. return NULL;
  879. // LCOV_EXCL_STOP
  880. }
  881. }
  882. /** A controller has requested that we map some address of type
  883. * <b>type</b> to the address <b>new_address</b>. Choose an address
  884. * that is unlikely to be used, and map it, and return it in a newly
  885. * allocated string. If another address of the same type is already
  886. * mapped to <b>new_address</b>, try to return a copy of that address.
  887. *
  888. * The string in <b>new_address</b> may be freed or inserted into a map
  889. * as appropriate. May return NULL if are out of virtual addresses.
  890. **/
  891. const char *
  892. addressmap_register_virtual_address(int type, char *new_address)
  893. {
  894. char **addrp;
  895. virtaddress_entry_t *vent;
  896. int vent_needs_to_be_added = 0;
  897. tor_assert(new_address);
  898. tor_assert(addressmap);
  899. tor_assert(virtaddress_reversemap);
  900. vent = strmap_get(virtaddress_reversemap, new_address);
  901. if (!vent) {
  902. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  903. vent_needs_to_be_added = 1;
  904. }
  905. if (type == RESOLVED_TYPE_IPV4)
  906. addrp = &vent->ipv4_address;
  907. else if (type == RESOLVED_TYPE_IPV6)
  908. addrp = &vent->ipv6_address;
  909. else
  910. addrp = &vent->hostname_address;
  911. if (*addrp) {
  912. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  913. if (ent && ent->new_address &&
  914. !strcasecmp(new_address, ent->new_address)) {
  915. tor_free(new_address);
  916. tor_assert(!vent_needs_to_be_added);
  917. return *addrp;
  918. } else {
  919. log_warn(LD_BUG,
  920. "Internal confusion: I thought that '%s' was mapped to by "
  921. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  922. safe_str_client(new_address),
  923. safe_str_client(*addrp),
  924. safe_str_client(*addrp),
  925. ent?safe_str_client(ent->new_address):"(nothing)");
  926. }
  927. }
  928. tor_free(*addrp);
  929. *addrp = addressmap_get_virtual_address(type);
  930. if (!*addrp) {
  931. tor_free(vent);
  932. tor_free(new_address);
  933. return NULL;
  934. }
  935. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  936. if (vent_needs_to_be_added)
  937. strmap_set(virtaddress_reversemap, new_address, vent);
  938. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
  939. /* FFFF register corresponding reverse mapping. */
  940. #if 0
  941. {
  942. /* Try to catch possible bugs */
  943. addressmap_entry_t *ent;
  944. ent = strmap_get(addressmap, *addrp);
  945. tor_assert(ent);
  946. tor_assert(!strcasecmp(ent->new_address,new_address));
  947. vent = strmap_get(virtaddress_reversemap, new_address);
  948. tor_assert(vent);
  949. tor_assert(!strcasecmp(*addrp,
  950. (type == RESOLVED_TYPE_IPV4) ?
  951. vent->ipv4_address : vent->hostname_address));
  952. log_info(LD_APP, "Map from %s to %s okay.",
  953. safe_str_client(*addrp),
  954. safe_str_client(new_address));
  955. }
  956. #endif /* 0 */
  957. return *addrp;
  958. }
  959. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  960. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  961. * should be true if we're using this address as a client; false if we're
  962. * using it as a server.
  963. */
  964. int
  965. address_is_invalid_destination(const char *address, int client)
  966. {
  967. if (client) {
  968. if (get_options()->AllowNonRFC953Hostnames)
  969. return 0;
  970. } else {
  971. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  972. return 0;
  973. }
  974. /* It might be an IPv6 address! */
  975. {
  976. tor_addr_t a;
  977. if (tor_addr_parse(&a, address) >= 0)
  978. return 0;
  979. }
  980. while (*address) {
  981. if (TOR_ISALNUM(*address) ||
  982. *address == '-' ||
  983. *address == '.' ||
  984. *address == '_') /* Underscore is not allowed, but Windows does it
  985. * sometimes, just to thumb its nose at the IETF. */
  986. ++address;
  987. else
  988. return 1;
  989. }
  990. return 0;
  991. }
  992. /** Iterate over all address mappings which have expiry times between
  993. * min_expires and max_expires, inclusive. If sl is provided, add an
  994. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  995. * the expiry time if want_expiry is false. If sl is NULL, remove the
  996. * mappings.
  997. */
  998. void
  999. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  1000. time_t max_expires, int want_expiry)
  1001. {
  1002. strmap_iter_t *iter;
  1003. const char *key;
  1004. void *val_;
  1005. addressmap_entry_t *val;
  1006. if (!addressmap)
  1007. addressmap_init();
  1008. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  1009. strmap_iter_get(iter, &key, &val_);
  1010. val = val_;
  1011. if (val->expires >= min_expires && val->expires <= max_expires) {
  1012. if (!sl) {
  1013. iter = strmap_iter_next_rmv(addressmap,iter);
  1014. addressmap_ent_remove(key, val);
  1015. continue;
  1016. } else if (val->new_address) {
  1017. const char *src_wc = val->src_wildcard ? "*." : "";
  1018. const char *dst_wc = val->dst_wildcard ? "*." : "";
  1019. if (want_expiry) {
  1020. if (val->expires < 3 || val->expires == TIME_MAX)
  1021. smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
  1022. src_wc, key, dst_wc, val->new_address);
  1023. else {
  1024. char isotime[ISO_TIME_LEN+1];
  1025. format_iso_time(isotime, val->expires);
  1026. smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
  1027. src_wc, key, dst_wc, val->new_address,
  1028. isotime);
  1029. }
  1030. } else {
  1031. smartlist_add_asprintf(sl, "%s%s %s%s",
  1032. src_wc, key, dst_wc, val->new_address);
  1033. }
  1034. }
  1035. }
  1036. iter = strmap_iter_next(addressmap,iter);
  1037. }
  1038. }