1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 const char dns_c_id
[] =
11 * \brief Implements a local cache for DNS results for Tor servers.
12 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
13 * (We can't just use gethostbyname() and friends because we really need to
21 /** Longest hostname we're willing to resolve. */
22 #define MAX_ADDRESSLEN 256
24 /** How long will we wait for an answer from the resolver before we decide
25 * that the resolver is wedged? */
26 #define RESOLVE_MAX_TIMEOUT 300
28 /** Possible outcomes from hostname lookup: permanent failure,
29 * transient (retryable) failure, and success. */
30 #define DNS_RESOLVE_FAILED_TRANSIENT 1
31 #define DNS_RESOLVE_FAILED_PERMANENT 2
32 #define DNS_RESOLVE_SUCCEEDED 3
34 /** Have we currently configured nameservers with eventdns? */
35 static int nameservers_configured
= 0;
36 /** What was the resolv_conf fname we last used when configuring the
37 * nameservers? Used to check whether we need to reconfigure. */
38 static char *resolv_conf_fname
= NULL
;
39 /** What was the mtime on the resolv.conf file we last used when configuring
40 * the nameservers? Used to check whether we need to reconfigure. */
41 static time_t resolv_conf_mtime
= 0;
43 /** Linked list of connections waiting for a DNS answer. */
44 typedef struct pending_connection_t
{
45 edge_connection_t
*conn
;
46 struct pending_connection_t
*next
;
47 } pending_connection_t
;
49 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
50 * pointers and memory stomping. */
51 #define CACHED_RESOLVE_MAGIC 0x1234F00D
53 /* Possible states for a cached resolve_t */
54 /** We are waiting for the resolver system to tell us an answer here.
55 * When we get one, or when we time out, the state of this cached_resolve_t
56 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
57 * entry. This cached_resolve_t will be in the hash table so that we will
58 * know not to launch more requests for this addr, but rather to add more
59 * connections to the pending list for the addr. */
60 #define CACHE_STATE_PENDING 0
61 /** This used to be a pending cached_resolve_t, and we got an answer for it.
62 * Now we're waiting for this cached_resolve_t to expire. This should
63 * have no pending connections, and should not appear in the hash table. */
64 #define CACHE_STATE_DONE 1
65 /** We are caching an answer for this address. This should have no pending
66 * connections, and should appear in the hash table. */
67 #define CACHE_STATE_CACHED_VALID 2
68 /** We are caching a failure for this address. This should have no pending
69 * connections, and should appear in the hash table */
70 #define CACHE_STATE_CACHED_FAILED 3
72 /** A DNS request: possibly completed, possibly pending; cached_resolve
73 * structs are stored at the OR side in a hash table, and as a linked
74 * list from oldest to newest.
76 typedef struct cached_resolve_t
{
77 HT_ENTRY(cached_resolve_t
) node
;
79 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
81 uint32_t addr
; /**< IPv4 addr for <b>address</b>. */
82 char *hostname
; /**< Hostname for <b>address</b> (if a reverse lookup) */
84 uint8_t state
; /**< Is this cached entry pending/done/valid/failed? */
85 uint8_t is_reverse
; /**< Is this a reverse (addr-to-hostname) lookup? */
86 time_t expire
; /**< Remove items from cache after this time. */
87 uint32_t ttl
; /**< What TTL did the nameserver tell us? */
88 /** Connections that want to know when we get an answer for this resolve. */
89 pending_connection_t
*pending_connections
;
92 static void purge_expired_resolves(time_t now
);
93 static void dns_found_answer(const char *address
, uint8_t is_reverse
,
94 uint32_t addr
, const char *hostname
, char outcome
,
96 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
);
97 static int launch_resolve(edge_connection_t
*exitconn
);
98 static void add_wildcarded_test_address(const char *address
);
99 static int configure_nameservers(int force
);
100 static int answer_is_wildcarded(const char *ip
);
101 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
102 or_circuit_t
*oncirc
, char **resolved_to_hostname
);
103 #ifdef DEBUG_DNS_CACHE
104 static void _assert_cache_ok(void);
105 #define assert_cache_ok() _assert_cache_ok()
107 #define assert_cache_ok() STMT_NIL
109 static void assert_resolve_ok(cached_resolve_t
*resolve
);
111 /** Hash table of cached_resolve objects. */
112 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
114 /** Function to compare hashed resolves on their addresses; used to
115 * implement hash tables. */
117 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
119 /* make this smarter one day? */
120 assert_resolve_ok(a
); // Not b; b may be just a search.
121 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
124 /** Hash function for cached_resolve objects */
125 static INLINE
unsigned int
126 cached_resolve_hash(cached_resolve_t
*a
)
128 return ht_string_hash(a
->address
);
131 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
133 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
134 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
136 /** Initialize the DNS cache. */
140 HT_INIT(cache_map
, &cache_root
);
143 /** Helper: called by eventdns when eventdns wants to log something. */
145 evdns_log_cb(int warn
, const char *msg
)
148 static int all_down
= 0;
149 int severity
= warn
? LOG_WARN
: LOG_INFO
;
150 if (!strcmpstart(msg
, "Resolve requested for") &&
151 get_options()->SafeLogging
) {
152 log(LOG_INFO
, LD_EXIT
, "eventdns: Resolve requested.");
154 } else if (!strcmpstart(msg
, "Search: ")) {
157 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
158 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
159 const char *err
= strchr(cp
, ':')+2;
161 /* Don't warn about a single failed nameserver; we'll warn with 'all
162 * nameservers have failed' if we're completely out of nameservers;
163 * otherwise, the situation is tolerable. */
165 control_event_server_status(LOG_NOTICE
,
166 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
169 } else if (!strcmpstart(msg
, "Nameserver ") &&
170 (cp
=strstr(msg
, " is back up"))) {
171 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
172 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
174 control_event_server_status(LOG_NOTICE
,
175 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
177 } else if (!strcmp(msg
, "All nameservers have failed")) {
178 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
181 log(severity
, LD_EXIT
, "eventdns: %s", msg
);
184 /** Helper: generate a good random transaction ID. */
186 dns_get_transaction_id(void)
189 crypto_rand((void*)&result
, sizeof(result
));
193 /** Initialize the DNS subsystem; called by the OR process. */
198 evdns_set_transaction_id_fn(dns_get_transaction_id
);
199 if (server_mode(get_options()))
200 return configure_nameservers(1);
204 /** Called when DNS-related options change (or may have changed). Returns -1
205 * on failure, 0 on success. */
209 or_options_t
*options
= get_options();
210 if (! server_mode(options
)) {
211 evdns_clear_nameservers_and_suspend();
212 evdns_search_clear();
213 nameservers_configured
= 0;
214 tor_free(resolv_conf_fname
);
215 resolv_conf_mtime
= 0;
217 if (configure_nameservers(0) < 0)
223 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
224 * OP that asked us to resolve it. */
226 dns_clip_ttl(uint32_t ttl
)
228 if (ttl
< MIN_DNS_TTL
)
230 else if (ttl
> MAX_DNS_TTL
)
236 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
239 dns_get_expiry_ttl(uint32_t ttl
)
241 if (ttl
< MIN_DNS_TTL
)
243 else if (ttl
> MAX_DNS_ENTRY_AGE
)
244 return MAX_DNS_ENTRY_AGE
;
249 /** Helper: free storage held by an entry in the DNS cache. */
251 _free_cached_resolve(cached_resolve_t
*r
)
253 while (r
->pending_connections
) {
254 pending_connection_t
*victim
= r
->pending_connections
;
255 r
->pending_connections
= victim
->next
;
259 tor_free(r
->result
.hostname
);
260 r
->magic
= 0xFF00FF00;
264 /** Compare two cached_resolve_t pointers by expiry time, and return
265 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
266 * the priority queue implementation. */
268 _compare_cached_resolves_by_expiry(const void *_a
, const void *_b
)
270 const cached_resolve_t
*a
= _a
, *b
= _b
;
271 if (a
->expire
< b
->expire
)
273 else if (a
->expire
== b
->expire
)
279 /** Priority queue of cached_resolve_t objects to let us know when they
281 static smartlist_t
*cached_resolve_pqueue
= NULL
;
283 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
286 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
288 tor_assert(resolve
&& resolve
->expire
== 0);
289 if (!cached_resolve_pqueue
)
290 cached_resolve_pqueue
= smartlist_create();
291 resolve
->expire
= expires
;
292 smartlist_pqueue_add(cached_resolve_pqueue
,
293 _compare_cached_resolves_by_expiry
,
297 /** Free all storage held in the DNS cache and related structures. */
301 cached_resolve_t
**ptr
, **next
, *item
;
303 if (cached_resolve_pqueue
) {
304 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
306 if (res
->state
== CACHE_STATE_DONE
)
307 _free_cached_resolve(res
);
310 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
312 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
313 _free_cached_resolve(item
);
315 HT_CLEAR(cache_map
, &cache_root
);
316 if (cached_resolve_pqueue
)
317 smartlist_free(cached_resolve_pqueue
);
318 cached_resolve_pqueue
= NULL
;
319 tor_free(resolv_conf_fname
);
322 /** Remove every cached_resolve whose <b>expire</b> time is before or
323 * equal to <b>now</b> from the cache. */
325 purge_expired_resolves(time_t now
)
327 cached_resolve_t
*resolve
, *removed
;
328 pending_connection_t
*pend
;
329 edge_connection_t
*pendconn
;
332 if (!cached_resolve_pqueue
)
335 while (smartlist_len(cached_resolve_pqueue
)) {
336 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
337 if (resolve
->expire
> now
)
339 smartlist_pqueue_pop(cached_resolve_pqueue
,
340 _compare_cached_resolves_by_expiry
);
342 if (resolve
->state
== CACHE_STATE_PENDING
) {
344 "Expiring a dns resolve %s that's still pending. Forgot to "
345 "cull it? DNS resolve didn't tell us about the timeout?",
346 escaped_safe_str(resolve
->address
));
347 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
348 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
350 "Forgetting old cached resolve (address %s, expires %lu)",
351 escaped_safe_str(resolve
->address
),
352 (unsigned long)resolve
->expire
);
353 tor_assert(!resolve
->pending_connections
);
355 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
356 tor_assert(!resolve
->pending_connections
);
359 if (resolve
->pending_connections
) {
361 "Closing pending connections on timed-out DNS resolve!");
362 tor_fragile_assert();
363 while (resolve
->pending_connections
) {
364 pend
= resolve
->pending_connections
;
365 resolve
->pending_connections
= pend
->next
;
366 /* Connections should only be pending if they have no socket. */
367 tor_assert(pend
->conn
->_base
.s
== -1);
368 pendconn
= pend
->conn
;
369 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
370 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
371 connection_free(TO_CONN(pendconn
));
376 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
377 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
378 resolve
->state
== CACHE_STATE_PENDING
) {
379 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
380 if (removed
!= resolve
) {
381 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
382 " the cache. Tried to purge %s (%p); instead got %s (%p).",
383 resolve
->address
, (void*)resolve
,
384 removed
? removed
->address
: "NULL", (void*)remove
);
386 tor_assert(removed
== resolve
);
388 /* This should be in state DONE. Make sure it's not in the cache. */
389 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
390 tor_assert(tmp
!= resolve
);
392 if (resolve
->is_reverse
)
393 tor_free(resolve
->result
.hostname
);
394 resolve
->magic
= 0xF0BBF0BB;
401 /** Send a response to the RESOLVE request of a connection.
402 * <b>answer_type</b> must be one of
403 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
405 * If <b>circ</b> is provided, and we have a cached answer, send the
406 * answer back along circ; otherwise, send the answer back along
407 * <b>conn</b>'s attached circuit.
410 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
412 char buf
[RELAY_PAYLOAD_SIZE
];
416 buf
[0] = answer_type
;
417 ttl
= dns_clip_ttl(conn
->address_ttl
);
421 case RESOLVED_TYPE_IPV4
:
423 set_uint32(buf
+2, htonl(conn
->_base
.addr
));
424 set_uint32(buf
+6, htonl(ttl
));
427 case RESOLVED_TYPE_ERROR_TRANSIENT
:
428 case RESOLVED_TYPE_ERROR
:
430 const char *errmsg
= "Error resolving hostname";
431 size_t msglen
= strlen(errmsg
);
434 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
435 set_uint32(buf
+2+msglen
, htonl(ttl
));
443 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
445 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
448 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
449 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
450 * The answer type will be RESOLVED_HOSTNAME.
452 * If <b>circ</b> is provided, and we have a cached answer, send the
453 * answer back along circ; otherwise, send the answer back along
454 * <b>conn</b>'s attached circuit.
457 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
459 char buf
[RELAY_PAYLOAD_SIZE
];
462 size_t namelen
= strlen(hostname
);
463 tor_assert(hostname
);
465 tor_assert(namelen
< 256);
466 ttl
= dns_clip_ttl(conn
->address_ttl
);
468 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
469 buf
[1] = (uint8_t)namelen
;
470 memcpy(buf
+2, hostname
, namelen
);
471 set_uint32(buf
+2+namelen
, htonl(ttl
));
472 buflen
= 2+namelen
+4;
474 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
475 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
476 // log_notice(LD_EXIT, "Sent");
479 /** Given a lower-case <b>address</b>, check to see whether it's a
480 * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
481 * parse it and place the address in <b>in</b> if present. Return 1 on success;
482 * 0 if the address is not in in-addr.arpa format, and -1 if the address is
485 parse_inaddr_arpa_address(const char *address
, struct in_addr
*in
)
487 char buf
[INET_NTOA_BUF_LEN
];
490 struct in_addr inaddr
;
492 cp
= strstr(address
, ".in-addr.arpa");
493 if (!cp
|| *(cp
+strlen(".in-addr.arpa")))
494 return 0; /* not an .in-addr.arpa address */
498 if (len
>= INET_NTOA_BUF_LEN
)
499 return -1; /* Too long. */
501 memcpy(buf
, address
, len
);
503 if (tor_inet_aton(buf
, &inaddr
) == 0)
504 return -1; /* malformed. */
508 /* reverse the bytes */
509 a
= (uint32_t) ( ((inaddr
.s_addr
& 0x000000fful
) << 24)
510 |((inaddr
.s_addr
& 0x0000ff00ul
) << 8)
511 |((inaddr
.s_addr
& 0x00ff0000ul
) >> 8)
512 |((inaddr
.s_addr
& 0xff000000ul
) >> 24));
515 memcpy(in
, &inaddr
, sizeof(inaddr
));
521 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
522 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
523 * If resolve failed, free exitconn and return -1.
525 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
526 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
527 * need to send back an END cell, since connection_exit_begin_conn will
530 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
533 * Else, if seen before and pending, add conn to the pending list,
536 * Else, if not seen before, add conn to pending list, hand to
537 * dns farm, and return 0.
539 * Exitconn's on_circuit field must be set, but exitconn should not
540 * yet be linked onto the n_streams/resolving_streams list of that circuit.
541 * On success, link the connection to n_streams if it's an exit connection.
542 * On "pending", link the connection to resolving streams. Otherwise,
543 * clear its on_circuit field.
546 dns_resolve(edge_connection_t
*exitconn
)
548 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
550 char *hostname
= NULL
;
551 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
553 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
556 /* We got an answer without a lookup -- either the answer was
557 * cached, or it was obvious (like an IP address). */
559 /* Send the answer back right now, and detach. */
561 send_resolved_hostname_cell(exitconn
, hostname
);
563 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
564 exitconn
->on_circuit
= NULL
;
566 /* Add to the n_streams list; the calling function will send back a
568 exitconn
->next_stream
= oncirc
->n_streams
;
569 oncirc
->n_streams
= exitconn
;
573 /* The request is pending: add the connection into the linked list of
574 * resolving_streams on this circuit. */
575 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
576 exitconn
->next_stream
= oncirc
->resolving_streams
;
577 oncirc
->resolving_streams
= exitconn
;
581 /* The request failed before it could start: cancel this connection,
582 * and stop everybody waiting for the same connection. */
584 send_resolved_cell(exitconn
,
585 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
588 exitconn
->on_circuit
= NULL
;
590 dns_cancel_pending_resolve(exitconn
->_base
.address
);
592 if (!exitconn
->_base
.marked_for_close
) {
593 connection_free(TO_CONN(exitconn
));
594 //XXX020 ... and we just leak exitconn otherwise? -RD
595 // If it's marked for close, it's on closeable_connection_lst in
596 // main.c. If it's on the closeable list, it will get freed from
598 // "<armadev> If that's true, there are other bugs around, where we
599 // don't check if it's marked, and will end up double-freeing."
600 // On the other hand, I don't know of any actual bugs here, so this
601 // shouldn't be holding up the rc. -RD
612 /** Helper function for dns_resolve: same functionality, but does not handle:
613 * - marking connections on error and clearing their on_circuit
614 * - linking connections to n_streams/resolving_streams,
615 * - sending resolved cells if we have an answer/error right away,
617 * Return -2 on a transient error. If it's a reverse resolve and it's
618 * successful, sets *<b>hostname_out</b> to a newly allocated string
619 * holding the cached reverse DNS value.
622 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
623 or_circuit_t
*oncirc
, char **hostname_out
)
625 cached_resolve_t
*resolve
;
626 cached_resolve_t search
;
627 pending_connection_t
*pending_connection
;
629 time_t now
= time(NULL
);
630 uint8_t is_reverse
= 0;
632 assert_connection_ok(TO_CONN(exitconn
), 0);
633 tor_assert(exitconn
->_base
.s
== -1);
637 /* first check if exitconn->_base.address is an IP. If so, we already
638 * know the answer. */
639 if (tor_inet_aton(exitconn
->_base
.address
, &in
) != 0) {
640 exitconn
->_base
.addr
= ntohl(in
.s_addr
);
641 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
644 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
645 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
646 "Rejecting invalid destination address %s",
647 escaped_safe_str(exitconn
->_base
.address
));
651 /* then take this opportunity to see if there are any expired
652 * resolves in the hash table. */
653 purge_expired_resolves(now
);
655 /* lower-case exitconn->_base.address, so it's in canonical form */
656 tor_strlower(exitconn
->_base
.address
);
658 /* Check whether this is a reverse lookup. If it's malformed, or it's a
659 * .in-addr.arpa address but this isn't a resolve request, kill the
662 if ((r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, NULL
)) != 0) {
666 if (!is_reverse
|| !is_resolve
) {
668 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
669 escaped_safe_str(exitconn
->_base
.address
));
670 else if (!is_resolve
)
672 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
674 escaped_safe_str(exitconn
->_base
.address
));
678 //log_notice(LD_EXIT, "Looks like an address %s",
679 //exitconn->_base.address);
682 /* now check the hash table to see if 'address' is already there. */
683 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
684 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
685 if (resolve
&& resolve
->expire
> now
) { /* already there */
686 switch (resolve
->state
) {
687 case CACHE_STATE_PENDING
:
688 /* add us to the pending list */
689 pending_connection
= tor_malloc_zero(
690 sizeof(pending_connection_t
));
691 pending_connection
->conn
= exitconn
;
692 pending_connection
->next
= resolve
->pending_connections
;
693 resolve
->pending_connections
= pending_connection
;
694 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
695 "resolve of %s", exitconn
->_base
.s
,
696 escaped_safe_str(exitconn
->_base
.address
));
698 case CACHE_STATE_CACHED_VALID
:
699 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
701 escaped_safe_str(resolve
->address
));
702 exitconn
->address_ttl
= resolve
->ttl
;
703 if (resolve
->is_reverse
) {
704 tor_assert(is_resolve
);
705 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
707 exitconn
->_base
.addr
= resolve
->result
.addr
;
710 case CACHE_STATE_CACHED_FAILED
:
711 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
713 escaped_safe_str(exitconn
->_base
.address
));
715 case CACHE_STATE_DONE
:
716 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
717 tor_fragile_assert();
721 tor_assert(!resolve
);
722 /* not there, need to add it */
723 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
724 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
725 resolve
->state
= CACHE_STATE_PENDING
;
726 resolve
->is_reverse
= is_reverse
;
727 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
729 /* add this connection to the pending list */
730 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
731 pending_connection
->conn
= exitconn
;
732 resolve
->pending_connections
= pending_connection
;
734 /* Add this resolve to the cache and priority queue. */
735 HT_INSERT(cache_map
, &cache_root
, resolve
);
736 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
738 log_debug(LD_EXIT
,"Launching %s.",
739 escaped_safe_str(exitconn
->_base
.address
));
742 return launch_resolve(exitconn
);
745 /** Log an error and abort if conn is waiting for a DNS resolve.
748 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
750 pending_connection_t
*pend
;
751 cached_resolve_t
**resolve
;
753 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
754 for (pend
= (*resolve
)->pending_connections
;
757 tor_assert(pend
->conn
!= conn
);
762 /** Log an error and abort if any connection waiting for a DNS resolve is
765 assert_all_pending_dns_resolves_ok(void)
767 pending_connection_t
*pend
;
768 cached_resolve_t
**resolve
;
770 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
771 for (pend
= (*resolve
)->pending_connections
;
774 assert_connection_ok(TO_CONN(pend
->conn
), 0);
775 tor_assert(pend
->conn
->_base
.s
== -1);
776 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
781 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
784 connection_dns_remove(edge_connection_t
*conn
)
786 pending_connection_t
*pend
, *victim
;
787 cached_resolve_t search
;
788 cached_resolve_t
*resolve
;
790 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
791 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
793 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
795 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
797 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
798 escaped_safe_str(conn
->_base
.address
));
802 tor_assert(resolve
->pending_connections
);
803 assert_connection_ok(TO_CONN(conn
),0);
805 pend
= resolve
->pending_connections
;
807 if (pend
->conn
== conn
) {
808 resolve
->pending_connections
= pend
->next
;
810 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
812 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
815 for ( ; pend
->next
; pend
= pend
->next
) {
816 if (pend
->next
->conn
== conn
) {
818 pend
->next
= victim
->next
;
821 "Connection (fd %d) no longer waiting for resolve of %s",
822 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
823 return; /* more are pending */
826 tor_assert(0); /* not reachable unless onlyconn not in pending list */
830 /** Mark all connections waiting for <b>address</b> for close. Then cancel
831 * the resolve for <b>address</b> itself, and remove any cached results for
832 * <b>address</b> from the cache.
835 dns_cancel_pending_resolve(const char *address
)
837 pending_connection_t
*pend
;
838 cached_resolve_t search
;
839 cached_resolve_t
*resolve
, *tmp
;
840 edge_connection_t
*pendconn
;
843 strlcpy(search
.address
, address
, sizeof(search
.address
));
845 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
849 if (resolve
->state
!= CACHE_STATE_PENDING
) {
850 /* We can get into this state if we never actually created the pending
851 * resolve, due to finding an earlier cached error or something. Just
853 if (resolve
->pending_connections
) {
855 "Address %s is not pending but has pending connections!",
856 escaped_safe_str(address
));
857 tor_fragile_assert();
862 if (!resolve
->pending_connections
) {
864 "Address %s is pending but has no pending connections!",
865 escaped_safe_str(address
));
866 tor_fragile_assert();
869 tor_assert(resolve
->pending_connections
);
871 /* mark all pending connections to fail */
873 "Failing all connections waiting on DNS resolve of %s",
874 escaped_safe_str(address
));
875 while (resolve
->pending_connections
) {
876 pend
= resolve
->pending_connections
;
877 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
878 pendconn
= pend
->conn
;
879 assert_connection_ok(TO_CONN(pendconn
), 0);
880 tor_assert(pendconn
->_base
.s
== -1);
881 if (!pendconn
->_base
.marked_for_close
) {
882 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
884 circ
= circuit_get_by_edge_conn(pendconn
);
886 circuit_detach_stream(circ
, pendconn
);
887 if (!pendconn
->_base
.marked_for_close
)
888 connection_free(TO_CONN(pendconn
));
889 resolve
->pending_connections
= pend
->next
;
893 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
894 if (tmp
!= resolve
) {
895 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
896 " the cache. Tried to purge %s (%p); instead got %s (%p).",
897 resolve
->address
, (void*)resolve
,
898 tmp
? tmp
->address
: "NULL", (void*)tmp
);
900 tor_assert(tmp
== resolve
);
902 resolve
->state
= CACHE_STATE_DONE
;
905 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
906 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
907 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
908 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
911 add_answer_to_cache(const char *address
, uint8_t is_reverse
, uint32_t addr
,
912 const char *hostname
, char outcome
, uint32_t ttl
)
914 cached_resolve_t
*resolve
;
915 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
918 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
919 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
920 // hostname?hostname:"NULL",(int)outcome);
922 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
923 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
924 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
925 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
926 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
927 resolve
->is_reverse
= is_reverse
;
929 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
930 tor_assert(hostname
);
931 resolve
->result
.hostname
= tor_strdup(hostname
);
933 tor_assert(! hostname
);
934 resolve
->result
.hostname
= NULL
;
937 tor_assert(!hostname
);
938 resolve
->result
.addr
= addr
;
941 assert_resolve_ok(resolve
);
942 HT_INSERT(cache_map
, &cache_root
, resolve
);
943 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
946 /** Return true iff <b>address</b> is one of the addresses we use to verify
947 * that well-known sites aren't being hijacked by our DNS servers. */
949 is_test_address(const char *address
)
951 or_options_t
*options
= get_options();
952 return options
->ServerDNSTestAddresses
&&
953 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
956 /** Called on the OR side when a DNS worker or the eventdns library tells us
957 * the outcome of a DNS resolve: tell all pending connections about the result
958 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
959 * string containing the address to look up; <b>addr</b> is an IPv4 address in
960 * host order; <b>outcome</b> is one of
961 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
964 dns_found_answer(const char *address
, uint8_t is_reverse
, uint32_t addr
,
965 const char *hostname
, char outcome
, uint32_t ttl
)
967 pending_connection_t
*pend
;
968 cached_resolve_t search
;
969 cached_resolve_t
*resolve
, *removed
;
970 edge_connection_t
*pendconn
;
975 strlcpy(search
.address
, address
, sizeof(search
.address
));
977 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
979 int is_test_addr
= is_test_address(address
);
981 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
982 escaped_safe_str(address
));
983 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
986 assert_resolve_ok(resolve
);
988 if (resolve
->state
!= CACHE_STATE_PENDING
) {
989 /* XXXX020 Maybe update addr? or check addr for consistency? Or let
990 * VALID replace FAILED? */
991 int is_test_addr
= is_test_address(address
);
994 "Resolved %s which was already resolved; ignoring",
995 escaped_safe_str(address
));
996 tor_assert(resolve
->pending_connections
== NULL
);
999 /* Removed this assertion: in fact, we'll sometimes get a double answer
1000 * to the same question. This can happen when we ask one worker to resolve
1001 * X.Y.Z., then we cancel the request, and then we ask another worker to
1003 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1005 while (resolve
->pending_connections
) {
1006 pend
= resolve
->pending_connections
;
1007 pendconn
= pend
->conn
; /* don't pass complex things to the
1008 connection_mark_for_close macro */
1009 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1010 pendconn
->_base
.addr
= addr
;
1011 pendconn
->address_ttl
= ttl
;
1013 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
1014 /* prevent double-remove. */
1015 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1016 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1017 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1018 /* This detach must happen after we send the end cell. */
1019 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1021 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
1022 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
1023 /* This detach must happen after we send the resolved cell. */
1024 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1026 connection_free(TO_CONN(pendconn
));
1028 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1029 tor_assert(!is_reverse
);
1030 /* prevent double-remove. */
1031 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1033 circ
= circuit_get_by_edge_conn(pend
->conn
);
1035 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1036 /* unlink pend->conn from resolving_streams, */
1037 circuit_detach_stream(circ
, pend
->conn
);
1038 /* and link it to n_streams */
1039 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1040 pend
->conn
->on_circuit
= circ
;
1041 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1043 connection_exit_connect(pend
->conn
);
1045 /* prevent double-remove. This isn't really an accurate state,
1046 * but it does the right thing. */
1047 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1049 send_resolved_hostname_cell(pendconn
, hostname
);
1051 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1052 circ
= circuit_get_by_edge_conn(pendconn
);
1054 circuit_detach_stream(circ
, pendconn
);
1055 connection_free(TO_CONN(pendconn
));
1058 resolve
->pending_connections
= pend
->next
;
1062 resolve
->state
= CACHE_STATE_DONE
;
1063 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1064 if (removed
!= resolve
) {
1065 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1066 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1067 resolve
->address
, (void*)resolve
,
1068 removed
? removed
->address
: "NULL", (void*)removed
);
1070 assert_resolve_ok(resolve
);
1073 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1077 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1078 * a transient failure. */
1080 evdns_err_is_transient(int err
)
1084 case DNS_ERR_SERVERFAILED
:
1085 case DNS_ERR_TRUNCATED
:
1086 case DNS_ERR_TIMEOUT
:
1093 /** Configure eventdns nameservers if force is true, or if the configuration
1094 * has changed since the last time we called this function. On Unix, this
1095 * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
1096 * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
1097 * Return 0 on success or -1 on failure. */
1099 configure_nameservers(int force
)
1101 or_options_t
*options
;
1102 const char *conf_fname
;
1105 options
= get_options();
1106 conf_fname
= options
->ServerDNSResolvConfFile
;
1109 conf_fname
= "/etc/resolv.conf";
1112 evdns_set_log_fn(evdns_log_cb
);
1114 if (stat(conf_fname
, &st
)) {
1115 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1116 conf_fname
, strerror(errno
));
1117 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1119 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1120 && st
.st_mtime
== resolv_conf_mtime
) {
1121 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1124 if (nameservers_configured
) {
1125 evdns_search_clear();
1126 evdns_clear_nameservers_and_suspend();
1128 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1129 if ((r
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, conf_fname
))) {
1130 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1131 conf_fname
, conf_fname
, r
);
1132 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1134 if (evdns_count_nameservers() == 0) {
1135 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1136 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1138 tor_free(resolv_conf_fname
);
1139 resolv_conf_fname
= tor_strdup(conf_fname
);
1140 resolv_conf_mtime
= st
.st_mtime
;
1141 if (nameservers_configured
)
1146 if (nameservers_configured
) {
1147 evdns_search_clear();
1148 evdns_clear_nameservers_and_suspend();
1150 if (evdns_config_windows_nameservers()) {
1151 log_warn(LD_EXIT
,"Could not config nameservers.");
1152 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1154 if (evdns_count_nameservers() == 0) {
1155 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1156 "your Windows configuration. Perhaps you should list a "
1157 "ServerDNSResolvConfFile file in your torrc?");
1158 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1160 if (nameservers_configured
)
1162 tor_free(resolv_conf_fname
);
1163 resolv_conf_mtime
= 0;
1167 if (evdns_count_nameservers() == 1) {
1168 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL
);
1169 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL
);
1171 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL
);
1172 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL
);
1175 dns_servers_relaunch_checks();
1177 nameservers_configured
= 1;
1181 /** For eventdns: Called when we get an answer for a request we launched.
1182 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1185 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1188 char *string_address
= arg
;
1189 uint8_t is_reverse
= 0;
1190 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1192 const char *hostname
= NULL
;
1193 int was_wildcarded
= 0;
1195 if (result
== DNS_ERR_NONE
) {
1196 if (type
== DNS_IPv4_A
&& count
) {
1197 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1199 char *escaped_address
;
1200 uint32_t *addrs
= addresses
;
1201 in
.s_addr
= addrs
[0];
1202 addr
= ntohl(addrs
[0]);
1203 status
= DNS_RESOLVE_SUCCEEDED
;
1204 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1205 escaped_address
= esc_for_log(string_address
);
1207 if (answer_is_wildcarded(answer_buf
)) {
1208 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1209 "address %s; treating as a failure.",
1210 safe_str(escaped_address
),
1211 escaped_safe_str(answer_buf
));
1214 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1216 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1217 safe_str(escaped_address
),
1218 escaped_safe_str(answer_buf
));
1220 tor_free(escaped_address
);
1221 } else if (type
== DNS_PTR
&& count
) {
1222 char *escaped_address
;
1224 hostname
= ((char**)addresses
)[0];
1225 status
= DNS_RESOLVE_SUCCEEDED
;
1226 escaped_address
= esc_for_log(string_address
);
1227 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1228 safe_str(escaped_address
),
1229 escaped_safe_str(hostname
));
1230 tor_free(escaped_address
);
1232 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1233 escaped_safe_str(string_address
));
1235 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1236 escaped_safe_str(string_address
));
1239 if (evdns_err_is_transient(result
))
1240 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1242 if (was_wildcarded
) {
1243 if (is_test_address(string_address
)) {
1244 /* Ick. We're getting redirected on known-good addresses. Our DNS
1245 * server must really hate us. */
1246 add_wildcarded_test_address(string_address
);
1249 if (result
!= DNS_ERR_SHUTDOWN
)
1250 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1251 tor_free(string_address
);
1254 /** For eventdns: start resolving as necessary to find the target for
1255 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1256 * 0 on "resolve launched." */
1258 launch_resolve(edge_connection_t
*exitconn
)
1260 char *addr
= tor_strdup(exitconn
->_base
.address
);
1263 int options
= get_options()->ServerDNSSearchDomains
? 0
1264 : DNS_QUERY_NO_SEARCH
;
1265 /* What? Nameservers not configured? Sounds like a bug. */
1266 if (!nameservers_configured
) {
1267 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1268 "launched. Configuring.");
1269 if (configure_nameservers(1) < 0)
1273 r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, &in
);
1275 log_info(LD_EXIT
, "Launching eventdns request for %s",
1276 escaped_safe_str(exitconn
->_base
.address
));
1277 r
= evdns_resolve_ipv4(exitconn
->_base
.address
, options
,
1278 evdns_callback
, addr
);
1279 } else if (r
== 1) {
1280 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1281 escaped_safe_str(exitconn
->_base
.address
));
1282 r
= evdns_resolve_reverse(&in
, DNS_QUERY_NO_SEARCH
,
1283 evdns_callback
, addr
);
1284 } else if (r
== -1) {
1285 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1289 log_warn(LD_EXIT
, "eventdns rejected address %s: error %d.",
1290 escaped_safe_str(addr
), r
);
1291 r
= evdns_err_is_transient(r
) ? -2 : -1;
1292 tor_free(addr
); /* There is no evdns request in progress; stop
1293 * addr from getting leaked. */
1298 /** How many requests for bogus addresses have we launched so far? */
1299 static int n_wildcard_requests
= 0;
1301 /** Map from dotted-quad IP address in response to an int holding how many
1302 * times we've seen it for a randomly generated (hopefully bogus) address. It
1303 * would be easier to use definitely-invalid addresses (as specified by
1304 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1305 static strmap_t
*dns_wildcard_response_count
= NULL
;
1307 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1308 * nameserver wants to return in response to requests for nonexistent domains.
1310 static smartlist_t
*dns_wildcard_list
= NULL
;
1311 /** True iff we've logged about a single address getting wildcarded.
1312 * Subsequent warnings will be less severe. */
1313 static int dns_wildcard_one_notice_given
= 0;
1314 /** True iff we've warned that our DNS server is wildcarding too many failures.
1316 static int dns_wildcard_notice_given
= 0;
1318 /** List of supposedly good addresses that are getting wildcarded to the
1319 * same addresses as nonexistent addresses. */
1320 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1321 /** True iff we've warned about a test address getting wildcarded */
1322 static int dns_wildcarded_test_address_notice_given
= 0;
1323 /** True iff all addresses seem to be getting wildcarded. */
1324 static int dns_is_completely_invalid
= 0;
1326 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1327 * a hopefully bogus address. */
1329 wildcard_increment_answer(const char *id
)
1332 if (!dns_wildcard_response_count
)
1333 dns_wildcard_response_count
= strmap_new();
1335 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1337 ip
= tor_malloc_zero(sizeof(int));
1338 strmap_set(dns_wildcard_response_count
, id
, ip
);
1342 if (*ip
> 5 && n_wildcard_requests
> 10) {
1343 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1344 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1345 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1346 "Your DNS provider has given \"%s\" as an answer for %d different "
1347 "invalid addresses. Apparently they are hijacking DNS failures. "
1348 "I'll try to correct for this by treating future occurrences of "
1349 "\"%s\" as 'not found'.", id
, *ip
, id
);
1350 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1352 if (!dns_wildcard_notice_given
)
1353 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1354 dns_wildcard_notice_given
= 1;
1358 /** Note that a single test address (one believed to be good) seems to be
1359 * getting redirected to the same IP as failures are. */
1361 add_wildcarded_test_address(const char *address
)
1363 int n
, n_test_addrs
;
1364 if (!dns_wildcarded_test_address_list
)
1365 dns_wildcarded_test_address_list
= smartlist_create();
1367 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1370 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1371 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1373 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1374 n
= smartlist_len(dns_wildcarded_test_address_list
);
1375 if (n
> n_test_addrs
/2) {
1376 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1377 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1378 "address. It has done this with %d test addresses so far. I'm "
1379 "going to stop being an exit node for now, since our DNS seems so "
1380 "broken.", address
, n
);
1381 if (!dns_is_completely_invalid
) {
1382 dns_is_completely_invalid
= 1;
1383 mark_my_descriptor_dirty();
1385 if (!dns_wildcarded_test_address_notice_given
)
1386 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1387 dns_wildcarded_test_address_notice_given
= 1;
1391 /** Callback function when we get an answer (possibly failing) for a request
1392 * for a (hopefully) nonexistent domain. */
1394 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1395 void *addresses
, void *arg
)
1398 ++n_wildcard_requests
;
1399 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1400 uint32_t *addrs
= addresses
;
1402 char *string_address
= arg
;
1403 for (i
= 0; i
< count
; ++i
) {
1404 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1406 in
.s_addr
= addrs
[i
];
1407 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1408 wildcard_increment_answer(answer_buf
);
1410 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1411 "Your DNS provider gave an answer for \"%s\", which "
1412 "is not supposed to exist. Apparently they are hijacking "
1413 "DNS failures. Trying to correct for this. We've noticed %d possibly "
1414 "bad addresses so far.",
1415 string_address
, strmap_size(dns_wildcard_response_count
));
1416 dns_wildcard_one_notice_given
= 1;
1421 /** Launch a single request for a nonexistent hostname consisting of between
1422 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1425 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1430 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1431 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1432 "domains with request for bogus hostname \"%s\"", addr
);
1434 r
= evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1436 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1437 /* This "addr" is an argument to the callback*/ addr
);
1439 /* There is no evdns request in progress; stop addr from getting leaked */
1444 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1445 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1447 launch_test_addresses(int fd
, short event
, void *args
)
1449 or_options_t
*options
= get_options();
1454 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1455 "hijack *everything*.");
1456 /* This situation is worse than the failure-hijacking situation. When this
1457 * happens, we're no good for DNS requests at all, and we shouldn't really
1458 * be an exit server.*/
1459 if (!options
->ServerDNSTestAddresses
)
1461 SMARTLIST_FOREACH(options
->ServerDNSTestAddresses
, const char *, address
,
1463 int r
= evdns_resolve_ipv4(address
, DNS_QUERY_NO_SEARCH
, evdns_callback
,
1464 tor_strdup(address
));
1466 log_info(LD_EXIT
, "eventdns rejected test address %s: error %d",
1467 escaped_safe_str(address
), r
);
1471 #define N_WILDCARD_CHECKS 2
1473 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1474 * hostnames, and see if we can catch our nameserver trying to hijack them and
1475 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1476 * buy these lovely encyclopedias" page. */
1478 dns_launch_wildcard_checks(void)
1481 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1482 "to hijack DNS failures.");
1483 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1484 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1485 * to 'comply' with rfc2606, refrain from giving A records for these.
1486 * This is the standards-compliance equivalent of making sure that your
1487 * crackhouse's elevator inspection certificate is up to date.
1489 launch_wildcard_check(2, 16, ".invalid");
1490 launch_wildcard_check(2, 16, ".test");
1492 /* These will break specs if there are ever any number of
1493 * 8+-character top-level domains. */
1494 launch_wildcard_check(8, 16, "");
1496 /* Try some random .com/org/net domains. This will work fine so long as
1497 * not too many resolve to the same place. */
1498 launch_wildcard_check(8, 16, ".com");
1499 launch_wildcard_check(8, 16, ".org");
1500 launch_wildcard_check(8, 16, ".net");
1504 /** If appropriate, start testing whether our DNS servers tend to lie to
1507 dns_launch_correctness_checks(void)
1509 static struct event launch_event
;
1510 struct timeval timeout
;
1511 if (!get_options()->ServerDNSDetectHijacking
)
1513 dns_launch_wildcard_checks();
1515 /* Wait a while before launching requests for test addresses, so we can
1516 * get the results from checking for wildcarding. */
1517 evtimer_set(&launch_event
, launch_test_addresses
, NULL
);
1518 timeout
.tv_sec
= 30;
1519 timeout
.tv_usec
= 0;
1520 if (evtimer_add(&launch_event
, &timeout
)<0) {
1521 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
1525 /** Return true iff our DNS servers lie to us too much to be trustd. */
1527 dns_seems_to_be_broken(void)
1529 return dns_is_completely_invalid
;
1532 /** Forget what we've previously learned about our DNS servers' correctness. */
1534 dns_reset_correctness_checks(void)
1536 if (dns_wildcard_response_count
) {
1537 strmap_free(dns_wildcard_response_count
, _tor_free
);
1538 dns_wildcard_response_count
= NULL
;
1540 n_wildcard_requests
= 0;
1542 if (dns_wildcard_list
) {
1543 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1544 smartlist_clear(dns_wildcard_list
);
1546 if (dns_wildcarded_test_address_list
) {
1547 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1549 smartlist_clear(dns_wildcarded_test_address_list
);
1551 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1552 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1555 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1556 * returned in response to requests for nonexistent hostnames. */
1558 answer_is_wildcarded(const char *ip
)
1560 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1563 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1565 assert_resolve_ok(cached_resolve_t
*resolve
)
1567 tor_assert(resolve
);
1568 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1569 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1570 tor_assert(tor_strisnonupper(resolve
->address
));
1571 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1572 tor_assert(!resolve
->pending_connections
);
1574 if (resolve
->state
== CACHE_STATE_PENDING
||
1575 resolve
->state
== CACHE_STATE_DONE
) {
1576 tor_assert(!resolve
->ttl
);
1577 if (resolve
->is_reverse
)
1578 tor_assert(!resolve
->result
.hostname
);
1580 tor_assert(!resolve
->result
.addr
);
1584 #ifdef DEBUG_DNS_CACHE
1585 /** Exit with an assertion if the DNS cache is corrupt. */
1587 _assert_cache_ok(void)
1589 cached_resolve_t
**resolve
;
1590 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1592 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1593 tor_assert(!bad_rep
);
1596 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1597 assert_resolve_ok(*resolve
);
1598 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1600 if (!cached_resolve_pqueue
)
1603 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1604 _compare_cached_resolves_by_expiry
);
1606 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1608 if (res
->state
== CACHE_STATE_DONE
) {
1609 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1610 tor_assert(!found
|| found
!= res
);
1612 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);