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