minor updates on upcoming changelog
[tor.git] / src / or / addressmap.c
blob7e92633601aeb434668469e96a89d9caedd8a7b8
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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 "or.h"
19 #include "addressmap.h"
20 #include "circuituse.h"
21 #include "config.h"
22 #include "connection_edge.h"
23 #include "control.h"
24 #include "dns.h"
25 #include "routerset.h"
26 #include "nodelist.h"
28 /** A client-side struct to remember requests to rewrite addresses
29 * to new addresses. These structs are stored in the hash table
30 * "addressmap" below.
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
47 * expire.)
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.
54 typedef struct {
55 char *new_address;
56 time_t expires;
57 addressmap_entry_source_bitfield_t source:3;
58 unsigned src_wildcard:1;
59 unsigned dst_wildcard:1;
60 short num_resolve_failures;
61 } addressmap_entry_t;
63 /** Entry for mapping addresses to which virtual address we mapped them to. */
64 typedef struct {
65 char *ipv4_address;
66 char *ipv6_address;
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;
73 /**
74 * Table mapping addresses to which virtual address, if any, we
75 * assigned them to.
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.
82 **/
83 static strmap_t *virtaddress_reversemap=NULL;
85 /** Initialize addressmap. */
86 void
87 addressmap_init(void)
89 addressmap = strmap_new();
90 virtaddress_reversemap = strmap_new();
93 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
94 static void
95 addressmap_ent_free(void *_ent)
97 addressmap_entry_t *ent;
98 if (!_ent)
99 return;
101 ent = _ent;
102 tor_free(ent->new_address);
103 tor_free(ent);
106 /** Free storage held by a virtaddress_entry_t* entry in <b>_ent</b>. */
107 static void
108 addressmap_virtaddress_ent_free(void *_ent)
110 virtaddress_entry_t *ent;
111 if (!_ent)
112 return;
114 ent = _ent;
115 tor_free(ent->ipv4_address);
116 tor_free(ent->ipv6_address);
117 tor_free(ent->hostname_address);
118 tor_free(ent);
121 /** Remove <b>address</b> (which must map to <b>ent</b>) from the
122 * virtual address map. */
123 static void
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);*/
131 if (ve) {
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) {
139 tor_free(ve);
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. */
148 static void
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. */
157 void
158 clear_trackexithost_mappings(const char *exitname)
160 char *suffix = NULL;
161 if (!addressmap || !exitname)
162 return;
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;
174 tor_free(suffix);
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. */
180 void
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_;
186 if (!addressmap)
187 return;
188 if (routerset_is_empty(allow_nodes))
189 allow_nodes = NULL;
190 if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
191 return;
193 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
194 size_t len;
195 const char *target = ent->new_address, *dot;
196 char *nodename;
197 const node_t *node;
199 if (!target) {
200 /* DNS resolving in progress */
201 continue;
202 } else if (strcmpend(target, ".exit")) {
203 /* Not a .exit mapping */
204 continue;
205 } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
206 /* Not a trackexit mapping. */
207 continue;
209 len = strlen(target);
210 if (len < 6)
211 continue; /* malformed. */
212 dot = target + len - 6; /* dot now points to just before .exit */
213 while (dot > target && *dot != '.')
214 dot--;
215 if (*dot == '.') dot++;
216 nodename = tor_strndup(dot, len-5-(dot-target));
217 node = node_get_by_nickname(nodename, NNF_NO_WARN_UNNAMED);
218 tor_free(nodename);
219 if (!node ||
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;
238 if (!suffix_list)
239 return 0;
241 SMARTLIST_FOREACH_BEGIN(suffix_list, const char *, suffix) {
242 if (!strcmp(suffix, "."))
243 return 1;
244 if (!strcasecmpend(address, suffix))
245 return 1;
246 } SMARTLIST_FOREACH_END(suffix);
247 return 0;
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. */
254 void
255 addressmap_clear_invalid_automaps(const or_options_t *options)
257 int clear_all = !options->AutomapHostsOnResolve;
258 const smartlist_t *suffixes = options->AutomapHostsSuffixes;
260 if (!addressmap)
261 return;
263 if (!suffixes)
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. */
271 if (!remove_this) {
272 remove_this = ! addressmap_address_should_automap(src_address, options);
275 if (!remove_this && ! address_is_in_virtual_range(ent->new_address))
276 remove_this = 1;
278 if (remove_this) {
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. */
287 void
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. */
294 void
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.
303 void
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
310 * itself. */
311 void
312 addressmap_free_all(void)
314 strmap_free(addressmap, addressmap_ent_free);
315 addressmap = NULL;
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
330 * function.
332 static addressmap_entry_t *
333 addressmap_match_superdomains(char *address)
335 addressmap_entry_t *val;
336 char *cp;
338 cp = address;
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)
344 *cp = '\0';
345 return val;
347 ++cp;
349 return NULL;
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
357 * not expire.
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
364 * was a .exit.
367 addressmap_rewrite(char *address, size_t maxlen,
368 unsigned flags,
369 time_t *expires_out,
370 addressmap_entry_source_t *exit_source_out)
372 addressmap_entry_t *ent;
373 int rewrites;
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 /* We use a loop here to limit the total number of rewrites we do,
380 * so that we can't hit an infinite loop. */
381 for (rewrites = 0; rewrites < 16; rewrites++) {
382 int exact_match = 0;
383 log_addr_orig = tor_strdup(escaped_safe_str_client(address));
385 /* First check to see if there's an exact match for this address */
386 ent = strmap_get(addressmap, address);
388 if (!ent || !ent->new_address) {
389 /* And if we don't have an exact match, try to check whether
390 * we have a pattern-based match.
392 ent = addressmap_match_superdomains(address);
393 } else {
394 if (ent->src_wildcard && !ent->dst_wildcard &&
395 !strcasecmp(address, ent->new_address)) {
396 /* This is a rule like "rewrite *.example.com to example.com", and we
397 * just got "example.com". Instead of calling it an infinite loop,
398 * call it complete. */
399 goto done;
401 exact_match = 1;
404 if (!ent || !ent->new_address) {
405 /* We still have no match at all. We're done! */
406 goto done;
409 /* Check wither the flags we were passed tell us not to use this
410 * mapping. */
411 switch (ent->source) {
412 case ADDRMAPSRC_DNS:
414 sa_family_t f;
415 tor_addr_t tmp;
416 f = tor_addr_parse(&tmp, ent->new_address);
417 if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
418 goto done;
419 else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
420 goto done;
422 break;
423 case ADDRMAPSRC_CONTROLLER:
424 case ADDRMAPSRC_TORRC:
425 if (!(flags & AMR_FLAG_USE_MAPADDRESS))
426 goto done;
427 break;
428 case ADDRMAPSRC_AUTOMAP:
429 if (!(flags & AMR_FLAG_USE_AUTOMAP))
430 goto done;
431 break;
432 case ADDRMAPSRC_TRACKEXIT:
433 if (!(flags & AMR_FLAG_USE_TRACKEXIT))
434 goto done;
435 break;
436 case ADDRMAPSRC_NONE:
437 default:
438 log_warn(LD_BUG, "Unknown addrmap source value %d. Ignoring it.",
439 (int) ent->source);
440 goto done;
443 /* Now fill in the address with the new address. That might be via
444 * appending some new stuff to the end, or via just replacing it. */
445 if (ent->dst_wildcard && !exact_match) {
446 strlcat(address, ".", maxlen);
447 strlcat(address, ent->new_address, maxlen);
448 } else {
449 strlcpy(address, ent->new_address, maxlen);
452 /* Is this now a .exit address? If so, remember where we got it.*/
453 if (!strcmpend(address, ".exit") &&
454 strcmpend(addr_orig, ".exit") &&
455 exit_source == ADDRMAPSRC_NONE) {
456 exit_source = ent->source;
459 log_info(LD_APP, "Addressmap: rewriting %s to %s",
460 log_addr_orig, escaped_safe_str_client(address));
461 if (ent->expires > 1 && ent->expires < expires)
462 expires = ent->expires;
464 tor_free(log_addr_orig);
466 log_warn(LD_CONFIG,
467 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
468 escaped_safe_str_client(address));
469 /* it's fine to rewrite a rewrite, but don't loop forever */
471 done:
472 tor_free(addr_orig);
473 tor_free(log_addr_orig);
474 if (exit_source_out)
475 *exit_source_out = exit_source;
476 if (expires_out)
477 *expires_out = expires;
478 return (rewrites > 0);
481 /** If we have a cached reverse DNS entry for the address stored in the
482 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
483 * rewrite to the cached value and return 1. Otherwise return 0. Set
484 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
485 * if the result does not expire. */
487 addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags,
488 time_t *expires_out)
490 char *s, *cp;
491 addressmap_entry_t *ent;
492 int r = 0;
494 sa_family_t f;
495 tor_addr_t tmp;
496 f = tor_addr_parse(&tmp, address);
497 if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
498 return 0;
499 else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
500 return 0;
501 /* FFFF we should reverse-map virtual addresses even if we haven't
502 * enabled DNS cacheing. */
505 tor_asprintf(&s, "REVERSE[%s]", address);
506 ent = strmap_get(addressmap, s);
507 if (ent) {
508 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
509 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
510 escaped_safe_str_client(s), cp);
511 tor_free(cp);
512 strlcpy(address, ent->new_address, maxlen);
513 r = 1;
516 if (expires_out)
517 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
519 tor_free(s);
520 return r;
523 /** Return 1 if <b>address</b> is already registered, else return 0. If address
524 * is already registered, and <b>update_expires</b> is non-zero, then update
525 * the expiry time on the mapping with update_expires if it is a
526 * mapping created by TrackHostExits. */
528 addressmap_have_mapping(const char *address, int update_expiry)
530 addressmap_entry_t *ent;
531 if (!(ent=strmap_get_lc(addressmap, address)))
532 return 0;
533 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
534 ent->expires=time(NULL) + update_expiry;
535 return 1;
538 /** Register a request to map <b>address</b> to <b>new_address</b>,
539 * which will expire on <b>expires</b> (or 0 if never expires from
540 * config file, 1 if never expires from controller, 2 if never expires
541 * (virtual address mapping) from the controller.)
543 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
544 * free as appropriate. We will leave address alone.
546 * If <b>wildcard_addr</b> is true, then the mapping will match any address
547 * equal to <b>address</b>, or any address ending with a period followed by
548 * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
549 * both true, the mapping will rewrite addresses that end with
550 * ".<b>address</b>" into ones that end with ".<b>new_address</b>".
552 * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
553 * <b>address</b> and <b>wildcard_addr</b> is equal to
554 * <b>wildcard_new_addr</b>, remove any mappings that exist from
555 * <b>address</b>.
558 * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
559 * not set. */
560 void
561 addressmap_register(const char *address, char *new_address, time_t expires,
562 addressmap_entry_source_t source,
563 const int wildcard_addr,
564 const int wildcard_new_addr)
566 addressmap_entry_t *ent;
568 if (wildcard_new_addr)
569 tor_assert(wildcard_addr);
571 ent = strmap_get(addressmap, address);
572 if (!new_address || (!strcasecmp(address,new_address) &&
573 wildcard_addr == wildcard_new_addr)) {
574 /* Remove the mapping, if any. */
575 tor_free(new_address);
576 if (ent) {
577 addressmap_ent_remove(address,ent);
578 strmap_remove(addressmap, address);
580 return;
582 if (!ent) { /* make a new one and register it */
583 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
584 strmap_set(addressmap, address, ent);
585 } else if (ent->new_address) { /* we need to clean up the old mapping. */
586 if (expires > 1) {
587 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
588 "since it's already mapped to '%s'",
589 safe_str_client(address),
590 safe_str_client(new_address),
591 safe_str_client(ent->new_address));
592 tor_free(new_address);
593 return;
595 if (address_is_in_virtual_range(ent->new_address) &&
596 expires != 2) {
597 /* XXX This isn't the perfect test; we want to avoid removing
598 * mappings set from the control interface _as virtual mapping */
599 addressmap_virtaddress_remove(address, ent);
601 tor_free(ent->new_address);
602 } /* else { we have an in-progress resolve with no mapping. } */
604 ent->new_address = new_address;
605 ent->expires = expires==2 ? 1 : expires;
606 ent->num_resolve_failures = 0;
607 ent->source = source;
608 ent->src_wildcard = wildcard_addr ? 1 : 0;
609 ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
611 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
612 safe_str_client(address),
613 safe_str_client(ent->new_address));
614 control_event_address_mapped(address, ent->new_address, expires, NULL, 1);
617 /** An attempt to resolve <b>address</b> failed at some OR.
618 * Increment the number of resolve failures we have on record
619 * for it, and then return that number.
622 client_dns_incr_failures(const char *address)
624 addressmap_entry_t *ent = strmap_get(addressmap, address);
625 if (!ent) {
626 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
627 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
628 strmap_set(addressmap,address,ent);
630 if (ent->num_resolve_failures < SHORT_MAX)
631 ++ent->num_resolve_failures; /* don't overflow */
632 log_info(LD_APP, "Address %s now has %d resolve failures.",
633 safe_str_client(address),
634 ent->num_resolve_failures);
635 return ent->num_resolve_failures;
638 /** If <b>address</b> is in the client DNS addressmap, reset
639 * the number of resolve failures we have on record for it.
640 * This is used when we fail a stream because it won't resolve:
641 * otherwise future attempts on that address will only try once.
643 void
644 client_dns_clear_failures(const char *address)
646 addressmap_entry_t *ent = strmap_get(addressmap, address);
647 if (ent)
648 ent->num_resolve_failures = 0;
651 /** Record the fact that <b>address</b> resolved to <b>name</b>.
652 * We can now use this in subsequent streams via addressmap_rewrite()
653 * so we can more correctly choose an exit that will allow <b>address</b>.
655 * If <b>exitname</b> is defined, then append the addresses with
656 * ".exitname.exit" before registering the mapping.
658 * If <b>ttl</b> is nonnegative, the mapping will be valid for
659 * <b>ttl</b>seconds; otherwise, we use the default.
661 static void
662 client_dns_set_addressmap_impl(entry_connection_t *for_conn,
663 const char *address, const char *name,
664 const char *exitname,
665 int ttl)
667 char *extendedaddress=NULL, *extendedval=NULL;
668 (void)for_conn;
670 tor_assert(address);
671 tor_assert(name);
673 if (ttl<0)
674 ttl = DEFAULT_DNS_TTL;
675 else
676 ttl = dns_clip_ttl(ttl);
678 if (exitname) {
679 /* XXXX fails to ever get attempts to get an exit address of
680 * google.com.digest[=~]nickname.exit; we need a syntax for this that
681 * won't make strict RFC952-compliant applications (like us) barf. */
682 tor_asprintf(&extendedaddress,
683 "%s.%s.exit", address, exitname);
684 tor_asprintf(&extendedval,
685 "%s.%s.exit", name, exitname);
686 } else {
687 tor_asprintf(&extendedaddress,
688 "%s", address);
689 tor_asprintf(&extendedval,
690 "%s", name);
692 addressmap_register(extendedaddress, extendedval,
693 time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
694 tor_free(extendedaddress);
697 /** Record the fact that <b>address</b> resolved to <b>val</b>.
698 * We can now use this in subsequent streams via addressmap_rewrite()
699 * so we can more correctly choose an exit that will allow <b>address</b>.
701 * If <b>exitname</b> is defined, then append the addresses with
702 * ".exitname.exit" before registering the mapping.
704 * If <b>ttl</b> is nonnegative, the mapping will be valid for
705 * <b>ttl</b>seconds; otherwise, we use the default.
707 void
708 client_dns_set_addressmap(entry_connection_t *for_conn,
709 const char *address,
710 const tor_addr_t *val,
711 const char *exitname,
712 int ttl)
714 tor_addr_t addr_tmp;
715 char valbuf[TOR_ADDR_BUF_LEN];
717 tor_assert(address);
718 tor_assert(val);
720 if (tor_addr_parse(&addr_tmp, address) >= 0)
721 return; /* If address was an IP address already, don't add a mapping. */
723 if (tor_addr_family(val) == AF_INET) {
724 if (! for_conn->entry_cfg.cache_ipv4_answers)
725 return;
726 } else if (tor_addr_family(val) == AF_INET6) {
727 if (! for_conn->entry_cfg.cache_ipv6_answers)
728 return;
731 if (! tor_addr_to_str(valbuf, val, sizeof(valbuf), 1))
732 return;
734 client_dns_set_addressmap_impl(for_conn, address, valbuf, exitname, ttl);
737 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
738 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
740 * If <b>exitname</b> is defined, then append the addresses with
741 * ".exitname.exit" before registering the mapping.
743 * If <b>ttl</b> is nonnegative, the mapping will be valid for
744 * <b>ttl</b>seconds; otherwise, we use the default.
746 void
747 client_dns_set_reverse_addressmap(entry_connection_t *for_conn,
748 const char *address, const char *v,
749 const char *exitname,
750 int ttl)
752 char *s = NULL;
754 tor_addr_t tmp_addr;
755 sa_family_t f = tor_addr_parse(&tmp_addr, address);
756 if ((f == AF_INET && ! for_conn->entry_cfg.cache_ipv4_answers) ||
757 (f == AF_INET6 && ! for_conn->entry_cfg.cache_ipv6_answers))
758 return;
760 tor_asprintf(&s, "REVERSE[%s]", address);
761 client_dns_set_addressmap_impl(for_conn, s, v, exitname, ttl);
762 tor_free(s);
765 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
766 * These addresses should map to localhost, so even if the
767 * application accidentally tried to connect to them directly (not
768 * via Tor), it wouldn't get too far astray.
770 * These options are configured by parse_virtual_addr_network().
773 static virtual_addr_conf_t virtaddr_conf_ipv4;
774 static virtual_addr_conf_t virtaddr_conf_ipv6;
776 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
777 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
778 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
779 * string and return -1 on failure. If validate_only is false, sets the
780 * actual virtual address range to the parsed value. */
782 parse_virtual_addr_network(const char *val, sa_family_t family,
783 int validate_only,
784 char **msg)
786 const int ipv6 = (family == AF_INET6);
787 tor_addr_t addr;
788 maskbits_t bits;
789 const int max_prefix_bits = ipv6 ? 104 : 16;
790 virtual_addr_conf_t *conf = ipv6 ? &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
792 if (!val || val[0] == '\0') {
793 if (msg)
794 tor_asprintf(msg, "Value not present (%s) after VirtualAddressNetwork%s",
795 val?"Empty":"NULL", ipv6?"IPv6":"");
796 return -1;
798 if (tor_addr_parse_mask_ports(val, 0, &addr, &bits, NULL, NULL) < 0) {
799 if (msg)
800 tor_asprintf(msg, "Error parsing VirtualAddressNetwork%s %s",
801 ipv6?"IPv6":"", val);
802 return -1;
804 if (tor_addr_family(&addr) != family) {
805 if (msg)
806 tor_asprintf(msg, "Incorrect address type for VirtualAddressNetwork%s",
807 ipv6?"IPv6":"");
808 return -1;
810 #if 0
811 if (port_min != 1 || port_max != 65535) {
812 if (msg)
813 tor_asprintf(msg, "Can't specify ports on VirtualAddressNetwork%s",
814 ipv6?"IPv6":"");
815 return -1;
817 #endif /* 0 */
819 if (bits > max_prefix_bits) {
820 if (msg)
821 tor_asprintf(msg, "VirtualAddressNetwork%s expects a /%d "
822 "network or larger",ipv6?"IPv6":"", max_prefix_bits);
823 return -1;
826 if (validate_only)
827 return 0;
829 tor_addr_copy(&conf->addr, &addr);
830 conf->bits = bits;
832 return 0;
836 * Return true iff <b>addr</b> is likely to have been returned by
837 * client_dns_get_unused_address.
840 address_is_in_virtual_range(const char *address)
842 tor_addr_t addr;
843 tor_assert(address);
844 if (!strcasecmpend(address, ".virtual")) {
845 return 1;
846 } else if (tor_addr_parse(&addr, address) >= 0) {
847 const virtual_addr_conf_t *conf = (tor_addr_family(&addr) == AF_INET6) ?
848 &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
849 if (tor_addr_compare_masked(&addr, &conf->addr, conf->bits, CMP_EXACT)==0)
850 return 1;
852 return 0;
855 /** Return a random address conforming to the virtual address configuration
856 * in <b>conf</b>.
858 STATIC void
859 get_random_virtual_addr(const virtual_addr_conf_t *conf, tor_addr_t *addr_out)
861 uint8_t tmp[4];
862 const uint8_t *addr_bytes;
863 uint8_t bytes[16];
864 const int ipv6 = tor_addr_family(&conf->addr) == AF_INET6;
865 const int total_bytes = ipv6 ? 16 : 4;
867 tor_assert(conf->bits <= total_bytes * 8);
869 /* Set addr_bytes to the bytes of the virtual network, in host order */
870 if (ipv6) {
871 addr_bytes = tor_addr_to_in6_addr8(&conf->addr);
872 } else {
873 set_uint32(tmp, tor_addr_to_ipv4n(&conf->addr));
874 addr_bytes = tmp;
877 /* Get an appropriate number of random bytes. */
878 crypto_rand((char*)bytes, total_bytes);
880 /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
881 if (conf->bits >= 8)
882 memcpy(bytes, addr_bytes, conf->bits / 8);
883 if (conf->bits & 7) {
884 uint8_t mask = 0xff >> (conf->bits & 7);
885 bytes[conf->bits/8] &= mask;
886 bytes[conf->bits/8] |= addr_bytes[conf->bits/8] & ~mask;
889 if (ipv6)
890 tor_addr_from_ipv6_bytes(addr_out, (char*) bytes);
891 else
892 tor_addr_from_ipv4n(addr_out, get_uint32(bytes));
894 tor_assert(tor_addr_compare_masked(addr_out, &conf->addr,
895 conf->bits, CMP_EXACT)==0);
898 /** Return a newly allocated string holding an address of <b>type</b>
899 * (one of RESOLVED_TYPE_{IPV4|IPV6|HOSTNAME}) that has not yet been
900 * mapped, and that is very unlikely to be the address of any real host.
902 * May return NULL if we have run out of virtual addresses.
904 static char *
905 addressmap_get_virtual_address(int type)
907 char buf[64];
908 tor_assert(addressmap);
910 if (type == RESOLVED_TYPE_HOSTNAME) {
911 char rand_bytes[10];
912 do {
913 crypto_rand(rand_bytes, sizeof(rand_bytes));
914 base32_encode(buf,sizeof(buf),rand_bytes,sizeof(rand_bytes));
915 strlcat(buf, ".virtual", sizeof(buf));
916 } while (strmap_get(addressmap, buf));
917 return tor_strdup(buf);
918 } else if (type == RESOLVED_TYPE_IPV4 || type == RESOLVED_TYPE_IPV6) {
919 const int ipv6 = (type == RESOLVED_TYPE_IPV6);
920 const virtual_addr_conf_t *conf = ipv6 ?
921 &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
923 /* Don't try more than 1000 times. This gives us P < 1e-9 for
924 * failing to get a good address so long as the address space is
925 * less than ~97.95% full. That's always going to be true under
926 * sensible circumstances for an IPv6 /10, and it's going to be
927 * true for an IPv4 /10 as long as we've handed out less than
928 * 4.08 million addresses. */
929 uint32_t attempts = 1000;
931 tor_addr_t addr;
933 while (attempts--) {
934 get_random_virtual_addr(conf, &addr);
936 if (!ipv6) {
937 /* Don't hand out any .0 or .255 address. */
938 const uint32_t a = tor_addr_to_ipv4h(&addr);
939 if ((a & 0xff) == 0 || (a & 0xff) == 0xff)
940 continue;
943 tor_addr_to_str(buf, &addr, sizeof(buf), 1);
944 if (!strmap_get(addressmap, buf)) {
945 /* XXXX This code is to make sure I didn't add an undecorated version
946 * by mistake. I hope it's needless. */
947 char tmp[TOR_ADDR_BUF_LEN];
948 tor_addr_to_str(tmp, &addr, sizeof(tmp), 0);
949 if (strmap_get(addressmap, tmp)) {
950 log_warn(LD_BUG, "%s wasn't in the addressmap, but %s was.",
951 buf, tmp);
952 continue;
955 return tor_strdup(buf);
958 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
959 return NULL;
960 } else {
961 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
962 return NULL;
966 /** A controller has requested that we map some address of type
967 * <b>type</b> to the address <b>new_address</b>. Choose an address
968 * that is unlikely to be used, and map it, and return it in a newly
969 * allocated string. If another address of the same type is already
970 * mapped to <b>new_address</b>, try to return a copy of that address.
972 * The string in <b>new_address</b> may be freed or inserted into a map
973 * as appropriate. May return NULL if are out of virtual addresses.
975 const char *
976 addressmap_register_virtual_address(int type, char *new_address)
978 char **addrp;
979 virtaddress_entry_t *vent;
980 int vent_needs_to_be_added = 0;
982 tor_assert(new_address);
983 tor_assert(addressmap);
984 tor_assert(virtaddress_reversemap);
986 vent = strmap_get(virtaddress_reversemap, new_address);
987 if (!vent) {
988 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
989 vent_needs_to_be_added = 1;
992 if (type == RESOLVED_TYPE_IPV4)
993 addrp = &vent->ipv4_address;
994 else if (type == RESOLVED_TYPE_IPV6)
995 addrp = &vent->ipv6_address;
996 else
997 addrp = &vent->hostname_address;
999 if (*addrp) {
1000 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1001 if (ent && ent->new_address &&
1002 !strcasecmp(new_address, ent->new_address)) {
1003 tor_free(new_address);
1004 tor_assert(!vent_needs_to_be_added);
1005 return *addrp;
1006 } else {
1007 log_warn(LD_BUG,
1008 "Internal confusion: I thought that '%s' was mapped to by "
1009 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1010 safe_str_client(new_address),
1011 safe_str_client(*addrp),
1012 safe_str_client(*addrp),
1013 ent?safe_str_client(ent->new_address):"(nothing)");
1017 tor_free(*addrp);
1018 *addrp = addressmap_get_virtual_address(type);
1019 if (!*addrp) {
1020 tor_free(vent);
1021 tor_free(new_address);
1022 return NULL;
1024 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1025 if (vent_needs_to_be_added)
1026 strmap_set(virtaddress_reversemap, new_address, vent);
1027 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
1029 /* FFFF register corresponding reverse mapping. */
1031 #if 0
1033 /* Try to catch possible bugs */
1034 addressmap_entry_t *ent;
1035 ent = strmap_get(addressmap, *addrp);
1036 tor_assert(ent);
1037 tor_assert(!strcasecmp(ent->new_address,new_address));
1038 vent = strmap_get(virtaddress_reversemap, new_address);
1039 tor_assert(vent);
1040 tor_assert(!strcasecmp(*addrp,
1041 (type == RESOLVED_TYPE_IPV4) ?
1042 vent->ipv4_address : vent->hostname_address));
1043 log_info(LD_APP, "Map from %s to %s okay.",
1044 safe_str_client(*addrp),
1045 safe_str_client(new_address));
1047 #endif /* 0 */
1049 return *addrp;
1052 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1053 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1054 * should be true if we're using this address as a client; false if we're
1055 * using it as a server.
1058 address_is_invalid_destination(const char *address, int client)
1060 if (client) {
1061 if (get_options()->AllowNonRFC953Hostnames)
1062 return 0;
1063 } else {
1064 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1065 return 0;
1068 /* It might be an IPv6 address! */
1070 tor_addr_t a;
1071 if (tor_addr_parse(&a, address) >= 0)
1072 return 0;
1075 while (*address) {
1076 if (TOR_ISALNUM(*address) ||
1077 *address == '-' ||
1078 *address == '.' ||
1079 *address == '_') /* Underscore is not allowed, but Windows does it
1080 * sometimes, just to thumb its nose at the IETF. */
1081 ++address;
1082 else
1083 return 1;
1085 return 0;
1088 /** Iterate over all address mappings which have expiry times between
1089 * min_expires and max_expires, inclusive. If sl is provided, add an
1090 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1091 * the expiry time if want_expiry is false. If sl is NULL, remove the
1092 * mappings.
1094 void
1095 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1096 time_t max_expires, int want_expiry)
1098 strmap_iter_t *iter;
1099 const char *key;
1100 void *val_;
1101 addressmap_entry_t *val;
1103 if (!addressmap)
1104 addressmap_init();
1106 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1107 strmap_iter_get(iter, &key, &val_);
1108 val = val_;
1109 if (val->expires >= min_expires && val->expires <= max_expires) {
1110 if (!sl) {
1111 iter = strmap_iter_next_rmv(addressmap,iter);
1112 addressmap_ent_remove(key, val);
1113 continue;
1114 } else if (val->new_address) {
1115 const char *src_wc = val->src_wildcard ? "*." : "";
1116 const char *dst_wc = val->dst_wildcard ? "*." : "";
1117 if (want_expiry) {
1118 if (val->expires < 3 || val->expires == TIME_MAX)
1119 smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
1120 src_wc, key, dst_wc, val->new_address);
1121 else {
1122 char isotime[ISO_TIME_LEN+1];
1123 format_iso_time(isotime, val->expires);
1124 smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
1125 src_wc, key, dst_wc, val->new_address,
1126 isotime);
1128 } else {
1129 smartlist_add_asprintf(sl, "%s%s %s%s",
1130 src_wc, key, dst_wc, val->new_address);
1134 iter = strmap_iter_next(addressmap,iter);