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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 * \brief The addressmap module manages the processes by which we rewrite
11 * addresses in client requess. It handles the MapAddress controller and
12 * torrc commands, and the TrackHostExits feature, and the client-side DNS
16 #define ADDRESSMAP_PRIVATE
19 #include "addressmap.h"
20 #include "circuituse.h"
22 #include "connection_edge.h"
25 #include "routerset.h"
28 /** A client-side struct to remember requests to rewrite addresses
29 * to new addresses. These structs are stored in the hash table
32 * There are 5 ways to set an address mapping:
33 * - A MapAddress command from the controller [permanent]
34 * - An AddressMap directive in the torrc [permanent]
35 * - When a TrackHostExits torrc directive is triggered [temporary]
36 * - When a DNS resolve succeeds [temporary]
37 * - When a DNS resolve fails [temporary]
39 * When an addressmap request is made but one is already registered,
40 * the new one is replaced only if the currently registered one has
41 * no "new_address" (that is, it's in the process of DNS resolve),
42 * or if the new one is permanent (expires==0 or 1).
44 * (We overload the 'expires' field, using "0" for mappings set via
45 * the configuration file, "1" for mappings set from the control
46 * interface, and other values for DNS and TrackHostExit mappings that can
49 * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
50 * any address that ends with a . followed by the key for this entry will
51 * get remapped by it. If "dst_wildcard" is also true, then only the
52 * matching suffix of such addresses will get replaced by new_address.
57 addressmap_entry_source_bitfield_t source
:3;
58 unsigned src_wildcard
:1;
59 unsigned dst_wildcard
:1;
60 short num_resolve_failures
;
63 /** Entry for mapping addresses to which virtual address we mapped them to. */
67 char *hostname_address
;
68 } virtaddress_entry_t
;
70 /** A hash table to store client-side address rewrite instructions. */
71 static strmap_t
*addressmap
=NULL
;
74 * Table mapping addresses to which virtual address, if any, we
77 * We maintain the following invariant: if [A,B] is in
78 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
79 * must be in addressmap. We do not require that the converse hold:
80 * if it fails, then we could end up mapping two virtual addresses to
81 * the same address, which is no disaster.
83 static strmap_t
*virtaddress_reversemap
=NULL
;
85 /** Initialize addressmap. */
89 addressmap
= strmap_new();
90 virtaddress_reversemap
= strmap_new();
93 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
95 addressmap_ent_free(void *_ent
)
97 addressmap_entry_t
*ent
;
102 tor_free(ent
->new_address
);
106 /** Free storage held by a virtaddress_entry_t* entry in <b>_ent</b>. */
108 addressmap_virtaddress_ent_free(void *_ent
)
110 virtaddress_entry_t
*ent
;
115 tor_free(ent
->ipv4_address
);
116 tor_free(ent
->ipv6_address
);
117 tor_free(ent
->hostname_address
);
121 /** Remove <b>address</b> (which must map to <b>ent</b>) from the
122 * virtual address map. */
124 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
126 if (ent
&& ent
->new_address
&&
127 address_is_in_virtual_range(ent
->new_address
)) {
128 virtaddress_entry_t
*ve
=
129 strmap_get(virtaddress_reversemap
, ent
->new_address
);
130 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
132 if (!strcmp(address
, ve
->ipv4_address
))
133 tor_free(ve
->ipv4_address
);
134 if (!strcmp(address
, ve
->ipv6_address
))
135 tor_free(ve
->ipv6_address
);
136 if (!strcmp(address
, ve
->hostname_address
))
137 tor_free(ve
->hostname_address
);
138 if (!ve
->ipv4_address
&& !ve
->ipv6_address
&& !ve
->hostname_address
) {
140 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
146 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
147 * client address maps, and then free it. */
149 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
151 addressmap_virtaddress_remove(address
, ent
);
152 addressmap_ent_free(ent
);
155 /** Unregister all TrackHostExits mappings from any address to
156 * *.exitname.exit. */
158 clear_trackexithost_mappings(const char *exitname
)
161 if (!addressmap
|| !exitname
)
163 tor_asprintf(&suffix
, ".%s.exit", exitname
);
164 tor_strlower(suffix
);
166 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
167 if (ent
->source
== ADDRMAPSRC_TRACKEXIT
&&
168 !strcmpend(ent
->new_address
, suffix
)) {
169 addressmap_ent_remove(address
, ent
);
170 MAP_DEL_CURRENT(address
);
172 } STRMAP_FOREACH_END
;
177 /** Remove all TRACKEXIT mappings from the addressmap for which the target
178 * host is unknown or no longer allowed, or for which the source address
179 * is no longer in trackexithosts. */
181 addressmap_clear_excluded_trackexithosts(const or_options_t
*options
)
183 const routerset_t
*allow_nodes
= options
->ExitNodes
;
184 const routerset_t
*exclude_nodes
= options
->ExcludeExitNodesUnion_
;
188 if (routerset_is_empty(allow_nodes
))
190 if (allow_nodes
== NULL
&& routerset_is_empty(exclude_nodes
))
193 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
195 const char *target
= ent
->new_address
, *dot
;
200 /* DNS resolving in progress */
202 } else if (strcmpend(target
, ".exit")) {
203 /* Not a .exit mapping */
205 } else if (ent
->source
!= ADDRMAPSRC_TRACKEXIT
) {
206 /* Not a trackexit mapping. */
209 len
= strlen(target
);
211 continue; /* malformed. */
212 dot
= target
+ len
- 6; /* dot now points to just before .exit */
213 while (dot
> target
&& *dot
!= '.')
215 if (*dot
== '.') dot
++;
216 nodename
= tor_strndup(dot
, len
-5-(dot
-target
));;
217 node
= node_get_by_nickname(nodename
, 0);
220 (allow_nodes
&& !routerset_contains_node(allow_nodes
, node
)) ||
221 routerset_contains_node(exclude_nodes
, node
) ||
222 !hostname_in_track_host_exits(options
, address
)) {
223 /* We don't know this one, or we want to be rid of it. */
224 addressmap_ent_remove(address
, ent
);
225 MAP_DEL_CURRENT(address
);
227 } STRMAP_FOREACH_END
;
230 /** Return true iff <b>address</b> is one that we are configured to
231 * automap on resolve according to <b>options</b>. */
233 addressmap_address_should_automap(const char *address
,
234 const or_options_t
*options
)
236 const smartlist_t
*suffix_list
= options
->AutomapHostsSuffixes
;
241 SMARTLIST_FOREACH_BEGIN(suffix_list
, const char *, suffix
) {
242 if (!strcmp(suffix
, "."))
244 if (!strcasecmpend(address
, suffix
))
246 } SMARTLIST_FOREACH_END(suffix
);
250 /** Remove all AUTOMAP mappings from the addressmap for which the
251 * source address no longer matches AutomapHostsSuffixes, which is
252 * no longer allowed by AutomapHostsOnResolve, or for which the
253 * target address is no longer in the virtual network. */
255 addressmap_clear_invalid_automaps(const or_options_t
*options
)
257 int clear_all
= !options
->AutomapHostsOnResolve
;
258 const smartlist_t
*suffixes
= options
->AutomapHostsSuffixes
;
264 clear_all
= 1; /* This should be impossible, but let's be sure. */
266 STRMAP_FOREACH_MODIFY(addressmap
, src_address
, addressmap_entry_t
*, ent
) {
267 int remove_this
= clear_all
;
268 if (ent
->source
!= ADDRMAPSRC_AUTOMAP
)
269 continue; /* not an automap mapping. */
272 remove_this
= ! addressmap_address_should_automap(src_address
, options
);
275 if (!remove_this
&& ! address_is_in_virtual_range(ent
->new_address
))
279 addressmap_ent_remove(src_address
, ent
);
280 MAP_DEL_CURRENT(src_address
);
282 } STRMAP_FOREACH_END
;
285 /** Remove all entries from the addressmap that were set via the
286 * configuration file or the command line. */
288 addressmap_clear_configured(void)
290 addressmap_get_mappings(NULL
, 0, 0, 0);
293 /** Remove all entries from the addressmap that are set to expire, ever. */
295 addressmap_clear_transient(void)
297 addressmap_get_mappings(NULL
, 2, TIME_MAX
, 0);
300 /** Clean out entries from the addressmap cache that were
301 * added long enough ago that they are no longer valid.
304 addressmap_clean(time_t now
)
306 addressmap_get_mappings(NULL
, 2, now
, 0);
309 /** Free all the elements in the addressmap, and free the addressmap
312 addressmap_free_all(void)
314 strmap_free(addressmap
, addressmap_ent_free
);
317 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
318 virtaddress_reversemap
= NULL
;
321 /** Try to find a match for AddressMap expressions that use
322 * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
323 * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
324 * Return the matching entry in AddressMap or NULL if no match is found.
325 * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
326 * to 'a' before we return the matching AddressMap entry.
328 * This function does not handle the case where a pattern of the form "*.c.d"
329 * matches the address c.d -- that's done by the main addressmap_rewrite
332 static addressmap_entry_t
*
333 addressmap_match_superdomains(char *address
)
335 addressmap_entry_t
*val
;
339 while ((cp
= strchr(cp
, '.'))) {
340 /* cp now points to a suffix of address that begins with a . */
341 val
= strmap_get_lc(addressmap
, cp
+1);
342 if (val
&& val
->src_wildcard
) {
343 if (val
->dst_wildcard
)
352 /** Look at address, and rewrite it until it doesn't want any
353 * more rewrites; but don't get into an infinite loop.
354 * Don't write more than maxlen chars into address. Return true if the
355 * address changed; false otherwise. Set *<b>expires_out</b> to the
356 * expiry time of the result, or to <b>time_max</b> if the result does
359 * If <b>exit_source_out</b> is non-null, we set it as follows. If we the
360 * address starts out as a non-exit address, and we remap it to an .exit
361 * address at any point, then set *<b>exit_source_out</b> to the
362 * address_entry_source_t of the first such rule. Set *<b>exit_source_out</b>
363 * to ADDRMAPSRC_NONE if there is no such rewrite, or if the original address
367 addressmap_rewrite(char *address
, size_t maxlen
,
370 addressmap_entry_source_t
*exit_source_out
)
372 addressmap_entry_t
*ent
;
374 time_t expires
= TIME_MAX
;
375 addressmap_entry_source_t exit_source
= ADDRMAPSRC_NONE
;
376 char *addr_orig
= tor_strdup(address
);
377 char *log_addr_orig
= NULL
;
379 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
381 log_addr_orig
= tor_strdup(escaped_safe_str_client(address
));
383 ent
= strmap_get(addressmap
, address
);
385 if (!ent
|| !ent
->new_address
) {
386 ent
= addressmap_match_superdomains(address
);
388 if (ent
->src_wildcard
&& !ent
->dst_wildcard
&&
389 !strcasecmp(address
, ent
->new_address
)) {
390 /* This is a rule like *.example.com example.com, and we just got
398 if (!ent
|| !ent
->new_address
) {
402 switch (ent
->source
) {
407 f
= tor_addr_parse(&tmp
, ent
->new_address
);
408 if (f
== AF_INET
&& !(flags
& AMR_FLAG_USE_IPV4_DNS
))
410 else if (f
== AF_INET6
&& !(flags
& AMR_FLAG_USE_IPV6_DNS
))
414 case ADDRMAPSRC_CONTROLLER
:
415 case ADDRMAPSRC_TORRC
:
416 if (!(flags
& AMR_FLAG_USE_MAPADDRESS
))
419 case ADDRMAPSRC_AUTOMAP
:
420 if (!(flags
& AMR_FLAG_USE_AUTOMAP
))
423 case ADDRMAPSRC_TRACKEXIT
:
424 if (!(flags
& AMR_FLAG_USE_TRACKEXIT
))
427 case ADDRMAPSRC_NONE
:
429 log_warn(LD_BUG
, "Unknown addrmap source value %d. Ignoring it.",
434 if (ent
->dst_wildcard
&& !exact_match
) {
435 strlcat(address
, ".", maxlen
);
436 strlcat(address
, ent
->new_address
, maxlen
);
438 strlcpy(address
, ent
->new_address
, maxlen
);
441 if (!strcmpend(address
, ".exit") &&
442 strcmpend(addr_orig
, ".exit") &&
443 exit_source
== ADDRMAPSRC_NONE
) {
444 exit_source
= ent
->source
;
447 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
448 log_addr_orig
, escaped_safe_str_client(address
));
449 if (ent
->expires
> 1 && ent
->expires
< expires
)
450 expires
= ent
->expires
;
452 tor_free(log_addr_orig
);
455 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
456 escaped_safe_str_client(address
));
457 /* it's fine to rewrite a rewrite, but don't loop forever */
461 tor_free(log_addr_orig
);
463 *exit_source_out
= exit_source
;
465 *expires_out
= expires
;
466 return (rewrites
> 0);
469 /** If we have a cached reverse DNS entry for the address stored in the
470 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
471 * rewrite to the cached value and return 1. Otherwise return 0. Set
472 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
473 * if the result does not expire. */
475 addressmap_rewrite_reverse(char *address
, size_t maxlen
, unsigned flags
,
479 addressmap_entry_t
*ent
;
484 f
= tor_addr_parse(&tmp
, address
);
485 if (f
== AF_INET
&& !(flags
& AMR_FLAG_USE_IPV4_DNS
))
487 else if (f
== AF_INET6
&& !(flags
& AMR_FLAG_USE_IPV6_DNS
))
489 /* FFFF we should reverse-map virtual addresses even if we haven't
490 * enabled DNS cacheing. */
493 tor_asprintf(&s
, "REVERSE[%s]", address
);
494 ent
= strmap_get(addressmap
, s
);
496 cp
= tor_strdup(escaped_safe_str_client(ent
->new_address
));
497 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
498 escaped_safe_str_client(s
), cp
);
500 strlcpy(address
, ent
->new_address
, maxlen
);
505 *expires_out
= (ent
&& ent
->expires
> 1) ? ent
->expires
: TIME_MAX
;
511 /** Return 1 if <b>address</b> is already registered, else return 0. If address
512 * is already registered, and <b>update_expires</b> is non-zero, then update
513 * the expiry time on the mapping with update_expires if it is a
514 * mapping created by TrackHostExits. */
516 addressmap_have_mapping(const char *address
, int update_expiry
)
518 addressmap_entry_t
*ent
;
519 if (!(ent
=strmap_get_lc(addressmap
, address
)))
521 if (update_expiry
&& ent
->source
==ADDRMAPSRC_TRACKEXIT
)
522 ent
->expires
=time(NULL
) + update_expiry
;
526 /** Register a request to map <b>address</b> to <b>new_address</b>,
527 * which will expire on <b>expires</b> (or 0 if never expires from
528 * config file, 1 if never expires from controller, 2 if never expires
529 * (virtual address mapping) from the controller.)
531 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
532 * free as appropriate. We will leave address alone.
534 * If <b>wildcard_addr</b> is true, then the mapping will match any address
535 * equal to <b>address</b>, or any address ending with a period followed by
536 * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
537 * both true, the mapping will rewrite addresses that end with
538 * ".<b>address</b>" into ones that end with ".<b>new_address</b>".
540 * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
541 * <b>address</b> and <b>wildcard_addr</b> is equal to
542 * <b>wildcard_new_addr</b>, remove any mappings that exist from
546 * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
549 addressmap_register(const char *address
, char *new_address
, time_t expires
,
550 addressmap_entry_source_t source
,
551 const int wildcard_addr
,
552 const int wildcard_new_addr
)
554 addressmap_entry_t
*ent
;
556 if (wildcard_new_addr
)
557 tor_assert(wildcard_addr
);
559 ent
= strmap_get(addressmap
, address
);
560 if (!new_address
|| (!strcasecmp(address
,new_address
) &&
561 wildcard_addr
== wildcard_new_addr
)) {
562 /* Remove the mapping, if any. */
563 tor_free(new_address
);
565 addressmap_ent_remove(address
,ent
);
566 strmap_remove(addressmap
, address
);
570 if (!ent
) { /* make a new one and register it */
571 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
572 strmap_set(addressmap
, address
, ent
);
573 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
575 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
576 "since it's already mapped to '%s'",
577 safe_str_client(address
),
578 safe_str_client(new_address
),
579 safe_str_client(ent
->new_address
));
580 tor_free(new_address
);
583 if (address_is_in_virtual_range(ent
->new_address
) &&
585 /* XXX This isn't the perfect test; we want to avoid removing
586 * mappings set from the control interface _as virtual mapping */
587 addressmap_virtaddress_remove(address
, ent
);
589 tor_free(ent
->new_address
);
590 } /* else { we have an in-progress resolve with no mapping. } */
592 ent
->new_address
= new_address
;
593 ent
->expires
= expires
==2 ? 1 : expires
;
594 ent
->num_resolve_failures
= 0;
595 ent
->source
= source
;
596 ent
->src_wildcard
= wildcard_addr
? 1 : 0;
597 ent
->dst_wildcard
= wildcard_new_addr
? 1 : 0;
599 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
600 safe_str_client(address
),
601 safe_str_client(ent
->new_address
));
602 control_event_address_mapped(address
, ent
->new_address
, expires
, NULL
, 1);
605 /** An attempt to resolve <b>address</b> failed at some OR.
606 * Increment the number of resolve failures we have on record
607 * for it, and then return that number.
610 client_dns_incr_failures(const char *address
)
612 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
614 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
615 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
616 strmap_set(addressmap
,address
,ent
);
618 if (ent
->num_resolve_failures
< SHORT_MAX
)
619 ++ent
->num_resolve_failures
; /* don't overflow */
620 log_info(LD_APP
, "Address %s now has %d resolve failures.",
621 safe_str_client(address
),
622 ent
->num_resolve_failures
);
623 return ent
->num_resolve_failures
;
626 /** If <b>address</b> is in the client DNS addressmap, reset
627 * the number of resolve failures we have on record for it.
628 * This is used when we fail a stream because it won't resolve:
629 * otherwise future attempts on that address will only try once.
632 client_dns_clear_failures(const char *address
)
634 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
636 ent
->num_resolve_failures
= 0;
639 /** Record the fact that <b>address</b> resolved to <b>name</b>.
640 * We can now use this in subsequent streams via addressmap_rewrite()
641 * so we can more correctly choose an exit that will allow <b>address</b>.
643 * If <b>exitname</b> is defined, then append the addresses with
644 * ".exitname.exit" before registering the mapping.
646 * If <b>ttl</b> is nonnegative, the mapping will be valid for
647 * <b>ttl</b>seconds; otherwise, we use the default.
650 client_dns_set_addressmap_impl(entry_connection_t
*for_conn
,
651 const char *address
, const char *name
,
652 const char *exitname
,
655 char *extendedaddress
=NULL
, *extendedval
=NULL
;
662 ttl
= DEFAULT_DNS_TTL
;
664 ttl
= dns_clip_ttl(ttl
);
667 /* XXXX fails to ever get attempts to get an exit address of
668 * google.com.digest[=~]nickname.exit; we need a syntax for this that
669 * won't make strict RFC952-compliant applications (like us) barf. */
670 tor_asprintf(&extendedaddress
,
671 "%s.%s.exit", address
, exitname
);
672 tor_asprintf(&extendedval
,
673 "%s.%s.exit", name
, exitname
);
675 tor_asprintf(&extendedaddress
,
677 tor_asprintf(&extendedval
,
680 addressmap_register(extendedaddress
, extendedval
,
681 time(NULL
) + ttl
, ADDRMAPSRC_DNS
, 0, 0);
682 tor_free(extendedaddress
);
685 /** Record the fact that <b>address</b> resolved to <b>val</b>.
686 * We can now use this in subsequent streams via addressmap_rewrite()
687 * so we can more correctly choose an exit that will allow <b>address</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.
696 client_dns_set_addressmap(entry_connection_t
*for_conn
,
698 const tor_addr_t
*val
,
699 const char *exitname
,
703 char valbuf
[TOR_ADDR_BUF_LEN
];
708 if (tor_addr_parse(&addr_tmp
, address
) >= 0)
709 return; /* If address was an IP address already, don't add a mapping. */
711 if (tor_addr_family(val
) == AF_INET
) {
712 if (! for_conn
->entry_cfg
.cache_ipv4_answers
)
714 } else if (tor_addr_family(val
) == AF_INET6
) {
715 if (! for_conn
->entry_cfg
.cache_ipv6_answers
)
719 if (! tor_addr_to_str(valbuf
, val
, sizeof(valbuf
), 1))
722 client_dns_set_addressmap_impl(for_conn
, address
, valbuf
, exitname
, ttl
);
725 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
726 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
728 * If <b>exitname</b> is defined, then append the addresses with
729 * ".exitname.exit" before registering the mapping.
731 * If <b>ttl</b> is nonnegative, the mapping will be valid for
732 * <b>ttl</b>seconds; otherwise, we use the default.
735 client_dns_set_reverse_addressmap(entry_connection_t
*for_conn
,
736 const char *address
, const char *v
,
737 const char *exitname
,
743 sa_family_t f
= tor_addr_parse(&tmp_addr
, address
);
744 if ((f
== AF_INET
&& ! for_conn
->entry_cfg
.cache_ipv4_answers
) ||
745 (f
== AF_INET6
&& ! for_conn
->entry_cfg
.cache_ipv6_answers
))
748 tor_asprintf(&s
, "REVERSE[%s]", address
);
749 client_dns_set_addressmap_impl(for_conn
, s
, v
, exitname
, ttl
);
753 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
754 * These addresses should map to localhost, so even if the
755 * application accidentally tried to connect to them directly (not
756 * via Tor), it wouldn't get too far astray.
758 * These options are configured by parse_virtual_addr_network().
761 static virtual_addr_conf_t virtaddr_conf_ipv4
;
762 static virtual_addr_conf_t virtaddr_conf_ipv6
;
764 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
765 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
766 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
767 * string and return -1 on failure. If validate_only is false, sets the
768 * actual virtual address range to the parsed value. */
770 parse_virtual_addr_network(const char *val
, sa_family_t family
,
774 const int ipv6
= (family
== AF_INET6
);
777 const int max_bits
= ipv6
? 40 : 16;
778 virtual_addr_conf_t
*conf
= ipv6
? &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
780 if (!val
|| val
[0] == '\0') {
782 tor_asprintf(msg
, "Value not present (%s) after VirtualAddressNetwork%s",
783 val
?"Empty":"NULL", ipv6
?"IPv6":"");
786 if (tor_addr_parse_mask_ports(val
, 0, &addr
, &bits
, NULL
, NULL
) < 0) {
788 tor_asprintf(msg
, "Error parsing VirtualAddressNetwork%s %s",
789 ipv6
?"IPv6":"", val
);
792 if (tor_addr_family(&addr
) != family
) {
794 tor_asprintf(msg
, "Incorrect address type for VirtualAddressNetwork%s",
799 if (port_min
!= 1 || port_max
!= 65535) {
801 tor_asprintf(msg
, "Can't specify ports on VirtualAddressNetwork%s",
807 if (bits
> max_bits
) {
809 tor_asprintf(msg
, "VirtualAddressNetwork%s expects a /%d "
810 "network or larger",ipv6
?"IPv6":"", max_bits
);
817 tor_addr_copy(&conf
->addr
, &addr
);
824 * Return true iff <b>addr</b> is likely to have been returned by
825 * client_dns_get_unused_address.
828 address_is_in_virtual_range(const char *address
)
832 if (!strcasecmpend(address
, ".virtual")) {
834 } else if (tor_addr_parse(&addr
, address
) >= 0) {
835 const virtual_addr_conf_t
*conf
= (tor_addr_family(&addr
) == AF_INET6
) ?
836 &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
837 if (tor_addr_compare_masked(&addr
, &conf
->addr
, conf
->bits
, CMP_EXACT
)==0)
843 /** Return a random address conforming to the virtual address configuration
847 get_random_virtual_addr(const virtual_addr_conf_t
*conf
, tor_addr_t
*addr_out
)
850 const uint8_t *addr_bytes
;
852 const int ipv6
= tor_addr_family(&conf
->addr
) == AF_INET6
;
853 const int total_bytes
= ipv6
? 16 : 4;
855 tor_assert(conf
->bits
<= total_bytes
* 8);
857 /* Set addr_bytes to the bytes of the virtual network, in host order */
859 addr_bytes
= tor_addr_to_in6_addr8(&conf
->addr
);
861 set_uint32(tmp
, tor_addr_to_ipv4n(&conf
->addr
));
865 /* Get an appropriate number of random bytes. */
866 crypto_rand((char*)bytes
, total_bytes
);
868 /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
870 memcpy(bytes
, addr_bytes
, conf
->bits
/ 8);
871 if (conf
->bits
& 7) {
872 uint8_t mask
= 0xff >> (conf
->bits
& 7);
873 bytes
[conf
->bits
/8] &= mask
;
874 bytes
[conf
->bits
/8] |= addr_bytes
[conf
->bits
/8] & ~mask
;
878 tor_addr_from_ipv6_bytes(addr_out
, (char*) bytes
);
880 tor_addr_from_ipv4n(addr_out
, get_uint32(bytes
));
882 tor_assert(tor_addr_compare_masked(addr_out
, &conf
->addr
,
883 conf
->bits
, CMP_EXACT
)==0);
886 /** Return a newly allocated string holding an address of <b>type</b>
887 * (one of RESOLVED_TYPE_{IPV4|IPV6|HOSTNAME}) that has not yet been
888 * mapped, and that is very unlikely to be the address of any real host.
890 * May return NULL if we have run out of virtual addresses.
893 addressmap_get_virtual_address(int type
)
896 tor_assert(addressmap
);
898 if (type
== RESOLVED_TYPE_HOSTNAME
) {
901 crypto_rand(rand_bytes
, sizeof(rand_bytes
));
902 base32_encode(buf
,sizeof(buf
),rand_bytes
,sizeof(rand_bytes
));
903 strlcat(buf
, ".virtual", sizeof(buf
));
904 } while (strmap_get(addressmap
, buf
));
905 return tor_strdup(buf
);
906 } else if (type
== RESOLVED_TYPE_IPV4
|| type
== RESOLVED_TYPE_IPV6
) {
907 const int ipv6
= (type
== RESOLVED_TYPE_IPV6
);
908 const virtual_addr_conf_t
*conf
= ipv6
?
909 &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
911 /* Don't try more than 1000 times. This gives us P < 1e-9 for
912 * failing to get a good address so long as the address space is
913 * less than ~97.95% full. That's always going to be true under
914 * sensible circumstances for an IPv6 /10, and it's going to be
915 * true for an IPv4 /10 as long as we've handed out less than
916 * 4.08 million addresses. */
917 uint32_t attempts
= 1000;
922 get_random_virtual_addr(conf
, &addr
);
925 /* Don't hand out any .0 or .255 address. */
926 const uint32_t a
= tor_addr_to_ipv4h(&addr
);
927 if ((a
& 0xff) == 0 || (a
& 0xff) == 0xff)
931 tor_addr_to_str(buf
, &addr
, sizeof(buf
), 1);
932 if (!strmap_get(addressmap
, buf
)) {
933 /* XXXX This code is to make sure I didn't add an undecorated version
934 * by mistake. I hope it's needless. */
935 char tmp
[TOR_ADDR_BUF_LEN
];
936 tor_addr_to_str(tmp
, &addr
, sizeof(tmp
), 0);
937 if (strmap_get(addressmap
, tmp
)) {
938 log_warn(LD_BUG
, "%s wasn't in the addressmap, but %s was.",
943 return tor_strdup(buf
);
946 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
949 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
954 /** A controller has requested that we map some address of type
955 * <b>type</b> to the address <b>new_address</b>. Choose an address
956 * that is unlikely to be used, and map it, and return it in a newly
957 * allocated string. If another address of the same type is already
958 * mapped to <b>new_address</b>, try to return a copy of that address.
960 * The string in <b>new_address</b> may be freed or inserted into a map
961 * as appropriate. May return NULL if are out of virtual addresses.
964 addressmap_register_virtual_address(int type
, char *new_address
)
967 virtaddress_entry_t
*vent
;
968 int vent_needs_to_be_added
= 0;
970 tor_assert(new_address
);
971 tor_assert(addressmap
);
972 tor_assert(virtaddress_reversemap
);
974 vent
= strmap_get(virtaddress_reversemap
, new_address
);
976 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
977 vent_needs_to_be_added
= 1;
980 if (type
== RESOLVED_TYPE_IPV4
)
981 addrp
= &vent
->ipv4_address
;
982 else if (type
== RESOLVED_TYPE_IPV6
)
983 addrp
= &vent
->ipv6_address
;
985 addrp
= &vent
->hostname_address
;
988 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
989 if (ent
&& ent
->new_address
&&
990 !strcasecmp(new_address
, ent
->new_address
)) {
991 tor_free(new_address
);
992 tor_assert(!vent_needs_to_be_added
);
996 "Internal confusion: I thought that '%s' was mapped to by "
997 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
998 safe_str_client(new_address
),
999 safe_str_client(*addrp
),
1000 safe_str_client(*addrp
),
1001 ent
?safe_str_client(ent
->new_address
):"(nothing)");
1006 *addrp
= addressmap_get_virtual_address(type
);
1009 tor_free(new_address
);
1012 log_info(LD_APP
, "Registering map from %s to %s", *addrp
, new_address
);
1013 if (vent_needs_to_be_added
)
1014 strmap_set(virtaddress_reversemap
, new_address
, vent
);
1015 addressmap_register(*addrp
, new_address
, 2, ADDRMAPSRC_AUTOMAP
, 0, 0);
1017 /* FFFF register corresponding reverse mapping. */
1021 /* Try to catch possible bugs */
1022 addressmap_entry_t
*ent
;
1023 ent
= strmap_get(addressmap
, *addrp
);
1025 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
1026 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1028 tor_assert(!strcasecmp(*addrp
,
1029 (type
== RESOLVED_TYPE_IPV4
) ?
1030 vent
->ipv4_address
: vent
->hostname_address
));
1031 log_info(LD_APP
, "Map from %s to %s okay.",
1032 safe_str_client(*addrp
),
1033 safe_str_client(new_address
));
1040 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1041 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1042 * should be true if we're using this address as a client; false if we're
1043 * using it as a server.
1046 address_is_invalid_destination(const char *address
, int client
)
1049 if (get_options()->AllowNonRFC953Hostnames
)
1052 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1056 /* It might be an IPv6 address! */
1059 if (tor_addr_parse(&a
, address
) >= 0)
1064 if (TOR_ISALNUM(*address
) ||
1067 *address
== '_') /* Underscore is not allowed, but Windows does it
1068 * sometimes, just to thumb its nose at the IETF. */
1076 /** Iterate over all address mappings which have expiry times between
1077 * min_expires and max_expires, inclusive. If sl is provided, add an
1078 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1079 * the expiry time if want_expiry is false. If sl is NULL, remove the
1083 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1084 time_t max_expires
, int want_expiry
)
1086 strmap_iter_t
*iter
;
1089 addressmap_entry_t
*val
;
1094 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1095 strmap_iter_get(iter
, &key
, &val_
);
1097 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1099 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1100 addressmap_ent_remove(key
, val
);
1102 } else if (val
->new_address
) {
1103 const char *src_wc
= val
->src_wildcard
? "*." : "";
1104 const char *dst_wc
= val
->dst_wildcard
? "*." : "";
1106 if (val
->expires
< 3 || val
->expires
== TIME_MAX
)
1107 smartlist_add_asprintf(sl
, "%s%s %s%s NEVER",
1108 src_wc
, key
, dst_wc
, val
->new_address
);
1110 char isotime
[ISO_TIME_LEN
+1];
1111 format_iso_time(isotime
, val
->expires
);
1112 smartlist_add_asprintf(sl
, "%s%s %s%s \"%s\"",
1113 src_wc
, key
, dst_wc
, val
->new_address
,
1117 smartlist_add_asprintf(sl
, "%s%s %s%s",
1118 src_wc
, key
, dst_wc
, val
->new_address
);
1122 iter
= strmap_iter_next(addressmap
,iter
);