conn: Stop writing when our write bandwidth limist is exhausted
[tor.git] / src / or / dns.c
blobba734ed900501544d7e5ddb8b5c5c04f9d48a51f
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file dns.c
8 * \brief Implements a local cache for DNS results for Tor servers.
9 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
10 * (We can't just use gethostbyname() and friends because we really need to
11 * be nonblocking.)
13 * There are three main cases when a Tor relay uses dns.c to launch a DNS
14 * request:
15 * <ol>
16 * <li>To check whether the DNS server is working more or less correctly.
17 * This happens via dns_launch_correctness_checks(). The answer is
18 * reported in the return value from later calls to
19 * dns_seems_to_be_broken().
20 * <li>When a client has asked the relay, in a RELAY_BEGIN cell, to connect
21 * to a given server by hostname. This happens via dns_resolve().
22 * <li>When a client has asked the relay, in a RELAY_RESOLVE cell, to look
23 * up a given server's IP address(es) by hostname. This also happens via
24 * dns_resolve().
25 * </ol>
27 * Each of these gets handled a little differently.
29 * To check for correctness, we look up some hostname we expect to exist and
30 * have real entries, some hostnames which we expect to definitely not exist,
31 * and some hostnames that we expect to probably not exist. If too many of
32 * the hostnames that shouldn't exist do exist, that's a DNS hijacking
33 * attempt. If too many of the hostnames that should exist have the same
34 * addresses as the ones that shouldn't exist, that's a very bad DNS hijacking
35 * attempt, or a very naughty captive portal. And if the hostnames that
36 * should exist simply don't exist, we probably have a broken nameserver.
38 * To handle client requests, we first check our cache for answers. If there
39 * isn't something up-to-date, we've got to launch A or AAAA requests as
40 * appropriate. How we handle responses to those in particular is a bit
41 * complex; see dns_lookup() and set_exitconn_info_from_resolve().
43 * When a lookup is finally complete, the inform_pending_connections()
44 * function will tell all of the streams that have been waiting for the
45 * resolve, by calling connection_exit_connect() if the client sent a
46 * RELAY_BEGIN cell, and by calling send_resolved_cell() or
47 * send_hostname_cell() if the client sent a RELAY_RESOLVE cell.
48 **/
50 #define DNS_PRIVATE
52 #include "or.h"
53 #include "circuitlist.h"
54 #include "circuituse.h"
55 #include "config.h"
56 #include "connection.h"
57 #include "connection_edge.h"
58 #include "control.h"
59 #include "crypto_rand.h"
60 #include "dns.h"
61 #include "main.h"
62 #include "policies.h"
63 #include "relay.h"
64 #include "router.h"
65 #include "ht.h"
66 #include "sandbox.h"
67 #include <event2/event.h>
68 #include <event2/dns.h>
70 /** How long will we wait for an answer from the resolver before we decide
71 * that the resolver is wedged? */
72 #define RESOLVE_MAX_TIMEOUT 300
74 /** Our evdns_base; this structure handles all our name lookups. */
75 static struct evdns_base *the_evdns_base = NULL;
77 /** Have we currently configured nameservers with eventdns? */
78 static int nameservers_configured = 0;
79 /** Did our most recent attempt to configure nameservers with eventdns fail? */
80 static int nameserver_config_failed = 0;
81 /** What was the resolv_conf fname we last used when configuring the
82 * nameservers? Used to check whether we need to reconfigure. */
83 static char *resolv_conf_fname = NULL;
84 /** What was the mtime on the resolv.conf file we last used when configuring
85 * the nameservers? Used to check whether we need to reconfigure. */
86 static time_t resolv_conf_mtime = 0;
88 static void purge_expired_resolves(time_t now);
89 static void dns_found_answer(const char *address, uint8_t query_type,
90 int dns_answer,
91 const tor_addr_t *addr,
92 const char *hostname,
93 uint32_t ttl);
94 static void add_wildcarded_test_address(const char *address);
95 static int configure_nameservers(int force);
96 static int answer_is_wildcarded(const char *ip);
97 static int evdns_err_is_transient(int err);
98 static void inform_pending_connections(cached_resolve_t *resolve);
99 static void make_pending_resolve_cached(cached_resolve_t *cached);
101 #ifdef DEBUG_DNS_CACHE
102 static void assert_cache_ok_(void);
103 #define assert_cache_ok() assert_cache_ok_()
104 #else
105 #define assert_cache_ok() STMT_NIL
106 #endif /* defined(DEBUG_DNS_CACHE) */
107 static void assert_resolve_ok(cached_resolve_t *resolve);
109 /** Hash table of cached_resolve objects. */
110 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
112 /** Global: how many IPv6 requests have we made in all? */
113 static uint64_t n_ipv6_requests_made = 0;
114 /** Global: how many IPv6 requests have timed out? */
115 static uint64_t n_ipv6_timeouts = 0;
116 /** Global: Do we think that IPv6 DNS is broken? */
117 static int dns_is_broken_for_ipv6 = 0;
119 /** Function to compare hashed resolves on their addresses; used to
120 * implement hash tables. */
121 static inline int
122 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
124 /* make this smarter one day? */
125 assert_resolve_ok(a); // Not b; b may be just a search.
126 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
129 /** Hash function for cached_resolve objects */
130 static inline unsigned int
131 cached_resolve_hash(cached_resolve_t *a)
133 return (unsigned) siphash24g((const uint8_t*)a->address, strlen(a->address));
136 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
137 cached_resolves_eq)
138 HT_GENERATE2(cache_map, cached_resolve_t, node, cached_resolve_hash,
139 cached_resolves_eq, 0.6, tor_reallocarray_, tor_free_)
141 /** Initialize the DNS cache. */
142 static void
143 init_cache_map(void)
145 HT_INIT(cache_map, &cache_root);
148 /** Helper: called by eventdns when eventdns wants to log something. */
149 static void
150 evdns_log_cb(int warn, const char *msg)
152 const char *cp;
153 static int all_down = 0;
154 int severity = warn ? LOG_WARN : LOG_INFO;
155 if (!strcmpstart(msg, "Resolve requested for") &&
156 get_options()->SafeLogging) {
157 log_info(LD_EXIT, "eventdns: Resolve requested.");
158 return;
159 } else if (!strcmpstart(msg, "Search: ")) {
160 return;
162 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
163 char *ns = tor_strndup(msg+11, cp-(msg+11));
164 const char *colon = strchr(cp, ':');
165 tor_assert(colon);
166 const char *err = colon+2;
167 /* Don't warn about a single failed nameserver; we'll warn with 'all
168 * nameservers have failed' if we're completely out of nameservers;
169 * otherwise, the situation is tolerable. */
170 severity = LOG_INFO;
171 control_event_server_status(LOG_NOTICE,
172 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
173 ns, escaped(err));
174 tor_free(ns);
175 } else if (!strcmpstart(msg, "Nameserver ") &&
176 (cp=strstr(msg, " is back up"))) {
177 char *ns = tor_strndup(msg+11, cp-(msg+11));
178 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
179 all_down = 0;
180 control_event_server_status(LOG_NOTICE,
181 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
182 tor_free(ns);
183 } else if (!strcmp(msg, "All nameservers have failed")) {
184 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
185 all_down = 1;
186 } else if (!strcmpstart(msg, "Address mismatch on received DNS")) {
187 static ratelim_t mismatch_limit = RATELIM_INIT(3600);
188 const char *src = strstr(msg, " Apparent source");
189 if (!src || get_options()->SafeLogging) {
190 src = "";
192 log_fn_ratelim(&mismatch_limit, severity, LD_EXIT,
193 "eventdns: Received a DNS packet from "
194 "an IP address to which we did not send a request. This "
195 "could be a DNS spoofing attempt, or some kind of "
196 "misconfiguration.%s", src);
197 return;
199 tor_log(severity, LD_EXIT, "eventdns: %s", msg);
202 /** Helper: passed to eventdns.c as a callback so it can generate random
203 * numbers for transaction IDs and 0x20-hack coding. */
204 static void
205 dns_randfn_(char *b, size_t n)
207 crypto_rand(b,n);
210 /** Initialize the DNS subsystem; called by the OR process. */
212 dns_init(void)
214 init_cache_map();
215 evdns_set_random_bytes_fn(dns_randfn_);
216 if (server_mode(get_options())) {
217 int r = configure_nameservers(1);
218 return r;
220 return 0;
223 /** Called when DNS-related options change (or may have changed). Returns -1
224 * on failure, 0 on success. */
226 dns_reset(void)
228 const or_options_t *options = get_options();
229 if (! server_mode(options)) {
231 if (!the_evdns_base) {
232 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
233 log_err(LD_BUG, "Couldn't create an evdns_base");
234 return -1;
238 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
239 evdns_base_search_clear(the_evdns_base);
240 nameservers_configured = 0;
241 tor_free(resolv_conf_fname);
242 resolv_conf_mtime = 0;
243 } else {
244 if (configure_nameservers(0) < 0) {
245 return -1;
248 return 0;
251 /** Return true iff the most recent attempt to initialize the DNS subsystem
252 * failed. */
254 has_dns_init_failed(void)
256 return nameserver_config_failed;
259 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
260 * OP that asked us to resolve it, and how long to cache that record
261 * ourselves. */
262 uint32_t
263 dns_clip_ttl(uint32_t ttl)
265 /* This logic is a defense against "DefectTor" DNS-based traffic
266 * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
267 * We only give two values: a "low" value and a "high" value.
269 if (ttl < MIN_DNS_TTL_AT_EXIT)
270 return MIN_DNS_TTL_AT_EXIT;
271 else
272 return MAX_DNS_TTL_AT_EXIT;
275 /** Helper: free storage held by an entry in the DNS cache. */
276 static void
277 free_cached_resolve_(cached_resolve_t *r)
279 if (!r)
280 return;
281 while (r->pending_connections) {
282 pending_connection_t *victim = r->pending_connections;
283 r->pending_connections = victim->next;
284 tor_free(victim);
286 if (r->res_status_hostname == RES_STATUS_DONE_OK)
287 tor_free(r->result_ptr.hostname);
288 r->magic = 0xFF00FF00;
289 tor_free(r);
292 /** Compare two cached_resolve_t pointers by expiry time, and return
293 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
294 * the priority queue implementation. */
295 static int
296 compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
298 const cached_resolve_t *a = _a, *b = _b;
299 if (a->expire < b->expire)
300 return -1;
301 else if (a->expire == b->expire)
302 return 0;
303 else
304 return 1;
307 /** Priority queue of cached_resolve_t objects to let us know when they
308 * will expire. */
309 static smartlist_t *cached_resolve_pqueue = NULL;
311 static void
312 cached_resolve_add_answer(cached_resolve_t *resolve,
313 int query_type,
314 int dns_result,
315 const tor_addr_t *answer_addr,
316 const char *answer_hostname,
317 uint32_t ttl)
319 if (query_type == DNS_PTR) {
320 if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
321 return;
323 if (dns_result == DNS_ERR_NONE && answer_hostname) {
324 resolve->result_ptr.hostname = tor_strdup(answer_hostname);
325 resolve->res_status_hostname = RES_STATUS_DONE_OK;
326 } else {
327 resolve->result_ptr.err_hostname = dns_result;
328 resolve->res_status_hostname = RES_STATUS_DONE_ERR;
330 resolve->ttl_hostname = ttl;
331 } else if (query_type == DNS_IPv4_A) {
332 if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
333 return;
335 if (dns_result == DNS_ERR_NONE && answer_addr &&
336 tor_addr_family(answer_addr) == AF_INET) {
337 resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
338 resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
339 } else {
340 resolve->result_ipv4.err_ipv4 = dns_result;
341 resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
343 resolve->ttl_ipv4 = ttl;
344 } else if (query_type == DNS_IPv6_AAAA) {
345 if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
346 return;
348 if (dns_result == DNS_ERR_NONE && answer_addr &&
349 tor_addr_family(answer_addr) == AF_INET6) {
350 memcpy(&resolve->result_ipv6.addr_ipv6,
351 tor_addr_to_in6(answer_addr),
352 sizeof(struct in6_addr));
353 resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
354 } else {
355 resolve->result_ipv6.err_ipv6 = dns_result;
356 resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
358 resolve->ttl_ipv6 = ttl;
362 /** Return true iff there are no in-flight requests for <b>resolve</b>. */
363 static int
364 cached_resolve_have_all_answers(const cached_resolve_t *resolve)
366 return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
367 resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
368 resolve->res_status_hostname != RES_STATUS_INFLIGHT);
371 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
372 * priority queue */
373 static void
374 set_expiry(cached_resolve_t *resolve, time_t expires)
376 tor_assert(resolve && resolve->expire == 0);
377 if (!cached_resolve_pqueue)
378 cached_resolve_pqueue = smartlist_new();
379 resolve->expire = expires;
380 smartlist_pqueue_add(cached_resolve_pqueue,
381 compare_cached_resolves_by_expiry_,
382 offsetof(cached_resolve_t, minheap_idx),
383 resolve);
386 /** Free all storage held in the DNS cache and related structures. */
387 void
388 dns_free_all(void)
390 cached_resolve_t **ptr, **next, *item;
391 assert_cache_ok();
392 if (cached_resolve_pqueue) {
393 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
395 if (res->state == CACHE_STATE_DONE)
396 free_cached_resolve_(res);
399 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
400 item = *ptr;
401 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
402 free_cached_resolve_(item);
404 HT_CLEAR(cache_map, &cache_root);
405 smartlist_free(cached_resolve_pqueue);
406 cached_resolve_pqueue = NULL;
407 tor_free(resolv_conf_fname);
410 /** Remove every cached_resolve whose <b>expire</b> time is before or
411 * equal to <b>now</b> from the cache. */
412 static void
413 purge_expired_resolves(time_t now)
415 cached_resolve_t *resolve, *removed;
416 pending_connection_t *pend;
417 edge_connection_t *pendconn;
419 assert_cache_ok();
420 if (!cached_resolve_pqueue)
421 return;
423 while (smartlist_len(cached_resolve_pqueue)) {
424 resolve = smartlist_get(cached_resolve_pqueue, 0);
425 if (resolve->expire > now)
426 break;
427 smartlist_pqueue_pop(cached_resolve_pqueue,
428 compare_cached_resolves_by_expiry_,
429 offsetof(cached_resolve_t, minheap_idx));
431 if (resolve->state == CACHE_STATE_PENDING) {
432 log_debug(LD_EXIT,
433 "Expiring a dns resolve %s that's still pending. Forgot to "
434 "cull it? DNS resolve didn't tell us about the timeout?",
435 escaped_safe_str(resolve->address));
436 } else if (resolve->state == CACHE_STATE_CACHED) {
437 log_debug(LD_EXIT,
438 "Forgetting old cached resolve (address %s, expires %lu)",
439 escaped_safe_str(resolve->address),
440 (unsigned long)resolve->expire);
441 tor_assert(!resolve->pending_connections);
442 } else {
443 tor_assert(resolve->state == CACHE_STATE_DONE);
444 tor_assert(!resolve->pending_connections);
447 if (resolve->pending_connections) {
448 log_debug(LD_EXIT,
449 "Closing pending connections on timed-out DNS resolve!");
450 while (resolve->pending_connections) {
451 pend = resolve->pending_connections;
452 resolve->pending_connections = pend->next;
453 /* Connections should only be pending if they have no socket. */
454 tor_assert(!SOCKET_OK(pend->conn->base_.s));
455 pendconn = pend->conn;
456 /* Prevent double-remove */
457 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
458 if (!pendconn->base_.marked_for_close) {
459 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
460 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
461 connection_free_(TO_CONN(pendconn));
463 tor_free(pend);
467 if (resolve->state == CACHE_STATE_CACHED ||
468 resolve->state == CACHE_STATE_PENDING) {
469 removed = HT_REMOVE(cache_map, &cache_root, resolve);
470 if (removed != resolve) {
471 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
472 " the cache. Tried to purge %s (%p); instead got %s (%p).",
473 resolve->address, (void*)resolve,
474 removed ? removed->address : "NULL", (void*)removed);
476 tor_assert(removed == resolve);
477 } else {
478 /* This should be in state DONE. Make sure it's not in the cache. */
479 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
480 tor_assert(tmp != resolve);
482 if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
483 tor_free(resolve->result_ptr.hostname);
484 resolve->magic = 0xF0BBF0BB;
485 tor_free(resolve);
488 assert_cache_ok();
491 /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
492 * or ipv6 depending on the connection's address". */
493 #define RESOLVED_TYPE_AUTO 0xff
495 /** Send a response to the RESOLVE request of a connection.
496 * <b>answer_type</b> must be one of
497 * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
499 * If <b>circ</b> is provided, and we have a cached answer, send the
500 * answer back along circ; otherwise, send the answer back along
501 * <b>conn</b>'s attached circuit.
503 MOCK_IMPL(STATIC void,
504 send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type,
505 const cached_resolve_t *resolved))
507 char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
508 size_t buflen = 0;
509 uint32_t ttl;
511 buf[0] = answer_type;
512 ttl = dns_clip_ttl(conn->address_ttl);
514 switch (answer_type)
516 case RESOLVED_TYPE_AUTO:
517 if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
518 cp[0] = RESOLVED_TYPE_IPV4;
519 cp[1] = 4;
520 set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
521 set_uint32(cp+6, htonl(ttl));
522 cp += 10;
524 if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
525 const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
526 cp[0] = RESOLVED_TYPE_IPV6;
527 cp[1] = 16;
528 memcpy(cp+2, bytes, 16);
529 set_uint32(cp+18, htonl(ttl));
530 cp += 22;
532 if (cp != buf) {
533 buflen = cp - buf;
534 break;
535 } else {
536 answer_type = RESOLVED_TYPE_ERROR;
537 /* fall through. */
539 /* Falls through. */
540 case RESOLVED_TYPE_ERROR_TRANSIENT:
541 case RESOLVED_TYPE_ERROR:
543 const char *errmsg = "Error resolving hostname";
544 size_t msglen = strlen(errmsg);
546 buf[0] = answer_type;
547 buf[1] = msglen;
548 strlcpy(buf+2, errmsg, sizeof(buf)-2);
549 set_uint32(buf+2+msglen, htonl(ttl));
550 buflen = 6+msglen;
551 break;
553 default:
554 tor_assert(0);
555 return;
557 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
559 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
562 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
563 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
564 * The answer type will be RESOLVED_HOSTNAME.
566 * If <b>circ</b> is provided, and we have a cached answer, send the
567 * answer back along circ; otherwise, send the answer back along
568 * <b>conn</b>'s attached circuit.
570 MOCK_IMPL(STATIC void,
571 send_resolved_hostname_cell,(edge_connection_t *conn,
572 const char *hostname))
574 char buf[RELAY_PAYLOAD_SIZE];
575 size_t buflen;
576 uint32_t ttl;
577 size_t namelen = strlen(hostname);
578 tor_assert(hostname);
580 tor_assert(namelen < 256);
581 ttl = dns_clip_ttl(conn->address_ttl);
583 buf[0] = RESOLVED_TYPE_HOSTNAME;
584 buf[1] = (uint8_t)namelen;
585 memcpy(buf+2, hostname, namelen);
586 set_uint32(buf+2+namelen, htonl(ttl));
587 buflen = 2+namelen+4;
589 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
590 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
591 // log_notice(LD_EXIT, "Sent");
594 /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
595 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
596 * If resolve failed, free exitconn and return -1.
598 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
599 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
600 * need to send back an END cell, since connection_exit_begin_conn will
601 * do that for us.)
603 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
604 * circuit.
606 * Else, if seen before and pending, add conn to the pending list,
607 * and return 0.
609 * Else, if not seen before, add conn to pending list, hand to
610 * dns farm, and return 0.
612 * Exitconn's on_circuit field must be set, but exitconn should not
613 * yet be linked onto the n_streams/resolving_streams list of that circuit.
614 * On success, link the connection to n_streams if it's an exit connection.
615 * On "pending", link the connection to resolving streams. Otherwise,
616 * clear its on_circuit field.
619 dns_resolve(edge_connection_t *exitconn)
621 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
622 int is_resolve, r;
623 int made_connection_pending = 0;
624 char *hostname = NULL;
625 cached_resolve_t *resolve = NULL;
626 is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
628 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
629 &made_connection_pending, &resolve);
631 switch (r) {
632 case 1:
633 /* We got an answer without a lookup -- either the answer was
634 * cached, or it was obvious (like an IP address). */
635 if (is_resolve) {
636 /* Send the answer back right now, and detach. */
637 if (hostname)
638 send_resolved_hostname_cell(exitconn, hostname);
639 else
640 send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
641 exitconn->on_circuit = NULL;
642 } else {
643 /* Add to the n_streams list; the calling function will send back a
644 * connected cell. */
645 exitconn->next_stream = oncirc->n_streams;
646 oncirc->n_streams = exitconn;
648 break;
649 case 0:
650 /* The request is pending: add the connection into the linked list of
651 * resolving_streams on this circuit. */
652 exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
653 exitconn->next_stream = oncirc->resolving_streams;
654 oncirc->resolving_streams = exitconn;
655 break;
656 case -2:
657 case -1:
658 /* The request failed before it could start: cancel this connection,
659 * and stop everybody waiting for the same connection. */
660 if (is_resolve) {
661 send_resolved_cell(exitconn,
662 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
663 NULL);
666 exitconn->on_circuit = NULL;
668 dns_cancel_pending_resolve(exitconn->base_.address);
670 if (!made_connection_pending && !exitconn->base_.marked_for_close) {
671 /* If we made the connection pending, then we freed it already in
672 * dns_cancel_pending_resolve(). If we marked it for close, it'll
673 * get freed from the main loop. Otherwise, can free it now. */
674 connection_free_(TO_CONN(exitconn));
676 break;
677 default:
678 tor_assert(0);
681 tor_free(hostname);
682 return r;
685 /** Helper function for dns_resolve: same functionality, but does not handle:
686 * - marking connections on error and clearing their on_circuit
687 * - linking connections to n_streams/resolving_streams,
688 * - sending resolved cells if we have an answer/error right away,
690 * Return -2 on a transient error. If it's a reverse resolve and it's
691 * successful, sets *<b>hostname_out</b> to a newly allocated string
692 * holding the cached reverse DNS value.
694 * Set *<b>made_connection_pending_out</b> to true if we have placed
695 * <b>exitconn</b> on the list of pending connections for some resolve; set it
696 * to false otherwise.
698 * Set *<b>resolve_out</b> to a cached resolve, if we found one.
700 MOCK_IMPL(STATIC int,
701 dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
702 or_circuit_t *oncirc, char **hostname_out,
703 int *made_connection_pending_out,
704 cached_resolve_t **resolve_out))
706 cached_resolve_t *resolve;
707 cached_resolve_t search;
708 pending_connection_t *pending_connection;
709 int is_reverse = 0;
710 tor_addr_t addr;
711 time_t now = time(NULL);
712 int r;
713 assert_connection_ok(TO_CONN(exitconn), 0);
714 tor_assert(!SOCKET_OK(exitconn->base_.s));
715 assert_cache_ok();
716 tor_assert(oncirc);
717 *made_connection_pending_out = 0;
719 /* first check if exitconn->base_.address is an IP. If so, we already
720 * know the answer. */
721 if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
722 if (tor_addr_family(&addr) == AF_INET ||
723 tor_addr_family(&addr) == AF_INET6) {
724 tor_addr_copy(&exitconn->base_.addr, &addr);
725 exitconn->address_ttl = DEFAULT_DNS_TTL;
726 return 1;
727 } else {
728 /* XXXX unspec? Bogus? */
729 return -1;
733 /* If we're a non-exit, don't even do DNS lookups. */
734 if (router_my_exit_policy_is_reject_star())
735 return -1;
737 if (address_is_invalid_destination(exitconn->base_.address, 0)) {
738 tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
739 "Rejecting invalid destination address %s",
740 escaped_safe_str(exitconn->base_.address));
741 return -1;
744 /* then take this opportunity to see if there are any expired
745 * resolves in the hash table. */
746 purge_expired_resolves(now);
748 /* lower-case exitconn->base_.address, so it's in canonical form */
749 tor_strlower(exitconn->base_.address);
751 /* Check whether this is a reverse lookup. If it's malformed, or it's a
752 * .in-addr.arpa address but this isn't a resolve request, kill the
753 * connection.
755 if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
756 AF_UNSPEC, 0)) != 0) {
757 if (r == 1) {
758 is_reverse = 1;
759 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
760 return -1;
763 if (!is_reverse || !is_resolve) {
764 if (!is_reverse)
765 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
766 escaped_safe_str(exitconn->base_.address));
767 else if (!is_resolve)
768 log_info(LD_EXIT,
769 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
770 "sending error.",
771 escaped_safe_str(exitconn->base_.address));
773 return -1;
775 //log_notice(LD_EXIT, "Looks like an address %s",
776 //exitconn->base_.address);
778 exitconn->is_reverse_dns_lookup = is_reverse;
780 /* now check the hash table to see if 'address' is already there. */
781 strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
782 resolve = HT_FIND(cache_map, &cache_root, &search);
783 if (resolve && resolve->expire > now) { /* already there */
784 switch (resolve->state) {
785 case CACHE_STATE_PENDING:
786 /* add us to the pending list */
787 pending_connection = tor_malloc_zero(
788 sizeof(pending_connection_t));
789 pending_connection->conn = exitconn;
790 pending_connection->next = resolve->pending_connections;
791 resolve->pending_connections = pending_connection;
792 *made_connection_pending_out = 1;
793 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
794 "for pending DNS resolve of %s", exitconn->base_.s,
795 escaped_safe_str(exitconn->base_.address));
796 return 0;
797 case CACHE_STATE_CACHED:
798 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
799 "cached answer for %s",
800 exitconn->base_.s,
801 escaped_safe_str(resolve->address));
803 *resolve_out = resolve;
805 return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
806 case CACHE_STATE_DONE:
807 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
808 tor_fragile_assert();
810 tor_assert(0);
812 tor_assert(!resolve);
813 /* not there, need to add it */
814 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
815 resolve->magic = CACHED_RESOLVE_MAGIC;
816 resolve->state = CACHE_STATE_PENDING;
817 resolve->minheap_idx = -1;
818 strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
820 /* add this connection to the pending list */
821 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
822 pending_connection->conn = exitconn;
823 resolve->pending_connections = pending_connection;
824 *made_connection_pending_out = 1;
826 /* Add this resolve to the cache and priority queue. */
827 HT_INSERT(cache_map, &cache_root, resolve);
828 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
830 log_debug(LD_EXIT,"Launching %s.",
831 escaped_safe_str(exitconn->base_.address));
832 assert_cache_ok();
834 return launch_resolve(resolve);
837 /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
838 * <b>resolve</b> whose DNS lookups have all either succeeded or failed,
839 * update the appropriate fields (address_ttl and addr) of <b>exitconn</b>.
841 * The logic can be complicated here, since we might have launched both
842 * an A lookup and an AAAA lookup, and since either of those might have
843 * succeeded or failed, and since we want to answer a RESOLVE cell with
844 * a full answer but answer a BEGIN cell with whatever answer the client
845 * would accept <i>and</i> we could still connect to.
847 * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
848 * copy of the name resulting hostname.
850 * Return -2 on a transient error, -1 on a permenent error, and 1 on
851 * a successful lookup.
853 MOCK_IMPL(STATIC int,
854 set_exitconn_info_from_resolve,(edge_connection_t *exitconn,
855 const cached_resolve_t *resolve,
856 char **hostname_out))
858 int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
859 uint32_t begincell_flags;
860 const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
861 tor_assert(exitconn);
862 tor_assert(resolve);
864 if (exitconn->is_reverse_dns_lookup) {
865 exitconn->address_ttl = resolve->ttl_hostname;
866 if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
867 *hostname_out = tor_strdup(resolve->result_ptr.hostname);
868 return 1;
869 } else {
870 return -1;
874 /* If we're here then the connection wants one or either of ipv4, ipv6, and
875 * we can give it one or both. */
876 if (is_resolve) {
877 begincell_flags = BEGIN_FLAG_IPV6_OK;
878 } else {
879 begincell_flags = exitconn->begincell_flags;
882 ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
883 ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
884 ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
885 (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
886 get_options()->IPv6Exit;
888 /* Now decide which one to actually give. */
889 if (ipv4_ok && ipv6_ok && is_resolve) {
890 answer_with_ipv4 = 1;
891 } else if (ipv4_ok && ipv6_ok) {
892 /* If we have both, see if our exit policy has an opinion. */
893 const uint16_t port = exitconn->base_.port;
894 int ipv4_allowed, ipv6_allowed;
895 tor_addr_t a4, a6;
896 tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
897 tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
898 ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
899 ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
900 if (ipv4_allowed && !ipv6_allowed) {
901 answer_with_ipv4 = 1;
902 } else if (ipv6_allowed && !ipv4_allowed) {
903 answer_with_ipv4 = 0;
904 } else {
905 /* Our exit policy would permit both. Answer with whichever the user
906 * prefers */
907 answer_with_ipv4 = !(begincell_flags &
908 BEGIN_FLAG_IPV6_PREFERRED);
910 } else {
911 /* Otherwise if one is okay, send it back. */
912 if (ipv4_ok) {
913 answer_with_ipv4 = 1;
914 } else if (ipv6_ok) {
915 answer_with_ipv4 = 0;
916 } else {
917 /* Neither one was okay. Choose based on user preference. */
918 answer_with_ipv4 = !(begincell_flags &
919 BEGIN_FLAG_IPV6_PREFERRED);
923 /* Finally, we write the answer back. */
924 r = 1;
925 if (answer_with_ipv4) {
926 if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
927 tor_addr_from_ipv4h(&exitconn->base_.addr,
928 resolve->result_ipv4.addr_ipv4);
929 } else {
930 r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
933 exitconn->address_ttl = resolve->ttl_ipv4;
934 } else {
935 if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
936 tor_addr_from_in6(&exitconn->base_.addr,
937 &resolve->result_ipv6.addr_ipv6);
938 } else {
939 r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
942 exitconn->address_ttl = resolve->ttl_ipv6;
945 return r;
948 /** Log an error and abort if conn is waiting for a DNS resolve.
950 void
951 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
953 pending_connection_t *pend;
954 cached_resolve_t search;
956 #if 1
957 cached_resolve_t *resolve;
958 strlcpy(search.address, conn->base_.address, sizeof(search.address));
959 resolve = HT_FIND(cache_map, &cache_root, &search);
960 if (!resolve)
961 return;
962 for (pend = resolve->pending_connections; pend; pend = pend->next) {
963 tor_assert(pend->conn != conn);
965 #else /* !(1) */
966 cached_resolve_t **resolve;
967 HT_FOREACH(resolve, cache_map, &cache_root) {
968 for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
969 tor_assert(pend->conn != conn);
972 #endif /* 1 */
975 /** Log an error and abort if any connection waiting for a DNS resolve is
976 * corrupted. */
977 void
978 assert_all_pending_dns_resolves_ok(void)
980 pending_connection_t *pend;
981 cached_resolve_t **resolve;
983 HT_FOREACH(resolve, cache_map, &cache_root) {
984 for (pend = (*resolve)->pending_connections;
985 pend;
986 pend = pend->next) {
987 assert_connection_ok(TO_CONN(pend->conn), 0);
988 tor_assert(!SOCKET_OK(pend->conn->base_.s));
989 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
994 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
996 void
997 connection_dns_remove(edge_connection_t *conn)
999 pending_connection_t *pend, *victim;
1000 cached_resolve_t search;
1001 cached_resolve_t *resolve;
1003 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
1004 tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
1006 strlcpy(search.address, conn->base_.address, sizeof(search.address));
1008 resolve = HT_FIND(cache_map, &cache_root, &search);
1009 if (!resolve) {
1010 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
1011 escaped_safe_str(conn->base_.address));
1012 return;
1015 tor_assert(resolve->pending_connections);
1016 assert_connection_ok(TO_CONN(conn),0);
1018 pend = resolve->pending_connections;
1020 if (pend->conn == conn) {
1021 resolve->pending_connections = pend->next;
1022 tor_free(pend);
1023 log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
1024 "longer waiting for resolve of %s",
1025 conn->base_.s,
1026 escaped_safe_str(conn->base_.address));
1027 return;
1028 } else {
1029 for ( ; pend->next; pend = pend->next) {
1030 if (pend->next->conn == conn) {
1031 victim = pend->next;
1032 pend->next = victim->next;
1033 tor_free(victim);
1034 log_debug(LD_EXIT,
1035 "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
1036 "for resolve of %s",
1037 conn->base_.s, escaped_safe_str(conn->base_.address));
1038 return; /* more are pending */
1041 log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
1042 "for a resolve of %s, but we tried to remove it.",
1043 conn->base_.s, escaped_safe_str(conn->base_.address));
1047 /** Mark all connections waiting for <b>address</b> for close. Then cancel
1048 * the resolve for <b>address</b> itself, and remove any cached results for
1049 * <b>address</b> from the cache.
1051 MOCK_IMPL(void,
1052 dns_cancel_pending_resolve,(const char *address))
1054 pending_connection_t *pend;
1055 cached_resolve_t search;
1056 cached_resolve_t *resolve, *tmp;
1057 edge_connection_t *pendconn;
1058 circuit_t *circ;
1060 strlcpy(search.address, address, sizeof(search.address));
1062 resolve = HT_FIND(cache_map, &cache_root, &search);
1063 if (!resolve)
1064 return;
1066 if (resolve->state != CACHE_STATE_PENDING) {
1067 /* We can get into this state if we never actually created the pending
1068 * resolve, due to finding an earlier cached error or something. Just
1069 * ignore it. */
1070 if (resolve->pending_connections) {
1071 log_warn(LD_BUG,
1072 "Address %s is not pending but has pending connections!",
1073 escaped_safe_str(address));
1074 tor_fragile_assert();
1076 return;
1079 if (!resolve->pending_connections) {
1080 log_warn(LD_BUG,
1081 "Address %s is pending but has no pending connections!",
1082 escaped_safe_str(address));
1083 tor_fragile_assert();
1084 return;
1086 tor_assert(resolve->pending_connections);
1088 /* mark all pending connections to fail */
1089 log_debug(LD_EXIT,
1090 "Failing all connections waiting on DNS resolve of %s",
1091 escaped_safe_str(address));
1092 while (resolve->pending_connections) {
1093 pend = resolve->pending_connections;
1094 pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1095 pendconn = pend->conn;
1096 assert_connection_ok(TO_CONN(pendconn), 0);
1097 tor_assert(!SOCKET_OK(pendconn->base_.s));
1098 if (!pendconn->base_.marked_for_close) {
1099 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1101 circ = circuit_get_by_edge_conn(pendconn);
1102 if (circ)
1103 circuit_detach_stream(circ, pendconn);
1104 if (!pendconn->base_.marked_for_close)
1105 connection_free_(TO_CONN(pendconn));
1106 resolve->pending_connections = pend->next;
1107 tor_free(pend);
1110 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
1111 if (tmp != resolve) {
1112 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
1113 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1114 resolve->address, (void*)resolve,
1115 tmp ? tmp->address : "NULL", (void*)tmp);
1117 tor_assert(tmp == resolve);
1119 resolve->state = CACHE_STATE_DONE;
1122 /** Return true iff <b>address</b> is one of the addresses we use to verify
1123 * that well-known sites aren't being hijacked by our DNS servers. */
1124 static inline int
1125 is_test_address(const char *address)
1127 const or_options_t *options = get_options();
1128 return options->ServerDNSTestAddresses &&
1129 smartlist_contains_string_case(options->ServerDNSTestAddresses, address);
1132 /** Called on the OR side when the eventdns library tells us the outcome of a
1133 * single DNS resolve: remember the answer, and tell all pending connections
1134 * about the result of the lookup if the lookup is now done. (<b>address</b>
1135 * is a NUL-terminated string containing the address to look up;
1136 * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
1137 * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
1138 * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
1139 * <b>ttl</b> is the time-to-live of this answer, in seconds.)
1141 static void
1142 dns_found_answer(const char *address, uint8_t query_type,
1143 int dns_answer,
1144 const tor_addr_t *addr,
1145 const char *hostname, uint32_t ttl)
1147 cached_resolve_t search;
1148 cached_resolve_t *resolve;
1150 assert_cache_ok();
1152 strlcpy(search.address, address, sizeof(search.address));
1154 resolve = HT_FIND(cache_map, &cache_root, &search);
1155 if (!resolve) {
1156 int is_test_addr = is_test_address(address);
1157 if (!is_test_addr)
1158 log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
1159 escaped_safe_str(address));
1160 return;
1162 assert_resolve_ok(resolve);
1164 if (resolve->state != CACHE_STATE_PENDING) {
1165 /* XXXX Maybe update addr? or check addr for consistency? Or let
1166 * VALID replace FAILED? */
1167 int is_test_addr = is_test_address(address);
1168 if (!is_test_addr)
1169 log_notice(LD_EXIT,
1170 "Resolved %s which was already resolved; ignoring",
1171 escaped_safe_str(address));
1172 tor_assert(resolve->pending_connections == NULL);
1173 return;
1176 cached_resolve_add_answer(resolve, query_type, dns_answer,
1177 addr, hostname, ttl);
1179 if (cached_resolve_have_all_answers(resolve)) {
1180 inform_pending_connections(resolve);
1182 make_pending_resolve_cached(resolve);
1186 /** Given a pending cached_resolve_t that we just finished resolving,
1187 * inform every connection that was waiting for the outcome of that
1188 * resolution.
1190 * Do this by sending a RELAY_RESOLVED cell (if the pending stream had sent us
1191 * RELAY_RESOLVE cell), or by launching an exit connection (if the pending
1192 * stream had send us a RELAY_BEGIN cell).
1194 static void
1195 inform_pending_connections(cached_resolve_t *resolve)
1197 pending_connection_t *pend;
1198 edge_connection_t *pendconn;
1199 int r;
1201 while (resolve->pending_connections) {
1202 char *hostname = NULL;
1203 pend = resolve->pending_connections;
1204 pendconn = pend->conn; /* don't pass complex things to the
1205 connection_mark_for_close macro */
1206 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1208 if (pendconn->base_.marked_for_close) {
1209 /* prevent double-remove. */
1210 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1211 resolve->pending_connections = pend->next;
1212 tor_free(pend);
1213 continue;
1216 r = set_exitconn_info_from_resolve(pendconn,
1217 resolve,
1218 &hostname);
1220 if (r < 0) {
1221 /* prevent double-remove. */
1222 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1223 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1224 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1225 /* This detach must happen after we send the end cell. */
1226 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1227 } else {
1228 send_resolved_cell(pendconn, r == -1 ?
1229 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
1230 NULL);
1231 /* This detach must happen after we send the resolved cell. */
1232 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1234 connection_free_(TO_CONN(pendconn));
1235 } else {
1236 circuit_t *circ;
1237 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1238 /* prevent double-remove. */
1239 pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
1241 circ = circuit_get_by_edge_conn(pend->conn);
1242 tor_assert(circ);
1243 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1244 /* unlink pend->conn from resolving_streams, */
1245 circuit_detach_stream(circ, pend->conn);
1246 /* and link it to n_streams */
1247 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1248 pend->conn->on_circuit = circ;
1249 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1251 connection_exit_connect(pend->conn);
1252 } else {
1253 /* prevent double-remove. This isn't really an accurate state,
1254 * but it does the right thing. */
1255 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1256 if (pendconn->is_reverse_dns_lookup)
1257 send_resolved_hostname_cell(pendconn, hostname);
1258 else
1259 send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
1260 circ = circuit_get_by_edge_conn(pendconn);
1261 tor_assert(circ);
1262 circuit_detach_stream(circ, pendconn);
1263 connection_free_(TO_CONN(pendconn));
1266 resolve->pending_connections = pend->next;
1267 tor_free(pend);
1268 tor_free(hostname);
1272 /** Remove a pending cached_resolve_t from the hashtable, and add a
1273 * corresponding cached cached_resolve_t.
1275 * This function is only necessary because of the perversity of our
1276 * cache timeout code; see inline comment for ideas on eliminating it.
1278 static void
1279 make_pending_resolve_cached(cached_resolve_t *resolve)
1281 cached_resolve_t *removed;
1283 resolve->state = CACHE_STATE_DONE;
1284 removed = HT_REMOVE(cache_map, &cache_root, resolve);
1285 if (removed != resolve) {
1286 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1287 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1288 resolve->address, (void*)resolve,
1289 removed ? removed->address : "NULL", (void*)removed);
1291 assert_resolve_ok(resolve);
1292 assert_cache_ok();
1293 /* The resolve will eventually just hit the time-out in the expiry queue and
1294 * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
1295 * way. XXXXX we could do better!*/
1298 cached_resolve_t *new_resolve = tor_memdup(resolve,
1299 sizeof(cached_resolve_t));
1300 uint32_t ttl = UINT32_MAX;
1301 new_resolve->expire = 0; /* So that set_expiry won't croak. */
1302 if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
1303 new_resolve->result_ptr.hostname =
1304 tor_strdup(resolve->result_ptr.hostname);
1306 new_resolve->state = CACHE_STATE_CACHED;
1308 assert_resolve_ok(new_resolve);
1309 HT_INSERT(cache_map, &cache_root, new_resolve);
1311 if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
1312 resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
1313 resolve->ttl_ipv4 < ttl)
1314 ttl = resolve->ttl_ipv4;
1316 if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
1317 resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
1318 resolve->ttl_ipv6 < ttl)
1319 ttl = resolve->ttl_ipv6;
1321 if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
1322 resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
1323 resolve->ttl_hostname < ttl)
1324 ttl = resolve->ttl_hostname;
1326 set_expiry(new_resolve, time(NULL) + dns_clip_ttl(ttl));
1329 assert_cache_ok();
1332 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1333 * a transient failure. */
1334 static int
1335 evdns_err_is_transient(int err)
1337 switch (err)
1339 case DNS_ERR_SERVERFAILED:
1340 case DNS_ERR_TRUNCATED:
1341 case DNS_ERR_TIMEOUT:
1342 return 1;
1343 default:
1344 return 0;
1348 /** Configure eventdns nameservers if force is true, or if the configuration
1349 * has changed since the last time we called this function, or if we failed on
1350 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1351 * options->ServerDNSResolvConfFile; on Windows, this reads from
1352 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1353 * -1 on failure. */
1354 static int
1355 configure_nameservers(int force)
1357 const or_options_t *options;
1358 const char *conf_fname;
1359 struct stat st;
1360 int r, flags;
1361 options = get_options();
1362 conf_fname = options->ServerDNSResolvConfFile;
1363 #ifndef _WIN32
1364 if (!conf_fname)
1365 conf_fname = "/etc/resolv.conf";
1366 #endif
1367 flags = DNS_OPTIONS_ALL;
1369 if (!the_evdns_base) {
1370 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
1371 log_err(LD_BUG, "Couldn't create an evdns_base");
1372 return -1;
1376 evdns_set_log_fn(evdns_log_cb);
1377 if (conf_fname) {
1378 log_debug(LD_FS, "stat()ing %s", conf_fname);
1379 if (stat(sandbox_intern_string(conf_fname), &st)) {
1380 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1381 conf_fname, strerror(errno));
1382 goto err;
1384 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1385 && st.st_mtime == resolv_conf_mtime) {
1386 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1387 return 0;
1389 if (nameservers_configured) {
1390 evdns_base_search_clear(the_evdns_base);
1391 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1393 #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
1394 if (flags & DNS_OPTION_HOSTSFILE) {
1395 flags ^= DNS_OPTION_HOSTSFILE;
1396 log_debug(LD_FS, "Loading /etc/hosts");
1397 evdns_base_load_hosts(the_evdns_base,
1398 sandbox_intern_string("/etc/hosts"));
1400 #endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
1401 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1402 if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
1403 sandbox_intern_string(conf_fname)))) {
1404 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1405 conf_fname, conf_fname, r);
1406 goto err;
1408 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1409 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1410 goto err;
1412 tor_free(resolv_conf_fname);
1413 resolv_conf_fname = tor_strdup(conf_fname);
1414 resolv_conf_mtime = st.st_mtime;
1415 if (nameservers_configured)
1416 evdns_base_resume(the_evdns_base);
1418 #ifdef _WIN32
1419 else {
1420 if (nameservers_configured) {
1421 evdns_base_search_clear(the_evdns_base);
1422 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1424 if (evdns_base_config_windows_nameservers(the_evdns_base)) {
1425 log_warn(LD_EXIT,"Could not config nameservers.");
1426 goto err;
1428 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1429 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1430 "your Windows configuration.");
1431 goto err;
1433 if (nameservers_configured)
1434 evdns_base_resume(the_evdns_base);
1435 tor_free(resolv_conf_fname);
1436 resolv_conf_mtime = 0;
1438 #endif /* defined(_WIN32) */
1440 #define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
1442 // If we only have one nameserver, it does not make sense to back off
1443 // from it for a timeout. Unfortunately, the value for max-timeouts is
1444 // currently clamped by libevent to 255, but it does not hurt to set
1445 // it higher in case libevent gets a patch for this. Higher-than-
1446 // default maximum of 3 with multiple nameservers to avoid spuriously
1447 // marking one down on bursts of timeouts resulting from scans/attacks
1448 // against non-responding authoritative DNS servers.
1449 if (evdns_base_count_nameservers(the_evdns_base) == 1) {
1450 SET("max-timeouts:", "1000000");
1451 } else {
1452 SET("max-timeouts:", "10");
1455 // Elongate the queue of maximum inflight dns requests, so if a bunch
1456 // remain pending at the resolver (happens commonly with Unbound) we won't
1457 // stall every other DNS request. This potentially means some wasted
1458 // CPU as there's a walk over a linear queue involved, but this is a
1459 // much better tradeoff compared to just failing DNS requests because
1460 // of a full queue.
1461 SET("max-inflight:", "8192");
1463 // Two retries at 5 and 10 seconds for bind9/named which relies on
1464 // clients to handle retries. Second retry for retried circuits with
1465 // extended 15 second timeout. Superfluous with local-system Unbound
1466 // instance--has its own elaborate retry scheme.
1467 SET("timeout:", "5");
1468 SET("attempts:","3");
1470 if (options->ServerDNSRandomizeCase)
1471 SET("randomize-case:", "1");
1472 else
1473 SET("randomize-case:", "0");
1475 #undef SET
1477 dns_servers_relaunch_checks();
1479 nameservers_configured = 1;
1480 if (nameserver_config_failed) {
1481 nameserver_config_failed = 0;
1482 /* XXX the three calls to republish the descriptor might be producing
1483 * descriptors that are only cosmetically different, especially on
1484 * non-exit relays! -RD */
1485 mark_my_descriptor_dirty("dns resolvers back");
1487 return 0;
1488 err:
1489 nameservers_configured = 0;
1490 if (! nameserver_config_failed) {
1491 nameserver_config_failed = 1;
1492 mark_my_descriptor_dirty("dns resolvers failed");
1494 return -1;
1497 /** For eventdns: Called when we get an answer for a request we launched.
1498 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1500 static void
1501 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1502 void *arg)
1504 char *arg_ = arg;
1505 uint8_t orig_query_type = arg_[0];
1506 char *string_address = arg_ + 1;
1507 tor_addr_t addr;
1508 const char *hostname = NULL;
1509 int was_wildcarded = 0;
1511 tor_addr_make_unspec(&addr);
1513 /* Keep track of whether IPv6 is working */
1514 if (type == DNS_IPv6_AAAA) {
1515 if (result == DNS_ERR_TIMEOUT) {
1516 ++n_ipv6_timeouts;
1519 if (n_ipv6_timeouts > 10 &&
1520 n_ipv6_timeouts > n_ipv6_requests_made / 2) {
1521 if (! dns_is_broken_for_ipv6) {
1522 log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
1523 "have timed out. I'm going to assume I can't get AAAA "
1524 "responses.");
1525 dns_is_broken_for_ipv6 = 1;
1530 if (result == DNS_ERR_NONE) {
1531 if (type == DNS_IPv4_A && count) {
1532 char answer_buf[INET_NTOA_BUF_LEN+1];
1533 char *escaped_address;
1534 uint32_t *addrs = addresses;
1535 tor_addr_from_ipv4n(&addr, addrs[0]);
1537 tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
1538 escaped_address = esc_for_log(string_address);
1540 if (answer_is_wildcarded(answer_buf)) {
1541 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1542 "address %s; treating as a failure.",
1543 safe_str(escaped_address),
1544 escaped_safe_str(answer_buf));
1545 was_wildcarded = 1;
1546 tor_addr_make_unspec(&addr);
1547 result = DNS_ERR_NOTEXIST;
1548 } else {
1549 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1550 safe_str(escaped_address),
1551 escaped_safe_str(answer_buf));
1553 tor_free(escaped_address);
1554 } else if (type == DNS_IPv6_AAAA && count) {
1555 char answer_buf[TOR_ADDR_BUF_LEN];
1556 char *escaped_address;
1557 struct in6_addr *addrs = addresses;
1558 tor_addr_from_in6(&addr, &addrs[0]);
1559 tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
1560 escaped_address = esc_for_log(string_address);
1562 if (answer_is_wildcarded(answer_buf)) {
1563 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1564 "address %s; treating as a failure.",
1565 safe_str(escaped_address),
1566 escaped_safe_str(answer_buf));
1567 was_wildcarded = 1;
1568 tor_addr_make_unspec(&addr);
1569 result = DNS_ERR_NOTEXIST;
1570 } else {
1571 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1572 safe_str(escaped_address),
1573 escaped_safe_str(answer_buf));
1575 tor_free(escaped_address);
1576 } else if (type == DNS_PTR && count) {
1577 char *escaped_address;
1578 hostname = ((char**)addresses)[0];
1579 escaped_address = esc_for_log(string_address);
1580 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1581 safe_str(escaped_address),
1582 escaped_safe_str(hostname));
1583 tor_free(escaped_address);
1584 } else if (count) {
1585 log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
1586 " for %s.",
1587 escaped_safe_str(string_address));
1588 } else {
1589 log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
1590 escaped_safe_str(string_address));
1593 if (was_wildcarded) {
1594 if (is_test_address(string_address)) {
1595 /* Ick. We're getting redirected on known-good addresses. Our DNS
1596 * server must really hate us. */
1597 add_wildcarded_test_address(string_address);
1601 if (orig_query_type && type && orig_query_type != type) {
1602 log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
1603 (int)orig_query_type, (int)type);
1605 if (result != DNS_ERR_SHUTDOWN)
1606 dns_found_answer(string_address, orig_query_type,
1607 result, &addr, hostname, ttl);
1609 tor_free(arg_);
1612 /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
1613 * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
1614 * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
1615 static int
1616 launch_one_resolve(const char *address, uint8_t query_type,
1617 const tor_addr_t *ptr_address)
1619 const int options = get_options()->ServerDNSSearchDomains ? 0
1620 : DNS_QUERY_NO_SEARCH;
1621 const size_t addr_len = strlen(address);
1622 struct evdns_request *req = 0;
1623 char *addr = tor_malloc(addr_len + 2);
1624 addr[0] = (char) query_type;
1625 memcpy(addr+1, address, addr_len + 1);
1627 switch (query_type) {
1628 case DNS_IPv4_A:
1629 req = evdns_base_resolve_ipv4(the_evdns_base,
1630 address, options, evdns_callback, addr);
1631 break;
1632 case DNS_IPv6_AAAA:
1633 req = evdns_base_resolve_ipv6(the_evdns_base,
1634 address, options, evdns_callback, addr);
1635 ++n_ipv6_requests_made;
1636 break;
1637 case DNS_PTR:
1638 if (tor_addr_family(ptr_address) == AF_INET)
1639 req = evdns_base_resolve_reverse(the_evdns_base,
1640 tor_addr_to_in(ptr_address),
1641 DNS_QUERY_NO_SEARCH,
1642 evdns_callback, addr);
1643 else if (tor_addr_family(ptr_address) == AF_INET6)
1644 req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
1645 tor_addr_to_in6(ptr_address),
1646 DNS_QUERY_NO_SEARCH,
1647 evdns_callback, addr);
1648 else
1649 log_warn(LD_BUG, "Called with PTR query and unexpected address family");
1650 break;
1651 default:
1652 log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
1653 break;
1656 if (req) {
1657 return 0;
1658 } else {
1659 tor_free(addr);
1660 return -1;
1664 /** For eventdns: start resolving as necessary to find the target for
1665 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1666 * 0 on "resolve launched." */
1667 MOCK_IMPL(STATIC int,
1668 launch_resolve,(cached_resolve_t *resolve))
1670 tor_addr_t a;
1671 int r;
1673 if (net_is_disabled())
1674 return -1;
1676 /* What? Nameservers not configured? Sounds like a bug. */
1677 if (!nameservers_configured) {
1678 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1679 "launched. Configuring.");
1680 if (configure_nameservers(1) < 0) {
1681 return -1;
1685 r = tor_addr_parse_PTR_name(
1686 &a, resolve->address, AF_UNSPEC, 0);
1688 tor_assert(the_evdns_base);
1689 if (r == 0) {
1690 log_info(LD_EXIT, "Launching eventdns request for %s",
1691 escaped_safe_str(resolve->address));
1692 resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
1693 if (get_options()->IPv6Exit)
1694 resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
1696 if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
1697 resolve->res_status_ipv4 = 0;
1698 r = -1;
1701 if (r==0 && get_options()->IPv6Exit) {
1702 /* We ask for an IPv6 address for *everything*. */
1703 if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
1704 resolve->res_status_ipv6 = 0;
1705 r = -1;
1708 } else if (r == 1) {
1709 r = 0;
1710 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1711 escaped_safe_str(resolve->address));
1712 resolve->res_status_hostname = RES_STATUS_INFLIGHT;
1713 if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
1714 resolve->res_status_hostname = 0;
1715 r = -1;
1717 } else if (r == -1) {
1718 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1721 if (r < 0) {
1722 log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
1723 escaped_safe_str(resolve->address));
1725 return r;
1728 /** How many requests for bogus addresses have we launched so far? */
1729 static int n_wildcard_requests = 0;
1731 /** Map from dotted-quad IP address in response to an int holding how many
1732 * times we've seen it for a randomly generated (hopefully bogus) address. It
1733 * would be easier to use definitely-invalid addresses (as specified by
1734 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1735 static strmap_t *dns_wildcard_response_count = NULL;
1737 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1738 * nameserver wants to return in response to requests for nonexistent domains.
1740 static smartlist_t *dns_wildcard_list = NULL;
1741 /** True iff we've logged about a single address getting wildcarded.
1742 * Subsequent warnings will be less severe. */
1743 static int dns_wildcard_one_notice_given = 0;
1744 /** True iff we've warned that our DNS server is wildcarding too many failures.
1746 static int dns_wildcard_notice_given = 0;
1748 /** List of supposedly good addresses that are getting wildcarded to the
1749 * same addresses as nonexistent addresses. */
1750 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1751 /** True iff we've warned about a test address getting wildcarded */
1752 static int dns_wildcarded_test_address_notice_given = 0;
1753 /** True iff all addresses seem to be getting wildcarded. */
1754 static int dns_is_completely_invalid = 0;
1756 /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
1757 * to a request for a hopefully bogus address. */
1758 static void
1759 wildcard_increment_answer(const char *id)
1761 int *ip;
1762 if (!dns_wildcard_response_count)
1763 dns_wildcard_response_count = strmap_new();
1765 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1766 if (!ip) {
1767 ip = tor_malloc_zero(sizeof(int));
1768 strmap_set(dns_wildcard_response_count, id, ip);
1770 ++*ip;
1772 if (*ip > 5 && n_wildcard_requests > 10) {
1773 if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
1774 if (!smartlist_contains_string(dns_wildcard_list, id)) {
1775 tor_log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1776 "Your DNS provider has given \"%s\" as an answer for %d different "
1777 "invalid addresses. Apparently they are hijacking DNS failures. "
1778 "I'll try to correct for this by treating future occurrences of "
1779 "\"%s\" as 'not found'.", id, *ip, id);
1780 smartlist_add_strdup(dns_wildcard_list, id);
1782 if (!dns_wildcard_notice_given)
1783 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1784 dns_wildcard_notice_given = 1;
1788 /** Note that a single test address (one believed to be good) seems to be
1789 * getting redirected to the same IP as failures are. */
1790 static void
1791 add_wildcarded_test_address(const char *address)
1793 int n, n_test_addrs;
1794 if (!dns_wildcarded_test_address_list)
1795 dns_wildcarded_test_address_list = smartlist_new();
1797 if (smartlist_contains_string_case(dns_wildcarded_test_address_list,
1798 address))
1799 return;
1801 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1802 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1804 smartlist_add_strdup(dns_wildcarded_test_address_list, address);
1805 n = smartlist_len(dns_wildcarded_test_address_list);
1806 if (n > n_test_addrs/2) {
1807 tor_log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1808 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1809 "address. It has done this with %d test addresses so far. I'm "
1810 "going to stop being an exit node for now, since our DNS seems so "
1811 "broken.", address, n);
1812 if (!dns_is_completely_invalid) {
1813 dns_is_completely_invalid = 1;
1814 mark_my_descriptor_dirty("dns hijacking confirmed");
1816 if (!dns_wildcarded_test_address_notice_given)
1817 control_event_server_status(LOG_WARN, "DNS_USELESS");
1818 dns_wildcarded_test_address_notice_given = 1;
1822 /** Callback function when we get an answer (possibly failing) for a request
1823 * for a (hopefully) nonexistent domain. */
1824 static void
1825 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1826 void *addresses, void *arg)
1828 (void)ttl;
1829 ++n_wildcard_requests;
1830 if (result == DNS_ERR_NONE && count) {
1831 char *string_address = arg;
1832 int i;
1833 if (type == DNS_IPv4_A) {
1834 const uint32_t *addrs = addresses;
1835 for (i = 0; i < count; ++i) {
1836 char answer_buf[INET_NTOA_BUF_LEN+1];
1837 struct in_addr in;
1838 in.s_addr = addrs[i];
1839 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1840 wildcard_increment_answer(answer_buf);
1842 } else if (type == DNS_IPv6_AAAA) {
1843 const struct in6_addr *addrs = addresses;
1844 for (i = 0; i < count; ++i) {
1845 char answer_buf[TOR_ADDR_BUF_LEN+1];
1846 tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
1847 wildcard_increment_answer(answer_buf);
1851 tor_log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1852 "Your DNS provider gave an answer for \"%s\", which "
1853 "is not supposed to exist. Apparently they are hijacking "
1854 "DNS failures. Trying to correct for this. We've noticed %d "
1855 "possibly bad address%s so far.",
1856 string_address, strmap_size(dns_wildcard_response_count),
1857 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1858 dns_wildcard_one_notice_given = 1;
1860 tor_free(arg);
1863 /** Launch a single request for a nonexistent hostname consisting of between
1864 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1865 * <b>suffix</b> */
1866 static void
1867 launch_wildcard_check(int min_len, int max_len, int is_ipv6,
1868 const char *suffix)
1870 char *addr;
1871 struct evdns_request *req;
1873 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1874 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1875 "domains with request for bogus hostname \"%s\"", addr);
1877 tor_assert(the_evdns_base);
1878 if (is_ipv6)
1879 req = evdns_base_resolve_ipv6(
1880 the_evdns_base,
1881 /* This "addr" tells us which address to resolve */
1882 addr,
1883 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1884 /* This "addr" is an argument to the callback*/ addr);
1885 else
1886 req = evdns_base_resolve_ipv4(
1887 the_evdns_base,
1888 /* This "addr" tells us which address to resolve */
1889 addr,
1890 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1891 /* This "addr" is an argument to the callback*/ addr);
1892 if (!req) {
1893 /* There is no evdns request in progress; stop addr from getting leaked */
1894 tor_free(addr);
1898 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1899 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1900 static void
1901 launch_test_addresses(evutil_socket_t fd, short event, void *args)
1903 const or_options_t *options = get_options();
1904 (void)fd;
1905 (void)event;
1906 (void)args;
1908 if (net_is_disabled())
1909 return;
1911 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1912 "hijack *everything*.");
1913 /* This situation is worse than the failure-hijacking situation. When this
1914 * happens, we're no good for DNS requests at all, and we shouldn't really
1915 * be an exit server.*/
1916 if (options->ServerDNSTestAddresses) {
1918 tor_assert(the_evdns_base);
1919 SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
1920 const char *, address) {
1921 if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
1922 log_info(LD_EXIT, "eventdns rejected test address %s",
1923 escaped_safe_str(address));
1926 if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
1927 log_info(LD_EXIT, "eventdns rejected test address %s",
1928 escaped_safe_str(address));
1930 } SMARTLIST_FOREACH_END(address);
1934 #define N_WILDCARD_CHECKS 2
1936 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1937 * hostnames, and see if we can catch our nameserver trying to hijack them and
1938 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1939 * buy these lovely encyclopedias" page. */
1940 static void
1941 dns_launch_wildcard_checks(void)
1943 int i, ipv6;
1944 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1945 "to hijack DNS failures.");
1946 for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
1947 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1948 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
1949 * attempt to 'comply' with rfc2606, refrain from giving A records for
1950 * these. This is the standards-compliance equivalent of making sure
1951 * that your crackhouse's elevator inspection certificate is up to date.
1953 launch_wildcard_check(2, 16, ipv6, ".invalid");
1954 launch_wildcard_check(2, 16, ipv6, ".test");
1956 /* These will break specs if there are ever any number of
1957 * 8+-character top-level domains. */
1958 launch_wildcard_check(8, 16, ipv6, "");
1960 /* Try some random .com/org/net domains. This will work fine so long as
1961 * not too many resolve to the same place. */
1962 launch_wildcard_check(8, 16, ipv6, ".com");
1963 launch_wildcard_check(8, 16, ipv6, ".org");
1964 launch_wildcard_check(8, 16, ipv6, ".net");
1969 /** If appropriate, start testing whether our DNS servers tend to lie to
1970 * us. */
1971 void
1972 dns_launch_correctness_checks(void)
1974 static struct event *launch_event = NULL;
1975 struct timeval timeout;
1976 if (!get_options()->ServerDNSDetectHijacking)
1977 return;
1978 dns_launch_wildcard_checks();
1980 /* Wait a while before launching requests for test addresses, so we can
1981 * get the results from checking for wildcarding. */
1982 if (! launch_event)
1983 launch_event = tor_evtimer_new(tor_libevent_get_base(),
1984 launch_test_addresses, NULL);
1985 timeout.tv_sec = 30;
1986 timeout.tv_usec = 0;
1987 if (evtimer_add(launch_event, &timeout)<0) {
1988 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1992 /** Return true iff our DNS servers lie to us too much to be trusted. */
1994 dns_seems_to_be_broken(void)
1996 return dns_is_completely_invalid;
1999 /** Return true iff we think that IPv6 hostname lookup is broken */
2001 dns_seems_to_be_broken_for_ipv6(void)
2003 return dns_is_broken_for_ipv6;
2006 /** Forget what we've previously learned about our DNS servers' correctness. */
2007 void
2008 dns_reset_correctness_checks(void)
2010 strmap_free(dns_wildcard_response_count, tor_free_);
2011 dns_wildcard_response_count = NULL;
2013 n_wildcard_requests = 0;
2015 n_ipv6_requests_made = n_ipv6_timeouts = 0;
2017 if (dns_wildcard_list) {
2018 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
2019 smartlist_clear(dns_wildcard_list);
2021 if (dns_wildcarded_test_address_list) {
2022 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
2023 tor_free(cp));
2024 smartlist_clear(dns_wildcarded_test_address_list);
2026 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
2027 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
2028 dns_is_broken_for_ipv6 = 0;
2031 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
2032 * returned in response to requests for nonexistent hostnames. */
2033 static int
2034 answer_is_wildcarded(const char *ip)
2036 return dns_wildcard_list && smartlist_contains_string(dns_wildcard_list, ip);
2039 /** Exit with an assertion if <b>resolve</b> is corrupt. */
2040 static void
2041 assert_resolve_ok(cached_resolve_t *resolve)
2043 tor_assert(resolve);
2044 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
2045 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
2046 tor_assert(tor_strisnonupper(resolve->address));
2047 if (resolve->state != CACHE_STATE_PENDING) {
2048 tor_assert(!resolve->pending_connections);
2050 if (resolve->state == CACHE_STATE_PENDING ||
2051 resolve->state == CACHE_STATE_DONE) {
2052 #if 0
2053 tor_assert(!resolve->ttl);
2054 if (resolve->is_reverse)
2055 tor_assert(!resolve->hostname);
2056 else
2057 tor_assert(!resolve->result_ipv4.addr_ipv4);
2058 #endif /* 0 */
2059 /*XXXXX ADD MORE */
2063 /** Return the number of DNS cache entries as an int */
2064 static int
2065 dns_cache_entry_count(void)
2067 return HT_SIZE(&cache_root);
2070 /** Log memory information about our internal DNS cache at level 'severity'. */
2071 void
2072 dump_dns_mem_usage(int severity)
2074 /* This should never be larger than INT_MAX. */
2075 int hash_count = dns_cache_entry_count();
2076 size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
2077 hash_mem += HT_MEM_USAGE(&cache_root);
2079 /* Print out the count and estimated size of our &cache_root. It undercounts
2080 hostnames in cached reverse resolves.
2082 tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
2083 tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
2084 (unsigned)hash_mem);
2087 #ifdef DEBUG_DNS_CACHE
2088 /** Exit with an assertion if the DNS cache is corrupt. */
2089 static void
2090 assert_cache_ok_(void)
2092 cached_resolve_t **resolve;
2093 int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
2094 if (bad_rep) {
2095 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
2096 tor_assert(!bad_rep);
2099 HT_FOREACH(resolve, cache_map, &cache_root) {
2100 assert_resolve_ok(*resolve);
2101 tor_assert((*resolve)->state != CACHE_STATE_DONE);
2103 if (!cached_resolve_pqueue)
2104 return;
2106 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
2107 compare_cached_resolves_by_expiry_,
2108 offsetof(cached_resolve_t, minheap_idx));
2110 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
2112 if (res->state == CACHE_STATE_DONE) {
2113 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2114 tor_assert(!found || found != res);
2115 } else {
2116 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2117 tor_assert(found);
2122 #endif /* defined(DEBUG_DNS_CACHE) */
2124 cached_resolve_t *
2125 dns_get_cache_entry(cached_resolve_t *query)
2127 return HT_FIND(cache_map, &cache_root, query);
2130 void
2131 dns_insert_cache_entry(cached_resolve_t *new_entry)
2133 HT_INSERT(cache_map, &cache_root, new_entry);