addressmap.c 34 KB

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