1 /* Copyright 2003-2004 Roger Dingledine.
2 * Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
3 /* See LICENSE for licensing information */
5 const char dns_c_id
[] =
10 * \brief Implements a local cache for DNS results for Tor servers.
11 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
12 * (We can't just use gethostbyname() and friends because we really need to
17 #include "../common/ht.h"
20 /** Longest hostname we're willing to resolve. */
21 #define MAX_ADDRESSLEN 256
23 /** How long will we wait for an answer from the resolver before we decide
24 * that the resolver is wedged? */
25 #define RESOLVE_MAX_TIMEOUT 300
27 /** Possible outcomes from hostname lookup: permanent failure,
28 * transient (retryable) failure, and success. */
29 #define DNS_RESOLVE_FAILED_TRANSIENT 1
30 #define DNS_RESOLVE_FAILED_PERMANENT 2
31 #define DNS_RESOLVE_SUCCEEDED 3
33 /** Have we currently configured nameservers with eventdns? */
34 static int nameservers_configured
= 0;
35 /** What was the resolv_conf fname we last used when configuring the
36 * nameservers? Used to check whether we need to reconfigure. */
37 static char *resolv_conf_fname
= NULL
;
38 /** What was the mtime on the resolv.conf file we last used when configuring
39 * the nameservers? Used to check whether we need to reconfigure. */
40 static time_t resolv_conf_mtime
= 0;
42 /** Linked list of connections waiting for a DNS answer. */
43 typedef struct pending_connection_t
{
44 edge_connection_t
*conn
;
45 struct pending_connection_t
*next
;
46 } pending_connection_t
;
48 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
49 * pointers and memory stomping. */
50 #define CACHED_RESOLVE_MAGIC 0x1234F00D
52 /* Possible states for a cached resolve_t */
53 /** We are waiting for the resolver system to tell us an answer here.
54 * When we get one, or when we time out, the state of this cached_resolve_t
55 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
56 * entry. This cached_resolve_t will be in the hash table so that we will
57 * know not to launch more requests for this addr, but rather to add more
58 * connections to the pending list for the addr. */
59 #define CACHE_STATE_PENDING 0
60 /** This used to be a pending cached_resolve_t, and we got an answer for it.
61 * Now we're waiting for this cached_resolve_t to expire. This should
62 * have no pending connections, and should not appear in the hash table. */
63 #define CACHE_STATE_DONE 1
64 /** We are caching an answer for this address. This should have no pending
65 * connections, and should appear in the hash table. */
66 #define CACHE_STATE_CACHED_VALID 2
67 /** We are caching a failure for this address. This should have no pending
68 * connections, and should appear in the hash table */
69 #define CACHE_STATE_CACHED_FAILED 3
71 /** A DNS request: possibly completed, possibly pending; cached_resolve
72 * structs are stored at the OR side in a hash table, and as a linked
73 * list from oldest to newest.
75 typedef struct cached_resolve_t
{
76 HT_ENTRY(cached_resolve_t
) node
;
78 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
80 uint32_t addr
; /**< IPv4 addr for <b>address</b>. */
81 char *hostname
; /**< Hostname for <b>address</b> (if a reverse lookup) */
83 uint8_t state
; /**< Is this cached entry pending/done/valid/failed? */
84 uint8_t is_reverse
; /**< Is this a reverse (addr-to-hostname) lookup? */
85 time_t expire
; /**< Remove items from cache after this time. */
86 uint32_t ttl
; /**< What TTL did the nameserver tell us? */
87 /** Connections that want to know when we get an answer for this resolve. */
88 pending_connection_t
*pending_connections
;
91 static void purge_expired_resolves(time_t now
);
92 static void dns_found_answer(const char *address
, int is_reverse
,
93 uint32_t addr
, const char *hostname
, char outcome
,
95 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
);
96 static int launch_resolve(edge_connection_t
*exitconn
);
97 static void add_wildcarded_test_address(const char *address
);
98 static int configure_nameservers(int force
);
99 static int answer_is_wildcarded(const char *ip
);
100 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
101 or_circuit_t
*oncirc
, char **resolved_to_hostname
);
102 #ifdef DEBUG_DNS_CACHE
103 static void _assert_cache_ok(void);
104 #define assert_cache_ok() _assert_cache_ok()
106 #define assert_cache_ok() STMT_NIL
108 static void assert_resolve_ok(cached_resolve_t
*resolve
);
110 /** Hash table of cached_resolve objects. */
111 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
113 /** Function to compare hashed resolves on their addresses; used to
114 * implement hash tables. */
116 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
118 /* make this smarter one day? */
119 assert_resolve_ok(a
); // Not b; b may be just a search.
120 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
123 /** Hash function for cached_resolve objects */
124 static INLINE
unsigned int
125 cached_resolve_hash(cached_resolve_t
*a
)
127 return ht_string_hash(a
->address
);
130 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
132 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
133 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
135 /** Initialize the DNS cache. */
139 HT_INIT(cache_map
, &cache_root
);
142 /** Helper: called by eventdns when eventdns wants to log something. */
144 evdns_log_cb(int warn
, const char *msg
)
147 static int all_down
= 0;
148 int severity
= warn
? LOG_WARN
: LOG_INFO
;
149 if (!strcmpstart(msg
, "Resolve requested for") &&
150 get_options()->SafeLogging
) {
151 log(LOG_INFO
, LD_EXIT
, "eventdns: Resolve requested.");
153 } else if (!strcmpstart(msg
, "Search: ")) {
156 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
157 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
158 const char *err
= strchr(cp
, ':'+2);
159 /* Don't warn about a single failed nameserver; we'll warn with 'all
160 * nameservers have failed' if we're completely out of nameservers;
161 * otherwise, the situation is tolerable. */
163 control_event_server_status(LOG_NOTICE
,
164 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
167 } else if (!strcmpstart(msg
, "Nameserver ") &&
168 (cp
=strstr(msg
, " is back up"))) {
169 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
170 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
172 control_event_server_status(LOG_NOTICE
,
173 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
175 } else if (!strcmp(msg
, "All nameservers have failed")) {
176 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
179 log(severity
, LD_EXIT
, "eventdns: %s", msg
);
182 /** Initialize the DNS subsystem; called by the OR process. */
187 if (server_mode(get_options()))
188 return configure_nameservers(1);
192 /** Called when DNS-related options change (or may have changed). Returns -1
193 * on failure, 0 on success. */
197 or_options_t
*options
= get_options();
198 if (! server_mode(options
)) {
199 evdns_clear_nameservers_and_suspend();
200 evdns_search_clear();
201 nameservers_configured
= 0;
202 tor_free(resolv_conf_fname
);
203 resolv_conf_mtime
= 0;
205 if (configure_nameservers(0) < 0)
211 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
212 * OP that asked us to resolve it. */
214 dns_clip_ttl(uint32_t ttl
)
216 if (ttl
< MIN_DNS_TTL
)
218 else if (ttl
> MAX_DNS_TTL
)
224 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
227 dns_get_expiry_ttl(uint32_t ttl
)
229 if (ttl
< MIN_DNS_TTL
)
231 else if (ttl
> MAX_DNS_ENTRY_AGE
)
232 return MAX_DNS_ENTRY_AGE
;
237 /** Helper: free storage held by an entry in the DNS cache. */
239 _free_cached_resolve(cached_resolve_t
*r
)
241 while (r
->pending_connections
) {
242 pending_connection_t
*victim
= r
->pending_connections
;
243 r
->pending_connections
= victim
->next
;
247 tor_free(r
->result
.hostname
);
248 r
->magic
= 0xFF00FF00;
252 /** Compare two cached_resolve_t pointers by expiry time, and return
253 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
254 * the priority queue implementation. */
256 _compare_cached_resolves_by_expiry(const void *_a
, const void *_b
)
258 const cached_resolve_t
*a
= _a
, *b
= _b
;
259 return a
->expire
- b
->expire
;
262 /** Priority queue of cached_resolve_t objects to let us know when they
264 static smartlist_t
*cached_resolve_pqueue
= NULL
;
266 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
269 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
271 tor_assert(resolve
&& resolve
->expire
== 0);
272 if (!cached_resolve_pqueue
)
273 cached_resolve_pqueue
= smartlist_create();
274 resolve
->expire
= expires
;
275 smartlist_pqueue_add(cached_resolve_pqueue
,
276 _compare_cached_resolves_by_expiry
,
280 /** Free all storage held in the DNS cache and related structures. */
284 cached_resolve_t
**ptr
, **next
, *item
;
286 if (cached_resolve_pqueue
) {
287 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
289 if (res
->state
== CACHE_STATE_DONE
)
290 _free_cached_resolve(res
);
293 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
295 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
296 _free_cached_resolve(item
);
298 HT_CLEAR(cache_map
, &cache_root
);
299 if (cached_resolve_pqueue
)
300 smartlist_free(cached_resolve_pqueue
);
301 cached_resolve_pqueue
= NULL
;
302 tor_free(resolv_conf_fname
);
305 /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
308 purge_expired_resolves(time_t now
)
310 cached_resolve_t
*resolve
, *removed
;
311 pending_connection_t
*pend
;
312 edge_connection_t
*pendconn
;
315 if (!cached_resolve_pqueue
)
318 while (smartlist_len(cached_resolve_pqueue
)) {
319 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
320 if (resolve
->expire
> now
)
322 smartlist_pqueue_pop(cached_resolve_pqueue
,
323 _compare_cached_resolves_by_expiry
);
325 if (resolve
->state
== CACHE_STATE_PENDING
) {
327 "Expiring a dns resolve %s that's still pending. Forgot to "
328 "cull it? DNS resolve didn't tell us about the timeout?",
329 escaped_safe_str(resolve
->address
));
330 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
331 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
333 "Forgetting old cached resolve (address %s, expires %lu)",
334 escaped_safe_str(resolve
->address
),
335 (unsigned long)resolve
->expire
);
336 tor_assert(!resolve
->pending_connections
);
338 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
339 tor_assert(!resolve
->pending_connections
);
342 if (resolve
->pending_connections
) {
344 "Closing pending connections on timed-out DNS resolve!");
345 tor_fragile_assert();
346 while (resolve
->pending_connections
) {
347 pend
= resolve
->pending_connections
;
348 resolve
->pending_connections
= pend
->next
;
349 /* Connections should only be pending if they have no socket. */
350 tor_assert(pend
->conn
->_base
.s
== -1);
351 pendconn
= pend
->conn
;
352 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
353 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
354 connection_free(TO_CONN(pendconn
));
359 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
360 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
361 resolve
->state
== CACHE_STATE_PENDING
) {
362 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
363 if (removed
!= resolve
) {
364 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
365 " the cache. Tried to purge %s (%p); instead got %s (%p).",
366 resolve
->address
, (void*)resolve
,
367 removed
? removed
->address
: "NULL", (void*)remove
);
369 tor_assert(removed
== resolve
);
370 if (resolve
->is_reverse
)
371 tor_free(resolve
->result
.hostname
);
372 resolve
->magic
= 0xF0BBF0BB;
375 /* This should be in state DONE. Make sure it's not in the cache. */
376 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
377 tor_assert(tmp
!= resolve
);
384 /** Send a response to the RESOLVE request of a connection.
385 * <b>answer_type</b> must be one of
386 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
388 * If <b>circ</b> is provided, and we have a cached answer, send the
389 * answer back along circ; otherwise, send the answer back along
390 * <b>conn</b>'s attached circuit.
393 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
395 char buf
[RELAY_PAYLOAD_SIZE
];
399 buf
[0] = answer_type
;
400 ttl
= dns_clip_ttl(conn
->address_ttl
);
404 case RESOLVED_TYPE_IPV4
:
406 set_uint32(buf
+2, htonl(conn
->_base
.addr
));
407 set_uint32(buf
+6, htonl(ttl
));
410 case RESOLVED_TYPE_ERROR_TRANSIENT
:
411 case RESOLVED_TYPE_ERROR
:
413 const char *errmsg
= "Error resolving hostname";
414 int msglen
= strlen(errmsg
);
417 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
418 set_uint32(buf
+2+msglen
, htonl(ttl
));
426 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
428 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
431 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
432 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
433 * The answer type will be RESOLVED_HOSTNAME.
435 * If <b>circ</b> is provided, and we have a cached answer, send the
436 * answer back along circ; otherwise, send the answer back along
437 * <b>conn</b>'s attached circuit.
440 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
442 char buf
[RELAY_PAYLOAD_SIZE
];
445 size_t namelen
= strlen(hostname
);
446 tor_assert(hostname
);
448 tor_assert(namelen
< 256);
449 ttl
= dns_clip_ttl(conn
->address_ttl
);
451 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
452 buf
[1] = (uint8_t)namelen
;
453 memcpy(buf
+2, hostname
, namelen
);
454 set_uint32(buf
+2+namelen
, htonl(ttl
));
455 buflen
= 2+namelen
+4;
457 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
458 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
459 // log_notice(LD_EXIT, "Sent");
462 /** Given a lower-case <b>address</b>, check to see whether it's a
463 * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
464 * parse it and place the address in <b>in</b> if present. Return 1 on success;
465 * 0 if the address is not in in-addr.arpa format, and -1 if the address is
468 parse_inaddr_arpa_address(const char *address
, struct in_addr
*in
)
470 char buf
[INET_NTOA_BUF_LEN
];
473 struct in_addr inaddr
;
475 cp
= strstr(address
, ".in-addr.arpa");
476 if (!cp
|| *(cp
+strlen(".in-addr.arpa")))
477 return 0; /* not an .in-addr.arpa address */
481 if (len
>= INET_NTOA_BUF_LEN
)
482 return -1; /* Too long. */
484 memcpy(buf
, address
, len
);
486 if (tor_inet_aton(buf
, &inaddr
) == 0)
487 return -1; /* malformed. */
491 /* reverse the bytes */
492 a
= ( ((inaddr
.s_addr
& 0x000000fful
) << 24)
493 |((inaddr
.s_addr
& 0x0000ff00ul
) << 8)
494 |((inaddr
.s_addr
& 0x00ff0000ul
) >> 8)
495 |((inaddr
.s_addr
& 0xff000000ul
) >> 24));
498 memcpy(in
, &inaddr
, sizeof(inaddr
));
504 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
505 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
506 * If resolve failed, free exitconn and return -1.
508 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
509 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
510 * need to send back an END cell, since connection_exit_begin_conn will
513 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
516 * Else, if seen before and pending, add conn to the pending list,
519 * Else, if not seen before, add conn to pending list, hand to
520 * dns farm, and return 0.
522 * Exitconn's on_circuit field must be set, but exitconn should not
523 * yet be linked onto the n_streams/resolving_streams list of that circuit.
524 * On success, link the connection to n_streams if it's an exit connection.
525 * On "pending", link the connection to resolving streams. Otherwise,
526 * clear its on_circuit field.
529 dns_resolve(edge_connection_t
*exitconn
)
531 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
533 char *hostname
= NULL
;
534 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
536 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
539 /* We got an answer without a lookup -- either the answer was
540 * cached, or it was obvious (like an IP address). */
542 /* Send the answer back right now, and detach. */
544 send_resolved_hostname_cell(exitconn
, hostname
);
546 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
547 exitconn
->on_circuit
= NULL
;
549 /* Add to the n_streams list; the calling function will send back a
551 exitconn
->next_stream
= oncirc
->n_streams
;
552 oncirc
->n_streams
= exitconn
;
556 /* The request is pending: add the connection into the linked list of
557 * resolving_streams on this circuit. */
558 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
559 exitconn
->next_stream
= oncirc
->resolving_streams
;
560 oncirc
->resolving_streams
= exitconn
;
564 /* The request failed before it could start: cancel this connection,
565 * and stop everybody waiting for the same connection. */
567 send_resolved_cell(exitconn
,
568 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
571 exitconn
->on_circuit
= NULL
;
573 dns_cancel_pending_resolve(exitconn
->_base
.address
);
575 if (!exitconn
->_base
.marked_for_close
) {
576 connection_free(TO_CONN(exitconn
));
577 //XXX020 ... and we just leak exitconn otherwise? -RD
578 // If it's marked for close, it's on closeable_connection_lst in
579 // main.c. If it's on the closeable list, it will get freed from
581 // "<armadev> If that's true, there are other bugs around, where we
582 // don't check if it's marked, and will end up double-freeing."
593 /** Helper function for dns_resolve: same functionality, but does not handle:
594 * - marking connections on error and clearing their on_circuit
595 * - linking connections to n_streams/resolving_streams,
596 * - sending resolved cells if we have an answer/error right away,
598 * Return -2 on a transient error. If it's a reverse resolve and it's
599 * successful, sets *<b>hostname_out</b> to a newly allocated string
600 * holding the cached reverse DNS value.
603 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
604 or_circuit_t
*oncirc
, char **hostname_out
)
606 cached_resolve_t
*resolve
;
607 cached_resolve_t search
;
608 pending_connection_t
*pending_connection
;
610 time_t now
= time(NULL
);
611 int is_reverse
= 0, r
;
612 assert_connection_ok(TO_CONN(exitconn
), 0);
613 tor_assert(exitconn
->_base
.s
== -1);
617 /* first check if exitconn->_base.address is an IP. If so, we already
618 * know the answer. */
619 if (tor_inet_aton(exitconn
->_base
.address
, &in
) != 0) {
620 exitconn
->_base
.addr
= ntohl(in
.s_addr
);
621 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
624 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
625 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
626 "Rejecting invalid destination address %s",
627 escaped_safe_str(exitconn
->_base
.address
));
631 /* then take this opportunity to see if there are any expired
632 * resolves in the hash table. */
633 purge_expired_resolves(now
);
635 /* lower-case exitconn->_base.address, so it's in canonical form */
636 tor_strlower(exitconn
->_base
.address
);
638 /* Check whether this is a reverse lookup. If it's malformed, or it's a
639 * .in-addr.arpa address but this isn't a resolve request, kill the
642 if ((r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, NULL
)) != 0) {
646 if (!is_reverse
|| !is_resolve
) {
648 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
649 escaped_safe_str(exitconn
->_base
.address
));
650 else if (!is_resolve
)
652 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
654 escaped_safe_str(exitconn
->_base
.address
));
658 //log_notice(LD_EXIT, "Looks like an address %s",
659 //exitconn->_base.address);
662 /* now check the hash table to see if 'address' is already there. */
663 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
664 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
665 if (resolve
&& resolve
->expire
> now
) { /* already there */
666 switch (resolve
->state
) {
667 case CACHE_STATE_PENDING
:
668 /* add us to the pending list */
669 pending_connection
= tor_malloc_zero(
670 sizeof(pending_connection_t
));
671 pending_connection
->conn
= exitconn
;
672 pending_connection
->next
= resolve
->pending_connections
;
673 resolve
->pending_connections
= pending_connection
;
674 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
675 "resolve of %s", exitconn
->_base
.s
,
676 escaped_safe_str(exitconn
->_base
.address
));
678 case CACHE_STATE_CACHED_VALID
:
679 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
681 escaped_safe_str(resolve
->address
));
682 exitconn
->address_ttl
= resolve
->ttl
;
683 if (resolve
->is_reverse
) {
684 tor_assert(is_resolve
);
685 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
687 exitconn
->_base
.addr
= resolve
->result
.addr
;
690 case CACHE_STATE_CACHED_FAILED
:
691 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
693 escaped_safe_str(exitconn
->_base
.address
));
695 case CACHE_STATE_DONE
:
696 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
697 tor_fragile_assert();
701 /* not there, need to add it */
702 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
703 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
704 resolve
->state
= CACHE_STATE_PENDING
;
705 resolve
->is_reverse
= is_reverse
;
706 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
708 /* add this connection to the pending list */
709 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
710 pending_connection
->conn
= exitconn
;
711 resolve
->pending_connections
= pending_connection
;
713 /* Add this resolve to the cache and priority queue. */
714 HT_INSERT(cache_map
, &cache_root
, resolve
);
715 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
717 log_debug(LD_EXIT
,"Launching %s.",
718 escaped_safe_str(exitconn
->_base
.address
));
721 return launch_resolve(exitconn
);
724 /** Log an error and abort if conn is waiting for a DNS resolve.
727 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
729 pending_connection_t
*pend
;
730 cached_resolve_t
**resolve
;
732 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
733 for (pend
= (*resolve
)->pending_connections
;
736 tor_assert(pend
->conn
!= conn
);
741 /** Log an error and abort if any connection waiting for a DNS resolve is
744 assert_all_pending_dns_resolves_ok(void)
746 pending_connection_t
*pend
;
747 cached_resolve_t
**resolve
;
749 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
750 for (pend
= (*resolve
)->pending_connections
;
753 assert_connection_ok(TO_CONN(pend
->conn
), 0);
754 tor_assert(pend
->conn
->_base
.s
== -1);
755 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
760 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
763 connection_dns_remove(edge_connection_t
*conn
)
765 pending_connection_t
*pend
, *victim
;
766 cached_resolve_t search
;
767 cached_resolve_t
*resolve
;
769 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
770 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
772 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
774 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
776 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
777 escaped_safe_str(conn
->_base
.address
));
781 tor_assert(resolve
->pending_connections
);
782 assert_connection_ok(TO_CONN(conn
),0);
784 pend
= resolve
->pending_connections
;
786 if (pend
->conn
== conn
) {
787 resolve
->pending_connections
= pend
->next
;
789 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
791 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
794 for ( ; pend
->next
; pend
= pend
->next
) {
795 if (pend
->next
->conn
== conn
) {
797 pend
->next
= victim
->next
;
800 "Connection (fd %d) no longer waiting for resolve of %s",
801 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
802 return; /* more are pending */
805 tor_assert(0); /* not reachable unless onlyconn not in pending list */
809 /** Mark all connections waiting for <b>address</b> for close. Then cancel
810 * the resolve for <b>address</b> itself, and remove any cached results for
811 * <b>address</b> from the cache.
814 dns_cancel_pending_resolve(const char *address
)
816 pending_connection_t
*pend
;
817 cached_resolve_t search
;
818 cached_resolve_t
*resolve
, *tmp
;
819 edge_connection_t
*pendconn
;
822 strlcpy(search
.address
, address
, sizeof(search
.address
));
824 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
828 if(resolve
->state
!= CACHE_STATE_PENDING
) {
829 log_notice(LD_BUG
,"Address %s is not pending (state %d). Dropping.",
830 escaped_safe_str(address
), resolve
->state
);
834 if (!resolve
->pending_connections
) {
835 /* XXX this should never trigger, but sometimes it does */
836 /* XXXX020 is the above still true? -NM */
838 "Address %s is pending but has no pending connections!",
839 escaped_safe_str(address
));
840 tor_fragile_assert();
843 tor_assert(resolve
->pending_connections
);
845 /* mark all pending connections to fail */
847 "Failing all connections waiting on DNS resolve of %s",
848 escaped_safe_str(address
));
849 while (resolve
->pending_connections
) {
850 pend
= resolve
->pending_connections
;
851 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
852 pendconn
= pend
->conn
;
853 assert_connection_ok(TO_CONN(pendconn
), 0);
854 tor_assert(pendconn
->_base
.s
== -1);
855 if (!pendconn
->_base
.marked_for_close
) {
856 /* XXXX020 RESOURCELIMIT? Not RESOLVEFAILED??? */
857 connection_edge_end(pendconn
, END_STREAM_REASON_RESOURCELIMIT
);
859 circ
= circuit_get_by_edge_conn(pendconn
);
861 circuit_detach_stream(circ
, pendconn
);
862 if (!pendconn
->_base
.marked_for_close
)
863 connection_free(TO_CONN(pendconn
));
864 resolve
->pending_connections
= pend
->next
;
868 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
869 if (tmp
!= resolve
) {
870 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
871 " the cache. Tried to purge %s (%p); instead got %s (%p).",
872 resolve
->address
, (void*)resolve
,
873 tmp
? tmp
->address
: "NULL", (void*)tmp
);
875 tor_assert(tmp
== resolve
);
877 resolve
->state
= CACHE_STATE_DONE
;
880 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
881 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
882 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
883 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
886 add_answer_to_cache(const char *address
, int is_reverse
, uint32_t addr
,
887 const char *hostname
, char outcome
, uint32_t ttl
)
889 cached_resolve_t
*resolve
;
890 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
893 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
894 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
895 // hostname?hostname:"NULL",(int)outcome);
897 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
898 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
899 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
900 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
901 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
902 resolve
->is_reverse
= is_reverse
;
904 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
905 tor_assert(hostname
);
906 resolve
->result
.hostname
= tor_strdup(hostname
);
908 tor_assert(! hostname
);
909 resolve
->result
.hostname
= NULL
;
912 tor_assert(!hostname
);
913 resolve
->result
.addr
= addr
;
916 assert_resolve_ok(resolve
);
917 HT_INSERT(cache_map
, &cache_root
, resolve
);
918 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
921 /** Return true iff <b>address</b> is one of the addresses we use to verify
922 * that well-known sites aren't being hijacked by our DNS servers. */
924 is_test_address(const char *address
)
926 or_options_t
*options
= get_options();
927 return options
->ServerDNSTestAddresses
&&
928 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
931 /** Called on the OR side when a DNS worker or the eventdns library tells us
932 * the outcome of a DNS resolve: tell all pending connections about the result
933 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
934 * string containing the address to look up; <b>addr</b> is an IPv4 address in
935 * host order; <b>outcome</b> is one of
936 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
939 dns_found_answer(const char *address
, int is_reverse
, uint32_t addr
,
940 const char *hostname
, char outcome
, uint32_t ttl
)
942 pending_connection_t
*pend
;
943 cached_resolve_t search
;
944 cached_resolve_t
*resolve
, *removed
;
945 edge_connection_t
*pendconn
;
950 strlcpy(search
.address
, address
, sizeof(search
.address
));
952 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
954 int is_test_addr
= is_test_address(address
);
956 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
957 escaped_safe_str(address
));
958 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
961 assert_resolve_ok(resolve
);
963 if (resolve
->state
!= CACHE_STATE_PENDING
) {
964 /* XXXX020 Maybe update addr? or check addr for consistency? Or let
965 * VALID replace FAILED? */
966 int is_test_addr
= is_test_address(address
);
969 "Resolved %s which was already resolved; ignoring",
970 escaped_safe_str(address
));
971 tor_assert(resolve
->pending_connections
== NULL
);
974 /* Removed this assertion: in fact, we'll sometimes get a double answer
975 * to the same question. This can happen when we ask one worker to resolve
976 * X.Y.Z., then we cancel the request, and then we ask another worker to
978 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
980 while (resolve
->pending_connections
) {
981 pend
= resolve
->pending_connections
;
982 pendconn
= pend
->conn
; /* don't pass complex things to the
983 connection_mark_for_close macro */
984 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
985 pendconn
->_base
.addr
= addr
;
986 pendconn
->address_ttl
= ttl
;
988 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
989 /* prevent double-remove. */
990 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
991 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
992 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
993 /* This detach must happen after we send the end cell. */
994 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
996 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
997 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
998 /* This detach must happen after we send the resolved cell. */
999 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1001 connection_free(TO_CONN(pendconn
));
1003 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1004 tor_assert(!is_reverse
);
1005 /* prevent double-remove. */
1006 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1008 circ
= circuit_get_by_edge_conn(pend
->conn
);
1010 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1011 /* unlink pend->conn from resolving_streams, */
1012 circuit_detach_stream(circ
, pend
->conn
);
1013 /* and link it to n_streams */
1014 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1015 pend
->conn
->on_circuit
= circ
;
1016 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1018 connection_exit_connect(pend
->conn
);
1020 /* prevent double-remove. This isn't really an accurate state,
1021 * but it does the right thing. */
1022 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1024 send_resolved_hostname_cell(pendconn
, hostname
);
1026 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1027 circ
= circuit_get_by_edge_conn(pendconn
);
1029 circuit_detach_stream(circ
, pendconn
);
1030 connection_free(TO_CONN(pendconn
));
1033 resolve
->pending_connections
= pend
->next
;
1037 resolve
->state
= CACHE_STATE_DONE
;
1038 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1039 if (removed
!= resolve
) {
1040 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1041 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1042 resolve
->address
, (void*)resolve
,
1043 removed
? removed
->address
: "NULL", (void*)removed
);
1045 assert_resolve_ok(resolve
);
1048 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1052 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1053 * a transient failure. */
1055 evdns_err_is_transient(int err
)
1059 case DNS_ERR_SERVERFAILED
:
1060 case DNS_ERR_TRUNCATED
:
1061 case DNS_ERR_TIMEOUT
:
1068 /** Configure eventdns nameservers if force is true, or if the configuration
1069 * has changed since the last time we called this function. On Unix, this
1070 * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
1071 * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
1072 * Return 0 on success or -1 on failure. */
1074 configure_nameservers(int force
)
1076 or_options_t
*options
;
1077 const char *conf_fname
;
1080 options
= get_options();
1081 conf_fname
= options
->ServerDNSResolvConfFile
;
1084 conf_fname
= "/etc/resolv.conf";
1087 evdns_set_log_fn(evdns_log_cb
);
1089 if (stat(conf_fname
, &st
)) {
1090 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1091 conf_fname
, strerror(errno
));
1094 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1095 && st
.st_mtime
== resolv_conf_mtime
) {
1096 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1099 if (nameservers_configured
) {
1100 evdns_search_clear();
1101 evdns_clear_nameservers_and_suspend();
1103 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1104 if ((r
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, conf_fname
))) {
1105 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1106 conf_fname
, conf_fname
, r
);
1109 if (evdns_count_nameservers() == 0) {
1110 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1113 tor_free(resolv_conf_fname
);
1114 resolv_conf_fname
= tor_strdup(conf_fname
);
1115 resolv_conf_mtime
= st
.st_mtime
;
1116 if (nameservers_configured
)
1121 if (nameservers_configured
) {
1122 evdns_search_clear();
1123 evdns_clear_nameservers_and_suspend();
1125 if (evdns_config_windows_nameservers()) {
1126 log_warn(LD_EXIT
,"Could not config nameservers.");
1129 if (evdns_count_nameservers() == 0) {
1130 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1131 "your Windows configuration. Perhaps you should list a "
1132 "ServerDNSResolvConfFile file in your torrc?");
1135 if (nameservers_configured
)
1137 tor_free(resolv_conf_fname
);
1138 resolv_conf_mtime
= 0;
1142 if (evdns_count_nameservers() == 1) {
1143 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL
);
1144 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL
);
1146 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL
);
1147 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL
);
1150 dns_servers_relaunch_checks();
1152 nameservers_configured
= 1;
1156 /** For eventdns: Called when we get an answer for a request we launched.
1157 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1160 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1163 char *string_address
= arg
;
1165 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1167 const char *hostname
= NULL
;
1168 int was_wildcarded
= 0;
1170 if (result
== DNS_ERR_NONE
) {
1171 if (type
== DNS_IPv4_A
&& count
) {
1172 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1174 char *escaped_address
;
1175 uint32_t *addrs
= addresses
;
1176 in
.s_addr
= addrs
[0];
1177 addr
= ntohl(addrs
[0]);
1178 status
= DNS_RESOLVE_SUCCEEDED
;
1179 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1180 escaped_address
= esc_for_log(string_address
);
1182 if (answer_is_wildcarded(answer_buf
)) {
1183 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1184 "address %s; treating as a failure.",
1185 safe_str(escaped_address
),
1186 escaped_safe_str(answer_buf
));
1189 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1191 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1192 safe_str(escaped_address
),
1193 escaped_safe_str(answer_buf
));
1195 tor_free(escaped_address
);
1196 } else if (type
== DNS_PTR
&& count
) {
1197 char *escaped_address
;
1199 hostname
= ((char**)addresses
)[0];
1200 status
= DNS_RESOLVE_SUCCEEDED
;
1201 escaped_address
= esc_for_log(string_address
);
1202 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1203 safe_str(escaped_address
),
1204 escaped_safe_str(hostname
));
1205 tor_free(escaped_address
);
1207 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1208 escaped_safe_str(string_address
));
1210 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1211 escaped_safe_str(string_address
));
1214 if (evdns_err_is_transient(result
))
1215 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1217 if (was_wildcarded
) {
1218 if (is_test_address(string_address
)) {
1219 /* Ick. We're getting redirected on known-good addresses. Our DNS
1220 * server must really hate us. */
1221 add_wildcarded_test_address(string_address
);
1224 if (result
!= DNS_ERR_SHUTDOWN
)
1225 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1226 tor_free(string_address
);
1229 /** For eventdns: start resolving as necessary to find the target for
1230 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1231 * 0 on "resolve launched." */
1233 launch_resolve(edge_connection_t
*exitconn
)
1235 char *addr
= tor_strdup(exitconn
->_base
.address
);
1238 int options
= get_options()->ServerDNSSearchDomains
? 0
1239 : DNS_QUERY_NO_SEARCH
;
1240 /* What? Nameservers not configured? Sounds like a bug. */
1241 if (!nameservers_configured
) {
1242 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1243 "launched. Configuring.");
1244 if (configure_nameservers(1) < 0)
1248 r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, &in
);
1250 log_info(LD_EXIT
, "Launching eventdns request for %s",
1251 escaped_safe_str(exitconn
->_base
.address
));
1252 r
= evdns_resolve_ipv4(exitconn
->_base
.address
, options
,
1253 evdns_callback
, addr
);
1254 } else if (r
== 1) {
1255 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1256 escaped_safe_str(exitconn
->_base
.address
));
1257 r
= evdns_resolve_reverse(&in
, DNS_QUERY_NO_SEARCH
,
1258 evdns_callback
, addr
);
1259 } else if (r
== -1) {
1260 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1264 log_warn(LD_EXIT
, "eventdns rejected address %s: error %d.",
1265 escaped_safe_str(addr
), r
);
1266 r
= evdns_err_is_transient(r
) ? -2 : -1;
1267 tor_free(addr
); /* There is no evdns request in progress; stop
1268 * addr from getting leaked. */
1273 /** How many requests for bogus addresses have we launched so far? */
1274 static int n_wildcard_requests
= 0;
1276 /** Map from dotted-quad IP address in response to an int holding how many
1277 * times we've seen it for a randomly generated (hopefully bogus) address. It
1278 * would be easier to use definitely-invalid addresses (as specified by
1279 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1280 static strmap_t
*dns_wildcard_response_count
= NULL
;
1282 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1283 * nameserver wants to return in response to requests for nonexistent domains.
1285 static smartlist_t
*dns_wildcard_list
= NULL
;
1286 /** True iff we've logged about a single address getting wildcarded.
1287 * Subsequent warnings will be less severe. */
1288 static int dns_wildcard_one_notice_given
= 0;
1289 /** True iff we've warned that our DNS server is wildcarding too many failures.
1291 static int dns_wildcard_notice_given
= 0;
1293 /** List of supposedly good addresses that are getting wildcarded to the
1294 * same addresses as nonexistent addresses. */
1295 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1296 /** True iff we've warned about a test address getting wildcarded */
1297 static int dns_wildcarded_test_address_notice_given
= 0;
1298 /** True iff all addresses seem to be getting wildcarded. */
1299 static int dns_is_completely_invalid
= 0;
1301 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1302 * a hopefully bogus address. */
1304 wildcard_increment_answer(const char *id
)
1307 if (!dns_wildcard_response_count
)
1308 dns_wildcard_response_count
= strmap_new();
1310 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1312 ip
= tor_malloc_zero(sizeof(int));
1313 strmap_set(dns_wildcard_response_count
, id
, ip
);
1317 if (*ip
> 5 && n_wildcard_requests
> 10) {
1318 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1319 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1320 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1321 "Your DNS provider has given \"%s\" as an answer for %d different "
1322 "invalid addresses. Apparently they are hijacking DNS failures. "
1323 "I'll try to correct for this by treating future occurrences of "
1324 "\"%s\" as 'not found'.", id
, *ip
, id
);
1325 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1327 if (!dns_wildcard_notice_given
)
1328 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1329 dns_wildcard_notice_given
= 1;
1333 /** Note that a single test address (one believed to be good) seems to be
1334 * getting redirected to the same IP as failures are. */
1336 add_wildcarded_test_address(const char *address
)
1338 int n
, n_test_addrs
;
1339 if (!dns_wildcarded_test_address_list
)
1340 dns_wildcarded_test_address_list
= smartlist_create();
1342 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1345 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1346 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1348 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1349 n
= smartlist_len(dns_wildcarded_test_address_list
);
1350 if (n
> n_test_addrs
/2) {
1351 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1352 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1353 "address. It has done this with %d test addresses so far. I'm "
1354 "going to stop being an exit node for now, since our DNS seems so "
1355 "broken.", address
, n
);
1356 if (!dns_is_completely_invalid
) {
1357 dns_is_completely_invalid
= 1;
1358 mark_my_descriptor_dirty();
1360 if (!dns_wildcarded_test_address_notice_given
)
1361 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1362 dns_wildcarded_test_address_notice_given
= 1;
1366 /** Callback function when we get an answer (possibly failing) for a request
1367 * for a (hopefully) nonexistent domain. */
1369 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1370 void *addresses
, void *arg
)
1373 ++n_wildcard_requests
;
1374 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1375 uint32_t *addrs
= addresses
;
1377 char *string_address
= arg
;
1378 for (i
= 0; i
< count
; ++i
) {
1379 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1381 in
.s_addr
= addrs
[i
];
1382 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1383 wildcard_increment_answer(answer_buf
);
1385 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1386 "Your DNS provider gave an answer for \"%s\", which "
1387 "is not supposed to exist. Apparently they are hijacking "
1388 "DNS failures. Trying to correct for this. We've noticed %d possibly "
1389 "bad addresses so far.",
1390 string_address
, strmap_size(dns_wildcard_response_count
));
1391 dns_wildcard_one_notice_given
= 1;
1396 /** Launch a single request for a nonexistent hostname consisting of between
1397 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1400 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1402 char random_bytes
[20], name
[64], *addr
;
1406 len
= min_len
+ crypto_rand_int(max_len
-min_len
+1);
1407 if (crypto_rand(random_bytes
, sizeof(random_bytes
)) < 0)
1409 base32_encode(name
, sizeof(name
), random_bytes
, sizeof(random_bytes
));
1411 strlcat(name
, suffix
, sizeof(name
));
1413 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1414 "domains with requrest for bogus hostname \"%s\"", name
);
1416 addr
= tor_strdup(name
);
1417 r
= evdns_resolve_ipv4(name
, DNS_QUERY_NO_SEARCH
,
1418 evdns_wildcard_check_callback
, addr
);
1423 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1424 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1426 launch_test_addresses(int fd
, short event
, void *args
)
1428 or_options_t
*options
= get_options();
1433 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1434 "hijack *everything*.");
1435 /* This situation is worse than the failure-hijacking situation. When this
1436 * happens, we're no good for DNS requests at all, and we shouldn't really
1437 * be an exit server.*/
1438 if (!options
->ServerDNSTestAddresses
)
1440 SMARTLIST_FOREACH(options
->ServerDNSTestAddresses
, const char *, address
,
1442 evdns_resolve_ipv4(address
, DNS_QUERY_NO_SEARCH
, evdns_callback
,
1443 tor_strdup(address
));
1447 #define N_WILDCARD_CHECKS 2
1449 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1450 * hostnames, and see if we can catch our nameserver trying to hijack them and
1451 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1452 * buy these lovely encyclopedias" page. */
1454 dns_launch_wildcard_checks(void)
1457 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1458 "to hijack DNS failures.");
1459 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1460 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1461 * to 'comply' with rfc2606, refrain from giving A records for these.
1462 * This is the standards-compliance equivalent of making sure that your
1463 * crackhouse's elevator inspection certificate is up to date.
1465 launch_wildcard_check(2, 16, ".invalid");
1466 launch_wildcard_check(2, 16, ".test");
1468 /* These will break specs if there are ever any number of
1469 * 8+-character top-level domains. */
1470 launch_wildcard_check(8, 16, "");
1472 /* Try some random .com/org/net domains. This will work fine so long as
1473 * not too many resolve to the same place. */
1474 launch_wildcard_check(8, 16, ".com");
1475 launch_wildcard_check(8, 16, ".org");
1476 launch_wildcard_check(8, 16, ".net");
1480 /** If appropriate, start testing whether our DNS servers tend to lie to
1483 dns_launch_correctness_checks(void)
1485 static struct event launch_event
;
1486 struct timeval timeout
;
1487 if (!get_options()->ServerDNSDetectHijacking
)
1489 dns_launch_wildcard_checks();
1491 /* Wait a while before launching requests for test addresses, so we can
1492 * get the results from checking for wildcarding. */
1493 evtimer_set(&launch_event
, launch_test_addresses
, NULL
);
1494 timeout
.tv_sec
= 30;
1495 timeout
.tv_usec
= 0;
1496 evtimer_add(&launch_event
, &timeout
);
1499 /** Return true iff our DNS servers lie to us too much to be trustd. */
1501 dns_seems_to_be_broken(void)
1503 return dns_is_completely_invalid
;
1506 /** Forget what we've previously learned about our DNS servers' correctness. */
1508 dns_reset_correctness_checks(void)
1510 if (dns_wildcard_response_count
) {
1511 strmap_free(dns_wildcard_response_count
, _tor_free
);
1512 dns_wildcard_response_count
= NULL
;
1514 n_wildcard_requests
= 0;
1516 if (dns_wildcard_list
) {
1517 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1518 smartlist_clear(dns_wildcard_list
);
1520 if (dns_wildcarded_test_address_list
) {
1521 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1523 smartlist_clear(dns_wildcarded_test_address_list
);
1525 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1526 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1529 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1530 * returned in response to requests for nonexistent hostnames. */
1532 answer_is_wildcarded(const char *ip
)
1534 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1537 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1539 assert_resolve_ok(cached_resolve_t
*resolve
)
1541 tor_assert(resolve
);
1542 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1543 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1544 tor_assert(tor_strisnonupper(resolve
->address
));
1545 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1546 tor_assert(!resolve
->pending_connections
);
1548 if (resolve
->state
== CACHE_STATE_PENDING
||
1549 resolve
->state
== CACHE_STATE_DONE
) {
1550 tor_assert(!resolve
->ttl
);
1551 if (resolve
->is_reverse
)
1552 tor_assert(!resolve
->result
.hostname
);
1554 tor_assert(!resolve
->result
.addr
);
1558 #ifdef DEBUG_DNS_CACHE
1559 /** Exit with an assertion if the DNS cache is corrupt. */
1561 _assert_cache_ok(void)
1563 cached_resolve_t
**resolve
;
1564 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1566 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1567 tor_assert(!bad_rep
);
1570 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1571 assert_resolve_ok(*resolve
);
1572 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1574 if (!cached_resolve_pqueue
)
1577 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1578 _compare_cached_resolves_by_expiry
);
1580 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1582 if (res
->state
== CACHE_STATE_DONE
) {
1583 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1584 tor_assert(!found
|| found
!= res
);
1586 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);