Do not replace a HS descriptor with a different replica of itself
[tor.git] / src / or / addressmap.c
blobd4b7acf27495a86052d471d5eed9123db7ca67b4
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 */
7 #define ADDRESSMAP_PRIVATE
9 #include "or.h"
10 #include "addressmap.h"
11 #include "circuituse.h"
12 #include "config.h"
13 #include "connection_edge.h"
14 #include "control.h"
15 #include "dns.h"
16 #include "routerset.h"
17 #include "nodelist.h"
19 /** A client-side struct to remember requests to rewrite addresses
20 * to new addresses. These structs are stored in the hash table
21 * "addressmap" below.
23 * There are 5 ways to set an address mapping:
24 * - A MapAddress command from the controller [permanent]
25 * - An AddressMap directive in the torrc [permanent]
26 * - When a TrackHostExits torrc directive is triggered [temporary]
27 * - When a DNS resolve succeeds [temporary]
28 * - When a DNS resolve fails [temporary]
30 * When an addressmap request is made but one is already registered,
31 * the new one is replaced only if the currently registered one has
32 * no "new_address" (that is, it's in the process of DNS resolve),
33 * or if the new one is permanent (expires==0 or 1).
35 * (We overload the 'expires' field, using "0" for mappings set via
36 * the configuration file, "1" for mappings set from the control
37 * interface, and other values for DNS and TrackHostExit mappings that can
38 * expire.)
40 * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
41 * any address that ends with a . followed by the key for this entry will
42 * get remapped by it. If "dst_wildcard" is also true, then only the
43 * matching suffix of such addresses will get replaced by new_address.
45 typedef struct {
46 char *new_address;
47 time_t expires;
48 addressmap_entry_source_bitfield_t source:3;
49 unsigned src_wildcard:1;
50 unsigned dst_wildcard:1;
51 short num_resolve_failures;
52 } addressmap_entry_t;
54 /** Entry for mapping addresses to which virtual address we mapped them to. */
55 typedef struct {
56 char *ipv4_address;
57 char *ipv6_address;
58 char *hostname_address;
59 } virtaddress_entry_t;
61 /** A hash table to store client-side address rewrite instructions. */
62 static strmap_t *addressmap=NULL;
64 /**
65 * Table mapping addresses to which virtual address, if any, we
66 * assigned them to.
68 * We maintain the following invariant: if [A,B] is in
69 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
70 * must be in addressmap. We do not require that the converse hold:
71 * if it fails, then we could end up mapping two virtual addresses to
72 * the same address, which is no disaster.
73 **/
74 static strmap_t *virtaddress_reversemap=NULL;
76 /** Initialize addressmap. */
77 void
78 addressmap_init(void)
80 addressmap = strmap_new();
81 virtaddress_reversemap = strmap_new();
84 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
85 static void
86 addressmap_ent_free(void *_ent)
88 addressmap_entry_t *ent;
89 if (!_ent)
90 return;
92 ent = _ent;
93 tor_free(ent->new_address);
94 tor_free(ent);
97 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
98 static void
99 addressmap_virtaddress_ent_free(void *_ent)
101 virtaddress_entry_t *ent;
102 if (!_ent)
103 return;
105 ent = _ent;
106 tor_free(ent->ipv4_address);
107 tor_free(ent->hostname_address);
108 tor_free(ent);
111 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
112 static void
113 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
115 if (ent && ent->new_address &&
116 address_is_in_virtual_range(ent->new_address)) {
117 virtaddress_entry_t *ve =
118 strmap_get(virtaddress_reversemap, ent->new_address);
119 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
120 if (ve) {
121 if (!strcmp(address, ve->ipv4_address))
122 tor_free(ve->ipv4_address);
123 if (!strcmp(address, ve->hostname_address))
124 tor_free(ve->hostname_address);
125 if (!ve->ipv4_address && !ve->hostname_address) {
126 tor_free(ve);
127 strmap_remove(virtaddress_reversemap, ent->new_address);
133 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
134 * client address maps. */
135 static void
136 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
138 addressmap_virtaddress_remove(address, ent);
139 addressmap_ent_free(ent);
142 /** Unregister all TrackHostExits mappings from any address to
143 * *.exitname.exit. */
144 void
145 clear_trackexithost_mappings(const char *exitname)
147 char *suffix = NULL;
148 if (!addressmap || !exitname)
149 return;
150 tor_asprintf(&suffix, ".%s.exit", exitname);
151 tor_strlower(suffix);
153 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
154 if (ent->source == ADDRMAPSRC_TRACKEXIT &&
155 !strcmpend(ent->new_address, suffix)) {
156 addressmap_ent_remove(address, ent);
157 MAP_DEL_CURRENT(address);
159 } STRMAP_FOREACH_END;
161 tor_free(suffix);
164 /** Remove all TRACKEXIT mappings from the addressmap for which the target
165 * host is unknown or no longer allowed, or for which the source address
166 * is no longer in trackexithosts. */
167 void
168 addressmap_clear_excluded_trackexithosts(const or_options_t *options)
170 const routerset_t *allow_nodes = options->ExitNodes;
171 const routerset_t *exclude_nodes = options->ExcludeExitNodesUnion_;
173 if (!addressmap)
174 return;
175 if (routerset_is_empty(allow_nodes))
176 allow_nodes = NULL;
177 if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
178 return;
180 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
181 size_t len;
182 const char *target = ent->new_address, *dot;
183 char *nodename;
184 const node_t *node;
186 if (!target) {
187 /* DNS resolving in progress */
188 continue;
189 } else if (strcmpend(target, ".exit")) {
190 /* Not a .exit mapping */
191 continue;
192 } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
193 /* Not a trackexit mapping. */
194 continue;
196 len = strlen(target);
197 if (len < 6)
198 continue; /* malformed. */
199 dot = target + len - 6; /* dot now points to just before .exit */
200 while (dot > target && *dot != '.')
201 dot--;
202 if (*dot == '.') dot++;
203 nodename = tor_strndup(dot, len-5-(dot-target));;
204 node = node_get_by_nickname(nodename, 0);
205 tor_free(nodename);
206 if (!node ||
207 (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
208 routerset_contains_node(exclude_nodes, node) ||
209 !hostname_in_track_host_exits(options, address)) {
210 /* We don't know this one, or we want to be rid of it. */
211 addressmap_ent_remove(address, ent);
212 MAP_DEL_CURRENT(address);
214 } STRMAP_FOREACH_END;
217 /** Return true iff <b>address</b> is one that we are configured to
218 * automap on resolve according to <b>options</b>. */
220 addressmap_address_should_automap(const char *address,
221 const or_options_t *options)
223 const smartlist_t *suffix_list = options->AutomapHostsSuffixes;
225 if (!suffix_list)
226 return 0;
228 SMARTLIST_FOREACH_BEGIN(suffix_list, const char *, suffix) {
229 if (!strcasecmpend(address, suffix))
230 return 1;
231 } SMARTLIST_FOREACH_END(suffix);
232 return 0;
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)
242 int clear_all = !options->AutomapHostsOnResolve;
243 const smartlist_t *suffixes = options->AutomapHostsSuffixes;
245 if (!addressmap)
246 return;
248 if (!suffixes)
249 clear_all = 1; /* This should be impossible, but let's be sure. */
251 STRMAP_FOREACH_MODIFY(addressmap, src_address, addressmap_entry_t *, ent) {
252 int remove = clear_all;
253 if (ent->source != ADDRMAPSRC_AUTOMAP)
254 continue; /* not an automap mapping. */
256 if (!remove) {
257 remove = ! addressmap_address_should_automap(src_address, options);
260 if (!remove && ! address_is_in_virtual_range(ent->new_address))
261 remove = 1;
263 if (remove) {
264 addressmap_ent_remove(src_address, ent);
265 MAP_DEL_CURRENT(src_address);
267 } STRMAP_FOREACH_END;
270 /** Remove all entries from the addressmap that were set via the
271 * configuration file or the command line. */
272 void
273 addressmap_clear_configured(void)
275 addressmap_get_mappings(NULL, 0, 0, 0);
278 /** Remove all entries from the addressmap that are set to expire, ever. */
279 void
280 addressmap_clear_transient(void)
282 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
285 /** Clean out entries from the addressmap cache that were
286 * added long enough ago that they are no longer valid.
288 void
289 addressmap_clean(time_t now)
291 addressmap_get_mappings(NULL, 2, now, 0);
294 /** Free all the elements in the addressmap, and free the addressmap
295 * itself. */
296 void
297 addressmap_free_all(void)
299 strmap_free(addressmap, addressmap_ent_free);
300 addressmap = NULL;
302 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
303 virtaddress_reversemap = NULL;
306 /** Try to find a match for AddressMap expressions that use
307 * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
308 * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
309 * Return the matching entry in AddressMap or NULL if no match is found.
310 * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
311 * to 'a' before we return the matching AddressMap entry.
313 * This function does not handle the case where a pattern of the form "*.c.d"
314 * matches the address c.d -- that's done by the main addressmap_rewrite
315 * function.
317 static addressmap_entry_t *
318 addressmap_match_superdomains(char *address)
320 addressmap_entry_t *val;
321 char *cp;
323 cp = address;
324 while ((cp = strchr(cp, '.'))) {
325 /* cp now points to a suffix of address that begins with a . */
326 val = strmap_get_lc(addressmap, cp+1);
327 if (val && val->src_wildcard) {
328 if (val->dst_wildcard)
329 *cp = '\0';
330 return val;
332 ++cp;
334 return NULL;
337 /** Look at address, and rewrite it until it doesn't want any
338 * more rewrites; but don't get into an infinite loop.
339 * Don't write more than maxlen chars into address. Return true if the
340 * address changed; false otherwise. Set *<b>expires_out</b> to the
341 * expiry time of the result, or to <b>time_max</b> if the result does
342 * not expire.
344 * If <b>exit_source_out</b> is non-null, we set it as follows. If we the
345 * address starts out as a non-exit address, and we remap it to an .exit
346 * address at any point, then set *<b>exit_source_out</b> to the
347 * address_entry_source_t of the first such rule. Set *<b>exit_source_out</b>
348 * to ADDRMAPSRC_NONE if there is no such rewrite, or if the original address
349 * was a .exit.
352 addressmap_rewrite(char *address, size_t maxlen,
353 unsigned flags,
354 time_t *expires_out,
355 addressmap_entry_source_t *exit_source_out)
357 addressmap_entry_t *ent;
358 int rewrites;
359 time_t expires = TIME_MAX;
360 addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
361 char *addr_orig = tor_strdup(address);
362 char *log_addr_orig = NULL;
364 for (rewrites = 0; rewrites < 16; rewrites++) {
365 int exact_match = 0;
366 log_addr_orig = tor_strdup(escaped_safe_str_client(address));
368 ent = strmap_get(addressmap, address);
370 if (!ent || !ent->new_address) {
371 ent = addressmap_match_superdomains(address);
372 } else {
373 if (ent->src_wildcard && !ent->dst_wildcard &&
374 !strcasecmp(address, ent->new_address)) {
375 /* This is a rule like *.example.com example.com, and we just got
376 * "example.com" */
377 goto done;
380 exact_match = 1;
383 if (!ent || !ent->new_address) {
384 goto done;
387 if (ent && ent->source == ADDRMAPSRC_DNS) {
388 sa_family_t f;
389 tor_addr_t tmp;
390 f = tor_addr_parse(&tmp, ent->new_address);
391 if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
392 goto done;
393 else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
394 goto done;
397 if (ent->dst_wildcard && !exact_match) {
398 strlcat(address, ".", maxlen);
399 strlcat(address, ent->new_address, maxlen);
400 } else {
401 strlcpy(address, ent->new_address, maxlen);
404 if (!strcmpend(address, ".exit") &&
405 strcmpend(addr_orig, ".exit") &&
406 exit_source == ADDRMAPSRC_NONE) {
407 exit_source = ent->source;
410 log_info(LD_APP, "Addressmap: rewriting %s to %s",
411 log_addr_orig, escaped_safe_str_client(address));
412 if (ent->expires > 1 && ent->expires < expires)
413 expires = ent->expires;
415 tor_free(log_addr_orig);
417 log_warn(LD_CONFIG,
418 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
419 escaped_safe_str_client(address));
420 /* it's fine to rewrite a rewrite, but don't loop forever */
422 done:
423 tor_free(addr_orig);
424 tor_free(log_addr_orig);
425 if (exit_source_out)
426 *exit_source_out = exit_source;
427 if (expires_out)
428 *expires_out = TIME_MAX;
429 return (rewrites > 0);
432 /** If we have a cached reverse DNS entry for the address stored in the
433 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
434 * rewrite to the cached value and return 1. Otherwise return 0. Set
435 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
436 * if the result does not expire. */
438 addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags,
439 time_t *expires_out)
441 char *s, *cp;
442 addressmap_entry_t *ent;
443 int r = 0;
445 sa_family_t f;
446 tor_addr_t tmp;
447 f = tor_addr_parse(&tmp, address);
448 if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
449 return 0;
450 else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
451 return 0;
454 tor_asprintf(&s, "REVERSE[%s]", address);
455 ent = strmap_get(addressmap, s);
456 if (ent) {
457 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
458 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
459 escaped_safe_str_client(s), cp);
460 tor_free(cp);
461 strlcpy(address, ent->new_address, maxlen);
462 r = 1;
465 if (expires_out)
466 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
468 tor_free(s);
469 return r;
472 /** Return 1 if <b>address</b> is already registered, else return 0. If address
473 * is already registered, and <b>update_expires</b> is non-zero, then update
474 * the expiry time on the mapping with update_expires if it is a
475 * mapping created by TrackHostExits. */
477 addressmap_have_mapping(const char *address, int update_expiry)
479 addressmap_entry_t *ent;
480 if (!(ent=strmap_get_lc(addressmap, address)))
481 return 0;
482 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
483 ent->expires=time(NULL) + update_expiry;
484 return 1;
487 /** Register a request to map <b>address</b> to <b>new_address</b>,
488 * which will expire on <b>expires</b> (or 0 if never expires from
489 * config file, 1 if never expires from controller, 2 if never expires
490 * (virtual address mapping) from the controller.)
492 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
493 * free as appropriate. We will leave address alone.
495 * If <b>wildcard_addr</b> is true, then the mapping will match any address
496 * equal to <b>address</b>, or any address ending with a period followed by
497 * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
498 * both true, the mapping will rewrite addresses that end with
499 * ".<b>address</b>" into ones that end with ".<b>new_address</b>."
501 * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
502 * <b>address</b> and <b>wildcard_addr</b> is equal to
503 * <b>wildcard_new_addr</b>, remove any mappings that exist from
504 * <b>address</b>.
507 * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
508 * not set. */
509 void
510 addressmap_register(const char *address, char *new_address, time_t expires,
511 addressmap_entry_source_t source,
512 const int wildcard_addr,
513 const int wildcard_new_addr)
515 addressmap_entry_t *ent;
517 if (wildcard_new_addr)
518 tor_assert(wildcard_addr);
520 ent = strmap_get(addressmap, address);
521 if (!new_address || (!strcasecmp(address,new_address) &&
522 wildcard_addr == wildcard_new_addr)) {
523 /* Remove the mapping, if any. */
524 tor_free(new_address);
525 if (ent) {
526 addressmap_ent_remove(address,ent);
527 strmap_remove(addressmap, address);
529 return;
531 if (!ent) { /* make a new one and register it */
532 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
533 strmap_set(addressmap, address, ent);
534 } else if (ent->new_address) { /* we need to clean up the old mapping. */
535 if (expires > 1) {
536 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
537 "since it's already mapped to '%s'",
538 safe_str_client(address),
539 safe_str_client(new_address),
540 safe_str_client(ent->new_address));
541 tor_free(new_address);
542 return;
544 if (address_is_in_virtual_range(ent->new_address) &&
545 expires != 2) {
546 /* XXX This isn't the perfect test; we want to avoid removing
547 * mappings set from the control interface _as virtual mapping */
548 addressmap_virtaddress_remove(address, ent);
550 tor_free(ent->new_address);
551 } /* else { we have an in-progress resolve with no mapping. } */
553 ent->new_address = new_address;
554 ent->expires = expires==2 ? 1 : expires;
555 ent->num_resolve_failures = 0;
556 ent->source = source;
557 ent->src_wildcard = wildcard_addr ? 1 : 0;
558 ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
560 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
561 safe_str_client(address),
562 safe_str_client(ent->new_address));
563 control_event_address_mapped(address, ent->new_address, expires, NULL, 1);
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.
571 client_dns_incr_failures(const char *address)
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);
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;
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.
592 void
593 client_dns_clear_failures(const char *address)
595 addressmap_entry_t *ent = strmap_get(addressmap, address);
596 if (ent)
597 ent->num_resolve_failures = 0;
600 /** Record the fact that <b>address</b> resolved to <b>name</b>.
601 * We can now use this in subsequent streams via addressmap_rewrite()
602 * so we can more correctly choose an exit that will allow <b>address</b>.
604 * If <b>exitname</b> is defined, then append the addresses with
605 * ".exitname.exit" before registering the mapping.
607 * If <b>ttl</b> is nonnegative, the mapping will be valid for
608 * <b>ttl</b>seconds; otherwise, we use the default.
610 static void
611 client_dns_set_addressmap_impl(entry_connection_t *for_conn,
612 const char *address, const char *name,
613 const char *exitname,
614 int ttl)
616 char *extendedaddress=NULL, *extendedval=NULL;
617 (void)for_conn;
619 tor_assert(address);
620 tor_assert(name);
622 if (ttl<0)
623 ttl = DEFAULT_DNS_TTL;
624 else
625 ttl = dns_clip_ttl(ttl);
627 if (exitname) {
628 /* XXXX fails to ever get attempts to get an exit address of
629 * google.com.digest[=~]nickname.exit; we need a syntax for this that
630 * won't make strict RFC952-compliant applications (like us) barf. */
631 tor_asprintf(&extendedaddress,
632 "%s.%s.exit", address, exitname);
633 tor_asprintf(&extendedval,
634 "%s.%s.exit", name, exitname);
635 } else {
636 tor_asprintf(&extendedaddress,
637 "%s", address);
638 tor_asprintf(&extendedval,
639 "%s", name);
641 addressmap_register(extendedaddress, extendedval,
642 time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
643 tor_free(extendedaddress);
646 /** Record the fact that <b>address</b> resolved to <b>val</b>.
647 * We can now use this in subsequent streams via addressmap_rewrite()
648 * so we can more correctly choose an exit that will allow <b>address</b>.
650 * If <b>exitname</b> is defined, then append the addresses with
651 * ".exitname.exit" before registering the mapping.
653 * If <b>ttl</b> is nonnegative, the mapping will be valid for
654 * <b>ttl</b>seconds; otherwise, we use the default.
656 void
657 client_dns_set_addressmap(entry_connection_t *for_conn,
658 const char *address,
659 const tor_addr_t *val,
660 const char *exitname,
661 int ttl)
663 tor_addr_t addr_tmp;
664 char valbuf[TOR_ADDR_BUF_LEN];
666 tor_assert(address);
667 tor_assert(val);
669 if (tor_addr_parse(&addr_tmp, address) >= 0)
670 return; /* If address was an IP address already, don't add a mapping. */
672 if (tor_addr_family(val) == AF_INET) {
673 if (! for_conn->cache_ipv4_answers)
674 return;
675 } else if (tor_addr_family(val) == AF_INET6) {
676 if (! for_conn->cache_ipv6_answers)
677 return;
680 if (! tor_addr_to_str(valbuf, val, sizeof(valbuf), 1))
681 return;
683 client_dns_set_addressmap_impl(for_conn, address, valbuf, exitname, ttl);
686 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
687 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
689 * If <b>exitname</b> is defined, then append the addresses with
690 * ".exitname.exit" before registering the mapping.
692 * If <b>ttl</b> is nonnegative, the mapping will be valid for
693 * <b>ttl</b>seconds; otherwise, we use the default.
695 void
696 client_dns_set_reverse_addressmap(entry_connection_t *for_conn,
697 const char *address, const char *v,
698 const char *exitname,
699 int ttl)
701 char *s = NULL;
703 tor_addr_t tmp_addr;
704 sa_family_t f = tor_addr_parse(&tmp_addr, address);
705 if ((f == AF_INET && ! for_conn->cache_ipv4_answers) ||
706 (f == AF_INET6 && ! for_conn->cache_ipv6_answers))
707 return;
709 tor_asprintf(&s, "REVERSE[%s]", address);
710 client_dns_set_addressmap_impl(for_conn, s, v, exitname, ttl);
711 tor_free(s);
714 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
715 * These addresses should map to localhost, so even if the
716 * application accidentally tried to connect to them directly (not
717 * via Tor), it wouldn't get too far astray.
719 * These options are configured by parse_virtual_addr_network().
722 static virtual_addr_conf_t virtaddr_conf_ipv4;
723 static virtual_addr_conf_t virtaddr_conf_ipv6;
725 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
726 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
727 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
728 * string and return -1 on failure. If validate_only is false, sets the
729 * actual virtual address range to the parsed value. */
731 parse_virtual_addr_network(const char *val, sa_family_t family,
732 int validate_only,
733 char **msg)
735 const int ipv6 = (family == AF_INET6);
736 tor_addr_t addr;
737 maskbits_t bits;
738 const int max_bits = ipv6 ? 40 : 16;
739 virtual_addr_conf_t *conf = ipv6 ? &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
741 if (!val || val[0] == '\0') {
742 if (msg)
743 tor_asprintf(msg, "Value not present (%s) after VirtualAddressNetwork%s",
744 val?"Empty":"NULL", ipv6?"IPv6":"");
745 return -1;
747 if (tor_addr_parse_mask_ports(val, 0, &addr, &bits, NULL, NULL) < 0) {
748 if (msg)
749 tor_asprintf(msg, "Error parsing VirtualAddressNetwork%s %s",
750 ipv6?"IPv6":"", val);
751 return -1;
753 if (tor_addr_family(&addr) != family) {
754 if (msg)
755 tor_asprintf(msg, "Incorrect address type for VirtualAddressNetwork%s",
756 ipv6?"IPv6":"");
757 return -1;
759 #if 0
760 if (port_min != 1 || port_max != 65535) {
761 if (msg)
762 tor_asprintf(msg, "Can't specify ports on VirtualAddressNetwork%s",
763 ipv6?"IPv6":"");
764 return -1;
766 #endif
768 if (bits > max_bits) {
769 if (msg)
770 tor_asprintf(msg, "VirtualAddressNetwork%s expects a /%d "
771 "network or larger",ipv6?"IPv6":"", max_bits);
772 return -1;
775 if (validate_only)
776 return 0;
778 tor_addr_copy(&conf->addr, &addr);
779 conf->bits = bits;
781 return 0;
785 * Return true iff <b>addr</b> is likely to have been returned by
786 * client_dns_get_unused_address.
789 address_is_in_virtual_range(const char *address)
791 tor_addr_t addr;
792 tor_assert(address);
793 if (!strcasecmpend(address, ".virtual")) {
794 return 1;
795 } else if (tor_addr_parse(&addr, address) >= 0) {
796 const virtual_addr_conf_t *conf = (tor_addr_family(&addr) == AF_INET6) ?
797 &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
798 if (tor_addr_compare_masked(&addr, &conf->addr, conf->bits, CMP_EXACT)==0)
799 return 1;
801 return 0;
804 /** Return a random address conforming to the virtual address configuration
805 * in <b>conf</b>.
807 STATIC void
808 get_random_virtual_addr(const virtual_addr_conf_t *conf, tor_addr_t *addr_out)
810 uint8_t tmp[4];
811 const uint8_t *addr_bytes;
812 uint8_t bytes[16];
813 const int ipv6 = tor_addr_family(&conf->addr) == AF_INET6;
814 const int total_bytes = ipv6 ? 16 : 4;
816 tor_assert(conf->bits <= total_bytes * 8);
818 /* Set addr_bytes to the bytes of the virtual network, in host order */
819 if (ipv6) {
820 addr_bytes = tor_addr_to_in6_addr8(&conf->addr);
821 } else {
822 set_uint32(tmp, tor_addr_to_ipv4n(&conf->addr));
823 addr_bytes = tmp;
826 /* Get an appropriate number of random bytes. */
827 crypto_rand((char*)bytes, total_bytes);
829 /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
830 if (conf->bits >= 8)
831 memcpy(bytes, addr_bytes, conf->bits / 8);
832 if (conf->bits & 7) {
833 uint8_t mask = 0xff >> (conf->bits & 7);
834 bytes[conf->bits/8] &= mask;
835 bytes[conf->bits/8] |= addr_bytes[conf->bits/8] & ~mask;
838 if (ipv6)
839 tor_addr_from_ipv6_bytes(addr_out, (char*) bytes);
840 else
841 tor_addr_from_ipv4n(addr_out, get_uint32(bytes));
843 tor_assert(tor_addr_compare_masked(addr_out, &conf->addr,
844 conf->bits, CMP_EXACT)==0);
847 /** Return a newly allocated string holding an address of <b>type</b>
848 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
849 * and that is very unlikely to be the address of any real host.
851 * May return NULL if we have run out of virtual addresses.
853 static char *
854 addressmap_get_virtual_address(int type)
856 char buf[64];
857 tor_assert(addressmap);
859 if (type == RESOLVED_TYPE_HOSTNAME) {
860 char rand[10];
861 do {
862 crypto_rand(rand, sizeof(rand));
863 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
864 strlcat(buf, ".virtual", sizeof(buf));
865 } while (strmap_get(addressmap, buf));
866 return tor_strdup(buf);
867 } else if (type == RESOLVED_TYPE_IPV4 || type == RESOLVED_TYPE_IPV6) {
868 const int ipv6 = (type == RESOLVED_TYPE_IPV6);
869 const virtual_addr_conf_t *conf = ipv6 ?
870 &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
872 /* Don't try more than 1000 times. This gives us P < 1e-9 for
873 * failing to get a good address so long as the address space is
874 * less than ~97.95% full. That's always going to be true under
875 * sensible circumstances for an IPv6 /10, and it's going to be
876 * true for an IPv4 /10 as long as we've handed out less than
877 * 4.08 million addresses. */
878 uint32_t attempts = 1000;
880 tor_addr_t addr;
882 while (attempts--) {
883 get_random_virtual_addr(conf, &addr);
885 if (!ipv6) {
886 /* Don't hand out any .0 or .255 address. */
887 const uint32_t a = tor_addr_to_ipv4h(&addr);
888 if ((a & 0xff) == 0 || (a & 0xff) == 0xff)
889 continue;
892 tor_addr_to_str(buf, &addr, sizeof(buf), 1);
893 if (!strmap_get(addressmap, buf)) {
894 /* XXXX This code is to make sure I didn't add an undecorated version
895 * by mistake. I hope it's needless. */
896 char tmp[TOR_ADDR_BUF_LEN];
897 tor_addr_to_str(buf, &addr, sizeof(tmp), 0);
898 if (strmap_get(addressmap, tmp)) {
899 log_warn(LD_BUG, "%s wasn't in the addressmap, but %s was.",
900 buf, tmp);
901 continue;
904 return tor_strdup(buf);
907 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
908 return NULL;
909 } else {
910 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
911 return NULL;
915 /** A controller has requested that we map some address of type
916 * <b>type</b> to the address <b>new_address</b>. Choose an address
917 * that is unlikely to be used, and map it, and return it in a newly
918 * allocated string. If another address of the same type is already
919 * mapped to <b>new_address</b>, try to return a copy of that address.
921 * The string in <b>new_address</b> may be freed or inserted into a map
922 * as appropriate. May return NULL if are out of virtual addresses.
924 const char *
925 addressmap_register_virtual_address(int type, char *new_address)
927 char **addrp;
928 virtaddress_entry_t *vent;
929 int vent_needs_to_be_added = 0;
931 tor_assert(new_address);
932 tor_assert(addressmap);
933 tor_assert(virtaddress_reversemap);
935 vent = strmap_get(virtaddress_reversemap, new_address);
936 if (!vent) {
937 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
938 vent_needs_to_be_added = 1;
941 if (type == RESOLVED_TYPE_IPV4)
942 addrp = &vent->ipv4_address;
943 else if (type == RESOLVED_TYPE_IPV6)
944 addrp = &vent->ipv6_address;
945 else
946 addrp = &vent->hostname_address;
948 if (*addrp) {
949 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
950 if (ent && ent->new_address &&
951 !strcasecmp(new_address, ent->new_address)) {
952 tor_free(new_address);
953 tor_assert(!vent_needs_to_be_added);
954 return *addrp;
955 } else {
956 log_warn(LD_BUG,
957 "Internal confusion: I thought that '%s' was mapped to by "
958 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
959 safe_str_client(new_address),
960 safe_str_client(*addrp),
961 safe_str_client(*addrp),
962 ent?safe_str_client(ent->new_address):"(nothing)");
966 tor_free(*addrp);
967 *addrp = addressmap_get_virtual_address(type);
968 if (!*addrp) {
969 tor_free(vent);
970 tor_free(new_address);
971 return NULL;
973 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
974 if (vent_needs_to_be_added)
975 strmap_set(virtaddress_reversemap, new_address, vent);
976 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
978 #if 0
980 /* Try to catch possible bugs */
981 addressmap_entry_t *ent;
982 ent = strmap_get(addressmap, *addrp);
983 tor_assert(ent);
984 tor_assert(!strcasecmp(ent->new_address,new_address));
985 vent = strmap_get(virtaddress_reversemap, new_address);
986 tor_assert(vent);
987 tor_assert(!strcasecmp(*addrp,
988 (type == RESOLVED_TYPE_IPV4) ?
989 vent->ipv4_address : vent->hostname_address));
990 log_info(LD_APP, "Map from %s to %s okay.",
991 safe_str_client(*addrp),
992 safe_str_client(new_address));
994 #endif
996 return *addrp;
999 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1000 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1001 * should be true if we're using this address as a client; false if we're
1002 * using it as a server.
1005 address_is_invalid_destination(const char *address, int client)
1007 if (client) {
1008 if (get_options()->AllowNonRFC953Hostnames)
1009 return 0;
1010 } else {
1011 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1012 return 0;
1015 /* It might be an IPv6 address! */
1017 tor_addr_t a;
1018 if (tor_addr_parse(&a, address) >= 0)
1019 return 0;
1022 while (*address) {
1023 if (TOR_ISALNUM(*address) ||
1024 *address == '-' ||
1025 *address == '.' ||
1026 *address == '_') /* Underscore is not allowed, but Windows does it
1027 * sometimes, just to thumb its nose at the IETF. */
1028 ++address;
1029 else
1030 return 1;
1032 return 0;
1035 /** Iterate over all address mappings which have expiry times between
1036 * min_expires and max_expires, inclusive. If sl is provided, add an
1037 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1038 * the expiry time if want_expiry is false. If sl is NULL, remove the
1039 * mappings.
1041 void
1042 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1043 time_t max_expires, int want_expiry)
1045 strmap_iter_t *iter;
1046 const char *key;
1047 void *val_;
1048 addressmap_entry_t *val;
1050 if (!addressmap)
1051 addressmap_init();
1053 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1054 strmap_iter_get(iter, &key, &val_);
1055 val = val_;
1056 if (val->expires >= min_expires && val->expires <= max_expires) {
1057 if (!sl) {
1058 iter = strmap_iter_next_rmv(addressmap,iter);
1059 addressmap_ent_remove(key, val);
1060 continue;
1061 } else if (val->new_address) {
1062 const char *src_wc = val->src_wildcard ? "*." : "";
1063 const char *dst_wc = val->dst_wildcard ? "*." : "";
1064 if (want_expiry) {
1065 if (val->expires < 3 || val->expires == TIME_MAX)
1066 smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
1067 src_wc, key, dst_wc, val->new_address);
1068 else {
1069 char time[ISO_TIME_LEN+1];
1070 format_iso_time(time, val->expires);
1071 smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
1072 src_wc, key, dst_wc, val->new_address,
1073 time);
1075 } else {
1076 smartlist_add_asprintf(sl, "%s%s %s%s",
1077 src_wc, key, dst_wc, val->new_address);
1081 iter = strmap_iter_next(addressmap,iter);