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 return a
->expire
- b
->expire
;
274 /** Priority queue of cached_resolve_t objects to let us know when they
276 static smartlist_t
*cached_resolve_pqueue
= NULL
;
278 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
281 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
283 tor_assert(resolve
&& resolve
->expire
== 0);
284 if (!cached_resolve_pqueue
)
285 cached_resolve_pqueue
= smartlist_create();
286 resolve
->expire
= expires
;
287 smartlist_pqueue_add(cached_resolve_pqueue
,
288 _compare_cached_resolves_by_expiry
,
292 /** Free all storage held in the DNS cache and related structures. */
296 cached_resolve_t
**ptr
, **next
, *item
;
298 if (cached_resolve_pqueue
) {
299 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
301 if (res
->state
== CACHE_STATE_DONE
)
302 _free_cached_resolve(res
);
305 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
307 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
308 _free_cached_resolve(item
);
310 HT_CLEAR(cache_map
, &cache_root
);
311 if (cached_resolve_pqueue
)
312 smartlist_free(cached_resolve_pqueue
);
313 cached_resolve_pqueue
= NULL
;
314 tor_free(resolv_conf_fname
);
317 /** Remove every cached_resolve whose <b>expire</b> time is before or
318 * equal to <b>now</b> from the cache. */
320 purge_expired_resolves(time_t now
)
322 cached_resolve_t
*resolve
, *removed
;
323 pending_connection_t
*pend
;
324 edge_connection_t
*pendconn
;
327 if (!cached_resolve_pqueue
)
330 while (smartlist_len(cached_resolve_pqueue
)) {
331 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
332 if (resolve
->expire
> now
)
334 smartlist_pqueue_pop(cached_resolve_pqueue
,
335 _compare_cached_resolves_by_expiry
);
337 if (resolve
->state
== CACHE_STATE_PENDING
) {
339 "Expiring a dns resolve %s that's still pending. Forgot to "
340 "cull it? DNS resolve didn't tell us about the timeout?",
341 escaped_safe_str(resolve
->address
));
342 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
343 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
345 "Forgetting old cached resolve (address %s, expires %lu)",
346 escaped_safe_str(resolve
->address
),
347 (unsigned long)resolve
->expire
);
348 tor_assert(!resolve
->pending_connections
);
350 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
351 tor_assert(!resolve
->pending_connections
);
354 if (resolve
->pending_connections
) {
356 "Closing pending connections on timed-out DNS resolve!");
357 tor_fragile_assert();
358 while (resolve
->pending_connections
) {
359 pend
= resolve
->pending_connections
;
360 resolve
->pending_connections
= pend
->next
;
361 /* Connections should only be pending if they have no socket. */
362 tor_assert(pend
->conn
->_base
.s
== -1);
363 pendconn
= pend
->conn
;
364 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
365 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
366 connection_free(TO_CONN(pendconn
));
371 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
372 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
373 resolve
->state
== CACHE_STATE_PENDING
) {
374 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
375 if (removed
!= resolve
) {
376 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
377 " the cache. Tried to purge %s (%p); instead got %s (%p).",
378 resolve
->address
, (void*)resolve
,
379 removed
? removed
->address
: "NULL", (void*)remove
);
381 tor_assert(removed
== resolve
);
383 /* This should be in state DONE. Make sure it's not in the cache. */
384 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
385 tor_assert(tmp
!= resolve
);
387 if (resolve
->is_reverse
)
388 tor_free(resolve
->result
.hostname
);
389 resolve
->magic
= 0xF0BBF0BB;
396 /** Send a response to the RESOLVE request of a connection.
397 * <b>answer_type</b> must be one of
398 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
400 * If <b>circ</b> is provided, and we have a cached answer, send the
401 * answer back along circ; otherwise, send the answer back along
402 * <b>conn</b>'s attached circuit.
405 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
407 char buf
[RELAY_PAYLOAD_SIZE
];
411 buf
[0] = answer_type
;
412 ttl
= dns_clip_ttl(conn
->address_ttl
);
416 case RESOLVED_TYPE_IPV4
:
418 set_uint32(buf
+2, htonl(conn
->_base
.addr
));
419 set_uint32(buf
+6, htonl(ttl
));
422 case RESOLVED_TYPE_ERROR_TRANSIENT
:
423 case RESOLVED_TYPE_ERROR
:
425 const char *errmsg
= "Error resolving hostname";
426 int msglen
= strlen(errmsg
);
429 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
430 set_uint32(buf
+2+msglen
, htonl(ttl
));
438 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
440 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
443 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
444 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
445 * The answer type will be RESOLVED_HOSTNAME.
447 * If <b>circ</b> is provided, and we have a cached answer, send the
448 * answer back along circ; otherwise, send the answer back along
449 * <b>conn</b>'s attached circuit.
452 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
454 char buf
[RELAY_PAYLOAD_SIZE
];
457 size_t namelen
= strlen(hostname
);
458 tor_assert(hostname
);
460 tor_assert(namelen
< 256);
461 ttl
= dns_clip_ttl(conn
->address_ttl
);
463 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
464 buf
[1] = (uint8_t)namelen
;
465 memcpy(buf
+2, hostname
, namelen
);
466 set_uint32(buf
+2+namelen
, htonl(ttl
));
467 buflen
= 2+namelen
+4;
469 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
470 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
471 // log_notice(LD_EXIT, "Sent");
474 /** Given a lower-case <b>address</b>, check to see whether it's a
475 * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
476 * parse it and place the address in <b>in</b> if present. Return 1 on success;
477 * 0 if the address is not in in-addr.arpa format, and -1 if the address is
480 parse_inaddr_arpa_address(const char *address
, struct in_addr
*in
)
482 char buf
[INET_NTOA_BUF_LEN
];
485 struct in_addr inaddr
;
487 cp
= strstr(address
, ".in-addr.arpa");
488 if (!cp
|| *(cp
+strlen(".in-addr.arpa")))
489 return 0; /* not an .in-addr.arpa address */
493 if (len
>= INET_NTOA_BUF_LEN
)
494 return -1; /* Too long. */
496 memcpy(buf
, address
, len
);
498 if (tor_inet_aton(buf
, &inaddr
) == 0)
499 return -1; /* malformed. */
503 /* reverse the bytes */
504 a
= ( ((inaddr
.s_addr
& 0x000000fful
) << 24)
505 |((inaddr
.s_addr
& 0x0000ff00ul
) << 8)
506 |((inaddr
.s_addr
& 0x00ff0000ul
) >> 8)
507 |((inaddr
.s_addr
& 0xff000000ul
) >> 24));
510 memcpy(in
, &inaddr
, sizeof(inaddr
));
516 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
517 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
518 * If resolve failed, free exitconn and return -1.
520 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
521 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
522 * need to send back an END cell, since connection_exit_begin_conn will
525 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
528 * Else, if seen before and pending, add conn to the pending list,
531 * Else, if not seen before, add conn to pending list, hand to
532 * dns farm, and return 0.
534 * Exitconn's on_circuit field must be set, but exitconn should not
535 * yet be linked onto the n_streams/resolving_streams list of that circuit.
536 * On success, link the connection to n_streams if it's an exit connection.
537 * On "pending", link the connection to resolving streams. Otherwise,
538 * clear its on_circuit field.
541 dns_resolve(edge_connection_t
*exitconn
)
543 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
545 char *hostname
= NULL
;
546 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
548 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
551 /* We got an answer without a lookup -- either the answer was
552 * cached, or it was obvious (like an IP address). */
554 /* Send the answer back right now, and detach. */
556 send_resolved_hostname_cell(exitconn
, hostname
);
558 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
559 exitconn
->on_circuit
= NULL
;
561 /* Add to the n_streams list; the calling function will send back a
563 exitconn
->next_stream
= oncirc
->n_streams
;
564 oncirc
->n_streams
= exitconn
;
568 /* The request is pending: add the connection into the linked list of
569 * resolving_streams on this circuit. */
570 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
571 exitconn
->next_stream
= oncirc
->resolving_streams
;
572 oncirc
->resolving_streams
= exitconn
;
576 /* The request failed before it could start: cancel this connection,
577 * and stop everybody waiting for the same connection. */
579 send_resolved_cell(exitconn
,
580 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
583 exitconn
->on_circuit
= NULL
;
585 dns_cancel_pending_resolve(exitconn
->_base
.address
);
587 if (!exitconn
->_base
.marked_for_close
) {
588 connection_free(TO_CONN(exitconn
));
589 //XXX020rc ... and we just leak exitconn otherwise? -RD
590 // If it's marked for close, it's on closeable_connection_lst in
591 // main.c. If it's on the closeable list, it will get freed from
593 // "<armadev> If that's true, there are other bugs around, where we
594 // don't check if it's marked, and will end up double-freeing."
595 // On the other hand, I don't know of any actual bugs here, so this
596 // shouldn't be holding up the rc. -RD
607 /** Helper function for dns_resolve: same functionality, but does not handle:
608 * - marking connections on error and clearing their on_circuit
609 * - linking connections to n_streams/resolving_streams,
610 * - sending resolved cells if we have an answer/error right away,
612 * Return -2 on a transient error. If it's a reverse resolve and it's
613 * successful, sets *<b>hostname_out</b> to a newly allocated string
614 * holding the cached reverse DNS value.
617 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
618 or_circuit_t
*oncirc
, char **hostname_out
)
620 cached_resolve_t
*resolve
;
621 cached_resolve_t search
;
622 pending_connection_t
*pending_connection
;
624 time_t now
= time(NULL
);
625 uint8_t is_reverse
= 0;
627 assert_connection_ok(TO_CONN(exitconn
), 0);
628 tor_assert(exitconn
->_base
.s
== -1);
632 /* first check if exitconn->_base.address is an IP. If so, we already
633 * know the answer. */
634 if (tor_inet_aton(exitconn
->_base
.address
, &in
) != 0) {
635 exitconn
->_base
.addr
= ntohl(in
.s_addr
);
636 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
639 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
640 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
641 "Rejecting invalid destination address %s",
642 escaped_safe_str(exitconn
->_base
.address
));
646 /* then take this opportunity to see if there are any expired
647 * resolves in the hash table. */
648 purge_expired_resolves(now
);
650 /* lower-case exitconn->_base.address, so it's in canonical form */
651 tor_strlower(exitconn
->_base
.address
);
653 /* Check whether this is a reverse lookup. If it's malformed, or it's a
654 * .in-addr.arpa address but this isn't a resolve request, kill the
657 if ((r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, NULL
)) != 0) {
661 if (!is_reverse
|| !is_resolve
) {
663 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
664 escaped_safe_str(exitconn
->_base
.address
));
665 else if (!is_resolve
)
667 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
669 escaped_safe_str(exitconn
->_base
.address
));
673 //log_notice(LD_EXIT, "Looks like an address %s",
674 //exitconn->_base.address);
677 /* now check the hash table to see if 'address' is already there. */
678 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
679 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
680 if (resolve
&& resolve
->expire
> now
) { /* already there */
681 switch (resolve
->state
) {
682 case CACHE_STATE_PENDING
:
683 /* add us to the pending list */
684 pending_connection
= tor_malloc_zero(
685 sizeof(pending_connection_t
));
686 pending_connection
->conn
= exitconn
;
687 pending_connection
->next
= resolve
->pending_connections
;
688 resolve
->pending_connections
= pending_connection
;
689 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
690 "resolve of %s", exitconn
->_base
.s
,
691 escaped_safe_str(exitconn
->_base
.address
));
693 case CACHE_STATE_CACHED_VALID
:
694 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
696 escaped_safe_str(resolve
->address
));
697 exitconn
->address_ttl
= resolve
->ttl
;
698 if (resolve
->is_reverse
) {
699 tor_assert(is_resolve
);
700 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
702 exitconn
->_base
.addr
= resolve
->result
.addr
;
705 case CACHE_STATE_CACHED_FAILED
:
706 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
708 escaped_safe_str(exitconn
->_base
.address
));
710 case CACHE_STATE_DONE
:
711 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
712 tor_fragile_assert();
716 tor_assert(!resolve
);
717 /* not there, need to add it */
718 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
719 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
720 resolve
->state
= CACHE_STATE_PENDING
;
721 resolve
->is_reverse
= is_reverse
;
722 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
724 /* add this connection to the pending list */
725 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
726 pending_connection
->conn
= exitconn
;
727 resolve
->pending_connections
= pending_connection
;
729 /* Add this resolve to the cache and priority queue. */
730 HT_INSERT(cache_map
, &cache_root
, resolve
);
731 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
733 log_debug(LD_EXIT
,"Launching %s.",
734 escaped_safe_str(exitconn
->_base
.address
));
737 return launch_resolve(exitconn
);
740 /** Log an error and abort if conn is waiting for a DNS resolve.
743 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
745 pending_connection_t
*pend
;
746 cached_resolve_t
**resolve
;
748 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
749 for (pend
= (*resolve
)->pending_connections
;
752 tor_assert(pend
->conn
!= conn
);
757 /** Log an error and abort if any connection waiting for a DNS resolve is
760 assert_all_pending_dns_resolves_ok(void)
762 pending_connection_t
*pend
;
763 cached_resolve_t
**resolve
;
765 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
766 for (pend
= (*resolve
)->pending_connections
;
769 assert_connection_ok(TO_CONN(pend
->conn
), 0);
770 tor_assert(pend
->conn
->_base
.s
== -1);
771 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
776 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
779 connection_dns_remove(edge_connection_t
*conn
)
781 pending_connection_t
*pend
, *victim
;
782 cached_resolve_t search
;
783 cached_resolve_t
*resolve
;
785 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
786 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
788 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
790 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
792 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
793 escaped_safe_str(conn
->_base
.address
));
797 tor_assert(resolve
->pending_connections
);
798 assert_connection_ok(TO_CONN(conn
),0);
800 pend
= resolve
->pending_connections
;
802 if (pend
->conn
== conn
) {
803 resolve
->pending_connections
= pend
->next
;
805 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
807 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
810 for ( ; pend
->next
; pend
= pend
->next
) {
811 if (pend
->next
->conn
== conn
) {
813 pend
->next
= victim
->next
;
816 "Connection (fd %d) no longer waiting for resolve of %s",
817 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
818 return; /* more are pending */
821 tor_assert(0); /* not reachable unless onlyconn not in pending list */
825 /** Mark all connections waiting for <b>address</b> for close. Then cancel
826 * the resolve for <b>address</b> itself, and remove any cached results for
827 * <b>address</b> from the cache.
830 dns_cancel_pending_resolve(const char *address
)
832 pending_connection_t
*pend
;
833 cached_resolve_t search
;
834 cached_resolve_t
*resolve
, *tmp
;
835 edge_connection_t
*pendconn
;
838 strlcpy(search
.address
, address
, sizeof(search
.address
));
840 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
844 if (resolve
->state
!= CACHE_STATE_PENDING
) {
845 /* We can get into this state if we never actually created the pending
846 * resolve, due to finding an earlier cached error or something. Just
848 if (resolve
->pending_connections
) {
850 "Address %s is not pending but has pending connections!",
851 escaped_safe_str(address
));
852 tor_fragile_assert();
857 if (!resolve
->pending_connections
) {
859 "Address %s is pending but has no pending connections!",
860 escaped_safe_str(address
));
861 tor_fragile_assert();
864 tor_assert(resolve
->pending_connections
);
866 /* mark all pending connections to fail */
868 "Failing all connections waiting on DNS resolve of %s",
869 escaped_safe_str(address
));
870 while (resolve
->pending_connections
) {
871 pend
= resolve
->pending_connections
;
872 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
873 pendconn
= pend
->conn
;
874 assert_connection_ok(TO_CONN(pendconn
), 0);
875 tor_assert(pendconn
->_base
.s
== -1);
876 if (!pendconn
->_base
.marked_for_close
) {
877 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
879 circ
= circuit_get_by_edge_conn(pendconn
);
881 circuit_detach_stream(circ
, pendconn
);
882 if (!pendconn
->_base
.marked_for_close
)
883 connection_free(TO_CONN(pendconn
));
884 resolve
->pending_connections
= pend
->next
;
888 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
889 if (tmp
!= resolve
) {
890 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
891 " the cache. Tried to purge %s (%p); instead got %s (%p).",
892 resolve
->address
, (void*)resolve
,
893 tmp
? tmp
->address
: "NULL", (void*)tmp
);
895 tor_assert(tmp
== resolve
);
897 resolve
->state
= CACHE_STATE_DONE
;
900 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
901 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
902 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
903 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
906 add_answer_to_cache(const char *address
, uint8_t is_reverse
, uint32_t addr
,
907 const char *hostname
, char outcome
, uint32_t ttl
)
909 cached_resolve_t
*resolve
;
910 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
913 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
914 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
915 // hostname?hostname:"NULL",(int)outcome);
917 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
918 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
919 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
920 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
921 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
922 resolve
->is_reverse
= is_reverse
;
924 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
925 tor_assert(hostname
);
926 resolve
->result
.hostname
= tor_strdup(hostname
);
928 tor_assert(! hostname
);
929 resolve
->result
.hostname
= NULL
;
932 tor_assert(!hostname
);
933 resolve
->result
.addr
= addr
;
936 assert_resolve_ok(resolve
);
937 HT_INSERT(cache_map
, &cache_root
, resolve
);
938 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
941 /** Return true iff <b>address</b> is one of the addresses we use to verify
942 * that well-known sites aren't being hijacked by our DNS servers. */
944 is_test_address(const char *address
)
946 or_options_t
*options
= get_options();
947 return options
->ServerDNSTestAddresses
&&
948 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
951 /** Called on the OR side when a DNS worker or the eventdns library tells us
952 * the outcome of a DNS resolve: tell all pending connections about the result
953 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
954 * string containing the address to look up; <b>addr</b> is an IPv4 address in
955 * host order; <b>outcome</b> is one of
956 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
959 dns_found_answer(const char *address
, uint8_t is_reverse
, uint32_t addr
,
960 const char *hostname
, char outcome
, uint32_t ttl
)
962 pending_connection_t
*pend
;
963 cached_resolve_t search
;
964 cached_resolve_t
*resolve
, *removed
;
965 edge_connection_t
*pendconn
;
970 strlcpy(search
.address
, address
, sizeof(search
.address
));
972 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
974 int is_test_addr
= is_test_address(address
);
976 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
977 escaped_safe_str(address
));
978 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
981 assert_resolve_ok(resolve
);
983 if (resolve
->state
!= CACHE_STATE_PENDING
) {
984 /* XXXX020 Maybe update addr? or check addr for consistency? Or let
985 * VALID replace FAILED? */
986 int is_test_addr
= is_test_address(address
);
989 "Resolved %s which was already resolved; ignoring",
990 escaped_safe_str(address
));
991 tor_assert(resolve
->pending_connections
== NULL
);
994 /* Removed this assertion: in fact, we'll sometimes get a double answer
995 * to the same question. This can happen when we ask one worker to resolve
996 * X.Y.Z., then we cancel the request, and then we ask another worker to
998 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1000 while (resolve
->pending_connections
) {
1001 pend
= resolve
->pending_connections
;
1002 pendconn
= pend
->conn
; /* don't pass complex things to the
1003 connection_mark_for_close macro */
1004 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1005 pendconn
->_base
.addr
= addr
;
1006 pendconn
->address_ttl
= ttl
;
1008 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
1009 /* prevent double-remove. */
1010 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1011 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1012 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1013 /* This detach must happen after we send the end cell. */
1014 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1016 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
1017 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
1018 /* This detach must happen after we send the resolved cell. */
1019 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1021 connection_free(TO_CONN(pendconn
));
1023 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1024 tor_assert(!is_reverse
);
1025 /* prevent double-remove. */
1026 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1028 circ
= circuit_get_by_edge_conn(pend
->conn
);
1030 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1031 /* unlink pend->conn from resolving_streams, */
1032 circuit_detach_stream(circ
, pend
->conn
);
1033 /* and link it to n_streams */
1034 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1035 pend
->conn
->on_circuit
= circ
;
1036 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1038 connection_exit_connect(pend
->conn
);
1040 /* prevent double-remove. This isn't really an accurate state,
1041 * but it does the right thing. */
1042 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1044 send_resolved_hostname_cell(pendconn
, hostname
);
1046 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1047 circ
= circuit_get_by_edge_conn(pendconn
);
1049 circuit_detach_stream(circ
, pendconn
);
1050 connection_free(TO_CONN(pendconn
));
1053 resolve
->pending_connections
= pend
->next
;
1057 resolve
->state
= CACHE_STATE_DONE
;
1058 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1059 if (removed
!= resolve
) {
1060 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1061 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1062 resolve
->address
, (void*)resolve
,
1063 removed
? removed
->address
: "NULL", (void*)removed
);
1065 assert_resolve_ok(resolve
);
1068 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1072 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1073 * a transient failure. */
1075 evdns_err_is_transient(int err
)
1079 case DNS_ERR_SERVERFAILED
:
1080 case DNS_ERR_TRUNCATED
:
1081 case DNS_ERR_TIMEOUT
:
1088 /** Configure eventdns nameservers if force is true, or if the configuration
1089 * has changed since the last time we called this function. On Unix, this
1090 * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
1091 * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
1092 * Return 0 on success or -1 on failure. */
1094 configure_nameservers(int force
)
1096 or_options_t
*options
;
1097 const char *conf_fname
;
1100 options
= get_options();
1101 conf_fname
= options
->ServerDNSResolvConfFile
;
1104 conf_fname
= "/etc/resolv.conf";
1107 evdns_set_log_fn(evdns_log_cb
);
1109 if (stat(conf_fname
, &st
)) {
1110 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1111 conf_fname
, strerror(errno
));
1112 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1114 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1115 && st
.st_mtime
== resolv_conf_mtime
) {
1116 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1119 if (nameservers_configured
) {
1120 evdns_search_clear();
1121 evdns_clear_nameservers_and_suspend();
1123 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1124 if ((r
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, conf_fname
))) {
1125 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1126 conf_fname
, conf_fname
, r
);
1127 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1129 if (evdns_count_nameservers() == 0) {
1130 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1131 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1133 tor_free(resolv_conf_fname
);
1134 resolv_conf_fname
= tor_strdup(conf_fname
);
1135 resolv_conf_mtime
= st
.st_mtime
;
1136 if (nameservers_configured
)
1141 if (nameservers_configured
) {
1142 evdns_search_clear();
1143 evdns_clear_nameservers_and_suspend();
1145 if (evdns_config_windows_nameservers()) {
1146 log_warn(LD_EXIT
,"Could not config nameservers.");
1147 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1149 if (evdns_count_nameservers() == 0) {
1150 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1151 "your Windows configuration. Perhaps you should list a "
1152 "ServerDNSResolvConfFile file in your torrc?");
1153 return options
->ServerDNSAllowBrokenResolvConf
? 0 : -1;
1155 if (nameservers_configured
)
1157 tor_free(resolv_conf_fname
);
1158 resolv_conf_mtime
= 0;
1162 if (evdns_count_nameservers() == 1) {
1163 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL
);
1164 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL
);
1166 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL
);
1167 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL
);
1170 dns_servers_relaunch_checks();
1172 nameservers_configured
= 1;
1176 /** For eventdns: Called when we get an answer for a request we launched.
1177 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1180 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1183 char *string_address
= arg
;
1184 uint8_t is_reverse
= 0;
1185 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1187 const char *hostname
= NULL
;
1188 int was_wildcarded
= 0;
1190 if (result
== DNS_ERR_NONE
) {
1191 if (type
== DNS_IPv4_A
&& count
) {
1192 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1194 char *escaped_address
;
1195 uint32_t *addrs
= addresses
;
1196 in
.s_addr
= addrs
[0];
1197 addr
= ntohl(addrs
[0]);
1198 status
= DNS_RESOLVE_SUCCEEDED
;
1199 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1200 escaped_address
= esc_for_log(string_address
);
1202 if (answer_is_wildcarded(answer_buf
)) {
1203 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1204 "address %s; treating as a failure.",
1205 safe_str(escaped_address
),
1206 escaped_safe_str(answer_buf
));
1209 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1211 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1212 safe_str(escaped_address
),
1213 escaped_safe_str(answer_buf
));
1215 tor_free(escaped_address
);
1216 } else if (type
== DNS_PTR
&& count
) {
1217 char *escaped_address
;
1219 hostname
= ((char**)addresses
)[0];
1220 status
= DNS_RESOLVE_SUCCEEDED
;
1221 escaped_address
= esc_for_log(string_address
);
1222 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1223 safe_str(escaped_address
),
1224 escaped_safe_str(hostname
));
1225 tor_free(escaped_address
);
1227 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1228 escaped_safe_str(string_address
));
1230 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1231 escaped_safe_str(string_address
));
1234 if (evdns_err_is_transient(result
))
1235 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1237 if (was_wildcarded
) {
1238 if (is_test_address(string_address
)) {
1239 /* Ick. We're getting redirected on known-good addresses. Our DNS
1240 * server must really hate us. */
1241 add_wildcarded_test_address(string_address
);
1244 if (result
!= DNS_ERR_SHUTDOWN
)
1245 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1246 tor_free(string_address
);
1249 /** For eventdns: start resolving as necessary to find the target for
1250 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1251 * 0 on "resolve launched." */
1253 launch_resolve(edge_connection_t
*exitconn
)
1255 char *addr
= tor_strdup(exitconn
->_base
.address
);
1258 int options
= get_options()->ServerDNSSearchDomains
? 0
1259 : DNS_QUERY_NO_SEARCH
;
1260 /* What? Nameservers not configured? Sounds like a bug. */
1261 if (!nameservers_configured
) {
1262 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1263 "launched. Configuring.");
1264 if (configure_nameservers(1) < 0)
1268 r
= parse_inaddr_arpa_address(exitconn
->_base
.address
, &in
);
1270 log_info(LD_EXIT
, "Launching eventdns request for %s",
1271 escaped_safe_str(exitconn
->_base
.address
));
1272 r
= evdns_resolve_ipv4(exitconn
->_base
.address
, options
,
1273 evdns_callback
, addr
);
1274 } else if (r
== 1) {
1275 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1276 escaped_safe_str(exitconn
->_base
.address
));
1277 r
= evdns_resolve_reverse(&in
, DNS_QUERY_NO_SEARCH
,
1278 evdns_callback
, addr
);
1279 } else if (r
== -1) {
1280 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1284 log_warn(LD_EXIT
, "eventdns rejected address %s: error %d.",
1285 escaped_safe_str(addr
), r
);
1286 r
= evdns_err_is_transient(r
) ? -2 : -1;
1287 tor_free(addr
); /* There is no evdns request in progress; stop
1288 * addr from getting leaked. */
1293 /** How many requests for bogus addresses have we launched so far? */
1294 static int n_wildcard_requests
= 0;
1296 /** Map from dotted-quad IP address in response to an int holding how many
1297 * times we've seen it for a randomly generated (hopefully bogus) address. It
1298 * would be easier to use definitely-invalid addresses (as specified by
1299 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1300 static strmap_t
*dns_wildcard_response_count
= NULL
;
1302 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1303 * nameserver wants to return in response to requests for nonexistent domains.
1305 static smartlist_t
*dns_wildcard_list
= NULL
;
1306 /** True iff we've logged about a single address getting wildcarded.
1307 * Subsequent warnings will be less severe. */
1308 static int dns_wildcard_one_notice_given
= 0;
1309 /** True iff we've warned that our DNS server is wildcarding too many failures.
1311 static int dns_wildcard_notice_given
= 0;
1313 /** List of supposedly good addresses that are getting wildcarded to the
1314 * same addresses as nonexistent addresses. */
1315 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1316 /** True iff we've warned about a test address getting wildcarded */
1317 static int dns_wildcarded_test_address_notice_given
= 0;
1318 /** True iff all addresses seem to be getting wildcarded. */
1319 static int dns_is_completely_invalid
= 0;
1321 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1322 * a hopefully bogus address. */
1324 wildcard_increment_answer(const char *id
)
1327 if (!dns_wildcard_response_count
)
1328 dns_wildcard_response_count
= strmap_new();
1330 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1332 ip
= tor_malloc_zero(sizeof(int));
1333 strmap_set(dns_wildcard_response_count
, id
, ip
);
1337 if (*ip
> 5 && n_wildcard_requests
> 10) {
1338 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1339 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1340 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1341 "Your DNS provider has given \"%s\" as an answer for %d different "
1342 "invalid addresses. Apparently they are hijacking DNS failures. "
1343 "I'll try to correct for this by treating future occurrences of "
1344 "\"%s\" as 'not found'.", id
, *ip
, id
);
1345 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1347 if (!dns_wildcard_notice_given
)
1348 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1349 dns_wildcard_notice_given
= 1;
1353 /** Note that a single test address (one believed to be good) seems to be
1354 * getting redirected to the same IP as failures are. */
1356 add_wildcarded_test_address(const char *address
)
1358 int n
, n_test_addrs
;
1359 if (!dns_wildcarded_test_address_list
)
1360 dns_wildcarded_test_address_list
= smartlist_create();
1362 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1365 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1366 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1368 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1369 n
= smartlist_len(dns_wildcarded_test_address_list
);
1370 if (n
> n_test_addrs
/2) {
1371 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1372 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1373 "address. It has done this with %d test addresses so far. I'm "
1374 "going to stop being an exit node for now, since our DNS seems so "
1375 "broken.", address
, n
);
1376 if (!dns_is_completely_invalid
) {
1377 dns_is_completely_invalid
= 1;
1378 mark_my_descriptor_dirty();
1380 if (!dns_wildcarded_test_address_notice_given
)
1381 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1382 dns_wildcarded_test_address_notice_given
= 1;
1386 /** Callback function when we get an answer (possibly failing) for a request
1387 * for a (hopefully) nonexistent domain. */
1389 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1390 void *addresses
, void *arg
)
1393 ++n_wildcard_requests
;
1394 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1395 uint32_t *addrs
= addresses
;
1397 char *string_address
= arg
;
1398 for (i
= 0; i
< count
; ++i
) {
1399 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1401 in
.s_addr
= addrs
[i
];
1402 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1403 wildcard_increment_answer(answer_buf
);
1405 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1406 "Your DNS provider gave an answer for \"%s\", which "
1407 "is not supposed to exist. Apparently they are hijacking "
1408 "DNS failures. Trying to correct for this. We've noticed %d possibly "
1409 "bad addresses so far.",
1410 string_address
, strmap_size(dns_wildcard_response_count
));
1411 dns_wildcard_one_notice_given
= 1;
1416 /** Launch a single request for a nonexistent hostname consisting of between
1417 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1420 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1425 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1426 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1427 "domains with request for bogus hostname \"%s\"", addr
);
1429 r
= evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1431 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1432 /* This "addr" is an argument to the callback*/ addr
);
1434 /* There is no evdns request in progress; stop addr from getting leaked */
1439 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1440 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1442 launch_test_addresses(int fd
, short event
, void *args
)
1444 or_options_t
*options
= get_options();
1449 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1450 "hijack *everything*.");
1451 /* This situation is worse than the failure-hijacking situation. When this
1452 * happens, we're no good for DNS requests at all, and we shouldn't really
1453 * be an exit server.*/
1454 if (!options
->ServerDNSTestAddresses
)
1456 SMARTLIST_FOREACH(options
->ServerDNSTestAddresses
, const char *, address
,
1458 int r
= evdns_resolve_ipv4(address
, DNS_QUERY_NO_SEARCH
, evdns_callback
,
1459 tor_strdup(address
));
1461 log_info(LD_EXIT
, "eventdns rejected test address %s: error %d",
1462 escaped_safe_str(address
), r
);
1466 #define N_WILDCARD_CHECKS 2
1468 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1469 * hostnames, and see if we can catch our nameserver trying to hijack them and
1470 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1471 * buy these lovely encyclopedias" page. */
1473 dns_launch_wildcard_checks(void)
1476 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1477 "to hijack DNS failures.");
1478 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1479 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1480 * to 'comply' with rfc2606, refrain from giving A records for these.
1481 * This is the standards-compliance equivalent of making sure that your
1482 * crackhouse's elevator inspection certificate is up to date.
1484 launch_wildcard_check(2, 16, ".invalid");
1485 launch_wildcard_check(2, 16, ".test");
1487 /* These will break specs if there are ever any number of
1488 * 8+-character top-level domains. */
1489 launch_wildcard_check(8, 16, "");
1491 /* Try some random .com/org/net domains. This will work fine so long as
1492 * not too many resolve to the same place. */
1493 launch_wildcard_check(8, 16, ".com");
1494 launch_wildcard_check(8, 16, ".org");
1495 launch_wildcard_check(8, 16, ".net");
1499 /** If appropriate, start testing whether our DNS servers tend to lie to
1502 dns_launch_correctness_checks(void)
1504 static struct event launch_event
;
1505 struct timeval timeout
;
1506 if (!get_options()->ServerDNSDetectHijacking
)
1508 dns_launch_wildcard_checks();
1510 /* Wait a while before launching requests for test addresses, so we can
1511 * get the results from checking for wildcarding. */
1512 evtimer_set(&launch_event
, launch_test_addresses
, NULL
);
1513 timeout
.tv_sec
= 30;
1514 timeout
.tv_usec
= 0;
1515 if (evtimer_add(&launch_event
, &timeout
)<0) {
1516 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
1520 /** Return true iff our DNS servers lie to us too much to be trustd. */
1522 dns_seems_to_be_broken(void)
1524 return dns_is_completely_invalid
;
1527 /** Forget what we've previously learned about our DNS servers' correctness. */
1529 dns_reset_correctness_checks(void)
1531 if (dns_wildcard_response_count
) {
1532 strmap_free(dns_wildcard_response_count
, _tor_free
);
1533 dns_wildcard_response_count
= NULL
;
1535 n_wildcard_requests
= 0;
1537 if (dns_wildcard_list
) {
1538 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1539 smartlist_clear(dns_wildcard_list
);
1541 if (dns_wildcarded_test_address_list
) {
1542 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1544 smartlist_clear(dns_wildcarded_test_address_list
);
1546 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1547 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1550 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1551 * returned in response to requests for nonexistent hostnames. */
1553 answer_is_wildcarded(const char *ip
)
1555 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1558 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1560 assert_resolve_ok(cached_resolve_t
*resolve
)
1562 tor_assert(resolve
);
1563 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1564 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1565 tor_assert(tor_strisnonupper(resolve
->address
));
1566 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1567 tor_assert(!resolve
->pending_connections
);
1569 if (resolve
->state
== CACHE_STATE_PENDING
||
1570 resolve
->state
== CACHE_STATE_DONE
) {
1571 tor_assert(!resolve
->ttl
);
1572 if (resolve
->is_reverse
)
1573 tor_assert(!resolve
->result
.hostname
);
1575 tor_assert(!resolve
->result
.addr
);
1579 #ifdef DEBUG_DNS_CACHE
1580 /** Exit with an assertion if the DNS cache is corrupt. */
1582 _assert_cache_ok(void)
1584 cached_resolve_t
**resolve
;
1585 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1587 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1588 tor_assert(!bad_rep
);
1591 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1592 assert_resolve_ok(*resolve
);
1593 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1595 if (!cached_resolve_pqueue
)
1598 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1599 _compare_cached_resolves_by_expiry
);
1601 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1603 if (res
->state
== CACHE_STATE_DONE
) {
1604 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1605 tor_assert(!found
|| found
!= res
);
1607 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);