Use the literal parse of an address in dns_resolve_impl if parsing the address as...
[tor/rransom.git] / src / or / dns.c
blobfe77a76d7b3cc74c41548fb65982e00adcf2c378
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 */
5 /* $Id$ */
6 const char dns_c_id[] =
7 "$Id$";
9 /**
10 * \file dns.c
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
14 * be nonblocking.)
15 **/
17 #include "or.h"
18 #include "ht.h"
19 #include "eventdns.h"
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 /** Did our most recent attempt to configure nameservers with eventdns fail? */
37 static int nameserver_config_failed = 0;
38 /** What was the resolv_conf fname we last used when configuring the
39 * nameservers? Used to check whether we need to reconfigure. */
40 static char *resolv_conf_fname = NULL;
41 /** What was the mtime on the resolv.conf file we last used when configuring
42 * the nameservers? Used to check whether we need to reconfigure. */
43 static time_t resolv_conf_mtime = 0;
45 /** Linked list of connections waiting for a DNS answer. */
46 typedef struct pending_connection_t {
47 edge_connection_t *conn;
48 struct pending_connection_t *next;
49 } pending_connection_t;
51 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
52 * pointers and memory stomping. */
53 #define CACHED_RESOLVE_MAGIC 0x1234F00D
55 /* Possible states for a cached resolve_t */
56 /** We are waiting for the resolver system to tell us an answer here.
57 * When we get one, or when we time out, the state of this cached_resolve_t
58 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
59 * entry. This cached_resolve_t will be in the hash table so that we will
60 * know not to launch more requests for this addr, but rather to add more
61 * connections to the pending list for the addr. */
62 #define CACHE_STATE_PENDING 0
63 /** This used to be a pending cached_resolve_t, and we got an answer for it.
64 * Now we're waiting for this cached_resolve_t to expire. This should
65 * have no pending connections, and should not appear in the hash table. */
66 #define CACHE_STATE_DONE 1
67 /** We are caching an answer for this address. This should have no pending
68 * connections, and should appear in the hash table. */
69 #define CACHE_STATE_CACHED_VALID 2
70 /** We are caching a failure for this address. This should have no pending
71 * connections, and should appear in the hash table */
72 #define CACHE_STATE_CACHED_FAILED 3
74 /** A DNS request: possibly completed, possibly pending; cached_resolve
75 * structs are stored at the OR side in a hash table, and as a linked
76 * list from oldest to newest.
78 typedef struct cached_resolve_t {
79 HT_ENTRY(cached_resolve_t) node;
80 uint32_t magic;
81 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
82 union {
83 struct {
84 struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
85 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
86 } a;
87 char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
88 } result;
89 uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
90 uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
91 time_t expire; /**< Remove items from cache after this time. */
92 uint32_t ttl; /**< What TTL did the nameserver tell us? */
93 /** Connections that want to know when we get an answer for this resolve. */
94 pending_connection_t *pending_connections;
95 } cached_resolve_t;
97 static void purge_expired_resolves(time_t now);
98 static void dns_found_answer(const char *address, uint8_t is_reverse,
99 uint32_t addr, const char *hostname, char outcome,
100 uint32_t ttl);
101 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
102 static int launch_resolve(edge_connection_t *exitconn);
103 static void add_wildcarded_test_address(const char *address);
104 static int configure_nameservers(int force);
105 static int answer_is_wildcarded(const char *ip);
106 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
107 or_circuit_t *oncirc, char **resolved_to_hostname);
108 #ifdef DEBUG_DNS_CACHE
109 static void _assert_cache_ok(void);
110 #define assert_cache_ok() _assert_cache_ok()
111 #else
112 #define assert_cache_ok() STMT_NIL
113 #endif
114 static void assert_resolve_ok(cached_resolve_t *resolve);
116 /** Hash table of cached_resolve objects. */
117 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
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 ht_string_hash(a->address);
136 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
137 cached_resolves_eq)
138 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
139 cached_resolves_eq, 0.6, malloc, realloc, 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(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 *err = strchr(cp, ':')+2;
165 tor_assert(err);
166 /* Don't warn about a single failed nameserver; we'll warn with 'all
167 * nameservers have failed' if we're completely out of nameservers;
168 * otherwise, the situation is tolerable. */
169 severity = LOG_INFO;
170 control_event_server_status(LOG_NOTICE,
171 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
172 ns, escaped(err));
173 tor_free(ns);
174 } else if (!strcmpstart(msg, "Nameserver ") &&
175 (cp=strstr(msg, " is back up"))) {
176 char *ns = tor_strndup(msg+11, cp-(msg+11));
177 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
178 all_down = 0;
179 control_event_server_status(LOG_NOTICE,
180 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
181 tor_free(ns);
182 } else if (!strcmp(msg, "All nameservers have failed")) {
183 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
184 all_down = 1;
186 log(severity, LD_EXIT, "eventdns: %s", msg);
189 /** Helper: passed to eventdns.c as a callback so it can generate random
190 * numbers for transaction IDs and 0x20-hack coding. */
191 static void
192 _dns_randfn(char *b, size_t n)
194 crypto_rand(b,n);
197 /** Initialize the DNS subsystem; called by the OR process. */
199 dns_init(void)
201 init_cache_map();
202 evdns_set_random_bytes_fn(_dns_randfn);
203 if (get_options()->ServerDNSRandomizeCase)
204 evdns_set_option("randomize-case", "1", DNS_OPTIONS_ALL);
205 else
206 evdns_set_option("randomize-case", "0", DNS_OPTIONS_ALL);
207 if (server_mode(get_options())) {
208 int r = configure_nameservers(1);
209 return r;
211 return 0;
214 /** Called when DNS-related options change (or may have changed). Returns -1
215 * on failure, 0 on success. */
217 dns_reset(void)
219 or_options_t *options = get_options();
220 if (! server_mode(options)) {
221 evdns_clear_nameservers_and_suspend();
222 evdns_search_clear();
223 nameservers_configured = 0;
224 tor_free(resolv_conf_fname);
225 resolv_conf_mtime = 0;
226 } else {
227 if (configure_nameservers(0) < 0) {
228 return -1;
231 return 0;
234 /** Return true iff the most recent attempt to initialize the DNS subsystem
235 * failed. */
237 has_dns_init_failed(void)
239 return nameserver_config_failed;
242 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
243 * OP that asked us to resolve it. */
244 uint32_t
245 dns_clip_ttl(uint32_t ttl)
247 if (ttl < MIN_DNS_TTL)
248 return MIN_DNS_TTL;
249 else if (ttl > MAX_DNS_TTL)
250 return MAX_DNS_TTL;
251 else
252 return ttl;
255 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
256 * our cache. */
257 static uint32_t
258 dns_get_expiry_ttl(uint32_t ttl)
260 if (ttl < MIN_DNS_TTL)
261 return MIN_DNS_TTL;
262 else if (ttl > MAX_DNS_ENTRY_AGE)
263 return MAX_DNS_ENTRY_AGE;
264 else
265 return ttl;
268 /** Helper: free storage held by an entry in the DNS cache. */
269 static void
270 _free_cached_resolve(cached_resolve_t *r)
272 while (r->pending_connections) {
273 pending_connection_t *victim = r->pending_connections;
274 r->pending_connections = victim->next;
275 tor_free(victim);
277 if (r->is_reverse)
278 tor_free(r->result.hostname);
279 r->magic = 0xFF00FF00;
280 tor_free(r);
283 /** Compare two cached_resolve_t pointers by expiry time, and return
284 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
285 * the priority queue implementation. */
286 static int
287 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
289 const cached_resolve_t *a = _a, *b = _b;
290 if (a->expire < b->expire)
291 return -1;
292 else if (a->expire == b->expire)
293 return 0;
294 else
295 return 1;
298 /** Priority queue of cached_resolve_t objects to let us know when they
299 * will expire. */
300 static smartlist_t *cached_resolve_pqueue = NULL;
302 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
303 * priority queue */
304 static void
305 set_expiry(cached_resolve_t *resolve, time_t expires)
307 tor_assert(resolve && resolve->expire == 0);
308 if (!cached_resolve_pqueue)
309 cached_resolve_pqueue = smartlist_create();
310 resolve->expire = expires;
311 smartlist_pqueue_add(cached_resolve_pqueue,
312 _compare_cached_resolves_by_expiry,
313 resolve);
316 /** Free all storage held in the DNS cache and related structures. */
317 void
318 dns_free_all(void)
320 cached_resolve_t **ptr, **next, *item;
321 assert_cache_ok();
322 if (cached_resolve_pqueue) {
323 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
325 if (res->state == CACHE_STATE_DONE)
326 _free_cached_resolve(res);
329 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
330 item = *ptr;
331 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
332 _free_cached_resolve(item);
334 HT_CLEAR(cache_map, &cache_root);
335 if (cached_resolve_pqueue)
336 smartlist_free(cached_resolve_pqueue);
337 cached_resolve_pqueue = NULL;
338 tor_free(resolv_conf_fname);
341 /** Remove every cached_resolve whose <b>expire</b> time is before or
342 * equal to <b>now</b> from the cache. */
343 static void
344 purge_expired_resolves(time_t now)
346 cached_resolve_t *resolve, *removed;
347 pending_connection_t *pend;
348 edge_connection_t *pendconn;
350 assert_cache_ok();
351 if (!cached_resolve_pqueue)
352 return;
354 while (smartlist_len(cached_resolve_pqueue)) {
355 resolve = smartlist_get(cached_resolve_pqueue, 0);
356 if (resolve->expire > now)
357 break;
358 smartlist_pqueue_pop(cached_resolve_pqueue,
359 _compare_cached_resolves_by_expiry);
361 if (resolve->state == CACHE_STATE_PENDING) {
362 log_debug(LD_EXIT,
363 "Expiring a dns resolve %s that's still pending. Forgot to "
364 "cull it? DNS resolve didn't tell us about the timeout?",
365 escaped_safe_str(resolve->address));
366 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
367 resolve->state == CACHE_STATE_CACHED_FAILED) {
368 log_debug(LD_EXIT,
369 "Forgetting old cached resolve (address %s, expires %lu)",
370 escaped_safe_str(resolve->address),
371 (unsigned long)resolve->expire);
372 tor_assert(!resolve->pending_connections);
373 } else {
374 tor_assert(resolve->state == CACHE_STATE_DONE);
375 tor_assert(!resolve->pending_connections);
378 if (resolve->pending_connections) {
379 log_debug(LD_EXIT,
380 "Closing pending connections on timed-out DNS resolve!");
381 tor_fragile_assert();
382 while (resolve->pending_connections) {
383 pend = resolve->pending_connections;
384 resolve->pending_connections = pend->next;
385 /* Connections should only be pending if they have no socket. */
386 tor_assert(pend->conn->_base.s == -1);
387 pendconn = pend->conn;
388 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
389 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
390 connection_free(TO_CONN(pendconn));
391 tor_free(pend);
395 if (resolve->state == CACHE_STATE_CACHED_VALID ||
396 resolve->state == CACHE_STATE_CACHED_FAILED ||
397 resolve->state == CACHE_STATE_PENDING) {
398 removed = HT_REMOVE(cache_map, &cache_root, resolve);
399 if (removed != resolve) {
400 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
401 " the cache. Tried to purge %s (%p); instead got %s (%p).",
402 resolve->address, (void*)resolve,
403 removed ? removed->address : "NULL", (void*)remove);
405 tor_assert(removed == resolve);
406 } else {
407 /* This should be in state DONE. Make sure it's not in the cache. */
408 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
409 tor_assert(tmp != resolve);
411 if (resolve->is_reverse)
412 tor_free(resolve->result.hostname);
413 resolve->magic = 0xF0BBF0BB;
414 tor_free(resolve);
417 assert_cache_ok();
420 /** Send a response to the RESOLVE request of a connection.
421 * <b>answer_type</b> must be one of
422 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
424 * If <b>circ</b> is provided, and we have a cached answer, send the
425 * answer back along circ; otherwise, send the answer back along
426 * <b>conn</b>'s attached circuit.
428 static void
429 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
431 char buf[RELAY_PAYLOAD_SIZE];
432 size_t buflen;
433 uint32_t ttl;
435 buf[0] = answer_type;
436 ttl = dns_clip_ttl(conn->address_ttl);
438 switch (answer_type)
440 case RESOLVED_TYPE_IPV4:
441 buf[1] = 4;
442 set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
443 set_uint32(buf+6, htonl(ttl));
444 buflen = 10;
445 break;
446 /*XXXX IP6 need ipv6 implementation */
447 case RESOLVED_TYPE_ERROR_TRANSIENT:
448 case RESOLVED_TYPE_ERROR:
450 const char *errmsg = "Error resolving hostname";
451 size_t msglen = strlen(errmsg);
453 buf[1] = msglen;
454 strlcpy(buf+2, errmsg, sizeof(buf)-2);
455 set_uint32(buf+2+msglen, htonl(ttl));
456 buflen = 6+msglen;
457 break;
459 default:
460 tor_assert(0);
461 return;
463 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
465 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
468 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
469 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
470 * The answer type will be RESOLVED_HOSTNAME.
472 * If <b>circ</b> is provided, and we have a cached answer, send the
473 * answer back along circ; otherwise, send the answer back along
474 * <b>conn</b>'s attached circuit.
476 static void
477 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
479 char buf[RELAY_PAYLOAD_SIZE];
480 size_t buflen;
481 uint32_t ttl;
482 size_t namelen = strlen(hostname);
483 tor_assert(hostname);
485 tor_assert(namelen < 256);
486 ttl = dns_clip_ttl(conn->address_ttl);
488 buf[0] = RESOLVED_TYPE_HOSTNAME;
489 buf[1] = (uint8_t)namelen;
490 memcpy(buf+2, hostname, namelen);
491 set_uint32(buf+2+namelen, htonl(ttl));
492 buflen = 2+namelen+4;
494 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
495 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
496 // log_notice(LD_EXIT, "Sent");
499 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
500 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
501 * If resolve failed, free exitconn and return -1.
503 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
504 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
505 * need to send back an END cell, since connection_exit_begin_conn will
506 * do that for us.)
508 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
509 * circuit.
511 * Else, if seen before and pending, add conn to the pending list,
512 * and return 0.
514 * Else, if not seen before, add conn to pending list, hand to
515 * dns farm, and return 0.
517 * Exitconn's on_circuit field must be set, but exitconn should not
518 * yet be linked onto the n_streams/resolving_streams list of that circuit.
519 * On success, link the connection to n_streams if it's an exit connection.
520 * On "pending", link the connection to resolving streams. Otherwise,
521 * clear its on_circuit field.
524 dns_resolve(edge_connection_t *exitconn)
526 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
527 int is_resolve, r;
528 char *hostname = NULL;
529 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
531 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
533 switch (r) {
534 case 1:
535 /* We got an answer without a lookup -- either the answer was
536 * cached, or it was obvious (like an IP address). */
537 if (is_resolve) {
538 /* Send the answer back right now, and detach. */
539 if (hostname)
540 send_resolved_hostname_cell(exitconn, hostname);
541 else
542 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
543 exitconn->on_circuit = NULL;
544 } else {
545 /* Add to the n_streams list; the calling function will send back a
546 * connected cell. */
547 exitconn->next_stream = oncirc->n_streams;
548 oncirc->n_streams = exitconn;
550 break;
551 case 0:
552 /* The request is pending: add the connection into the linked list of
553 * resolving_streams on this circuit. */
554 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
555 exitconn->next_stream = oncirc->resolving_streams;
556 oncirc->resolving_streams = exitconn;
557 break;
558 case -2:
559 case -1:
560 /* The request failed before it could start: cancel this connection,
561 * and stop everybody waiting for the same connection. */
562 if (is_resolve) {
563 send_resolved_cell(exitconn,
564 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
567 exitconn->on_circuit = NULL;
569 dns_cancel_pending_resolve(exitconn->_base.address);
571 if (!exitconn->_base.marked_for_close) {
572 connection_free(TO_CONN(exitconn));
573 // XXX ... and we just leak exitconn otherwise? -RD
574 // If it's marked for close, it's on closeable_connection_lst in
575 // main.c. If it's on the closeable list, it will get freed from
576 // main.c. -NM
577 // "<armadev> If that's true, there are other bugs around, where we
578 // don't check if it's marked, and will end up double-freeing."
579 // On the other hand, I don't know of any actual bugs here, so this
580 // shouldn't be holding up the rc. -RD
582 break;
583 default:
584 tor_assert(0);
587 tor_free(hostname);
588 return r;
591 /** Helper function for dns_resolve: same functionality, but does not handle:
592 * - marking connections on error and clearing their on_circuit
593 * - linking connections to n_streams/resolving_streams,
594 * - sending resolved cells if we have an answer/error right away,
596 * Return -2 on a transient error. If it's a reverse resolve and it's
597 * successful, sets *<b>hostname_out</b> to a newly allocated string
598 * holding the cached reverse DNS value.
600 static int
601 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
602 or_circuit_t *oncirc, char **hostname_out)
604 cached_resolve_t *resolve;
605 cached_resolve_t search;
606 pending_connection_t *pending_connection;
607 routerinfo_t *me;
608 tor_addr_t addr;
609 time_t now = time(NULL);
610 uint8_t is_reverse = 0;
611 int r;
612 assert_connection_ok(TO_CONN(exitconn), 0);
613 tor_assert(exitconn->_base.s == -1);
614 assert_cache_ok();
615 tor_assert(oncirc);
617 /* first check if exitconn->_base.address is an IP. If so, we already
618 * know the answer. */
619 if (tor_addr_from_str(&addr, exitconn->_base.address) >= 0) {
620 tor_addr_assign(&exitconn->_base.addr, &addr);
621 exitconn->address_ttl = DEFAULT_DNS_TTL;
622 return 1;
624 /* If we're a non-exit, don't even do DNS lookups. */
625 if (!(me = router_get_my_routerinfo()) ||
626 policy_is_reject_star(me->exit_policy)) {
627 return -1;
629 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
630 log(LOG_PROTOCOL_WARN, LD_EXIT,
631 "Rejecting invalid destination address %s",
632 escaped_safe_str(exitconn->_base.address));
633 return -1;
636 /* then take this opportunity to see if there are any expired
637 * resolves in the hash table. */
638 purge_expired_resolves(now);
640 /* lower-case exitconn->_base.address, so it's in canonical form */
641 tor_strlower(exitconn->_base.address);
643 /* Check whether this is a reverse lookup. If it's malformed, or it's a
644 * .in-addr.arpa address but this isn't a resolve request, kill the
645 * connection.
647 if ((r = tor_addr_parse_reverse_lookup_name(&addr, exitconn->_base.address,
648 AF_UNSPEC, 0)) != 0) {
649 if (r == 1) {
650 is_reverse = 1;
651 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
652 return -1;
655 if (!is_reverse || !is_resolve) {
656 if (!is_reverse)
657 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
658 escaped_safe_str(exitconn->_base.address));
659 else if (!is_resolve)
660 log_info(LD_EXIT,
661 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
662 "sending error.",
663 escaped_safe_str(exitconn->_base.address));
665 return -1;
667 //log_notice(LD_EXIT, "Looks like an address %s",
668 //exitconn->_base.address);
671 /* now check the hash table to see if 'address' is already there. */
672 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
673 resolve = HT_FIND(cache_map, &cache_root, &search);
674 if (resolve && resolve->expire > now) { /* already there */
675 switch (resolve->state) {
676 case CACHE_STATE_PENDING:
677 /* add us to the pending list */
678 pending_connection = tor_malloc_zero(
679 sizeof(pending_connection_t));
680 pending_connection->conn = exitconn;
681 pending_connection->next = resolve->pending_connections;
682 resolve->pending_connections = pending_connection;
683 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
684 "resolve of %s", exitconn->_base.s,
685 escaped_safe_str(exitconn->_base.address));
686 return 0;
687 case CACHE_STATE_CACHED_VALID:
688 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
689 exitconn->_base.s,
690 escaped_safe_str(resolve->address));
691 exitconn->address_ttl = resolve->ttl;
692 if (resolve->is_reverse) {
693 tor_assert(is_resolve);
694 *hostname_out = tor_strdup(resolve->result.hostname);
695 } else {
696 tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
698 return 1;
699 case CACHE_STATE_CACHED_FAILED:
700 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
701 exitconn->_base.s,
702 escaped_safe_str(exitconn->_base.address));
703 return -1;
704 case CACHE_STATE_DONE:
705 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
706 tor_fragile_assert();
708 tor_assert(0);
710 tor_assert(!resolve);
711 /* not there, need to add it */
712 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
713 resolve->magic = CACHED_RESOLVE_MAGIC;
714 resolve->state = CACHE_STATE_PENDING;
715 resolve->is_reverse = is_reverse;
716 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
718 /* add this connection to the pending list */
719 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
720 pending_connection->conn = exitconn;
721 resolve->pending_connections = pending_connection;
723 /* Add this resolve to the cache and priority queue. */
724 HT_INSERT(cache_map, &cache_root, resolve);
725 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
727 log_debug(LD_EXIT,"Launching %s.",
728 escaped_safe_str(exitconn->_base.address));
729 assert_cache_ok();
731 return launch_resolve(exitconn);
734 /** Log an error and abort if conn is waiting for a DNS resolve.
736 void
737 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
739 pending_connection_t *pend;
740 cached_resolve_t **resolve;
742 HT_FOREACH(resolve, cache_map, &cache_root) {
743 for (pend = (*resolve)->pending_connections;
744 pend;
745 pend = pend->next) {
746 tor_assert(pend->conn != conn);
751 /** Log an error and abort if any connection waiting for a DNS resolve is
752 * corrupted. */
753 void
754 assert_all_pending_dns_resolves_ok(void)
756 pending_connection_t *pend;
757 cached_resolve_t **resolve;
759 HT_FOREACH(resolve, cache_map, &cache_root) {
760 for (pend = (*resolve)->pending_connections;
761 pend;
762 pend = pend->next) {
763 assert_connection_ok(TO_CONN(pend->conn), 0);
764 tor_assert(pend->conn->_base.s == -1);
765 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
770 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
772 void
773 connection_dns_remove(edge_connection_t *conn)
775 pending_connection_t *pend, *victim;
776 cached_resolve_t search;
777 cached_resolve_t *resolve;
779 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
780 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
782 strlcpy(search.address, conn->_base.address, sizeof(search.address));
784 resolve = HT_FIND(cache_map, &cache_root, &search);
785 if (!resolve) {
786 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
787 escaped_safe_str(conn->_base.address));
788 return;
791 tor_assert(resolve->pending_connections);
792 assert_connection_ok(TO_CONN(conn),0);
794 pend = resolve->pending_connections;
796 if (pend->conn == conn) {
797 resolve->pending_connections = pend->next;
798 tor_free(pend);
799 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
800 "for resolve of %s",
801 conn->_base.s, escaped_safe_str(conn->_base.address));
802 return;
803 } else {
804 for ( ; pend->next; pend = pend->next) {
805 if (pend->next->conn == conn) {
806 victim = pend->next;
807 pend->next = victim->next;
808 tor_free(victim);
809 log_debug(LD_EXIT,
810 "Connection (fd %d) no longer waiting for resolve of %s",
811 conn->_base.s, escaped_safe_str(conn->_base.address));
812 return; /* more are pending */
815 tor_assert(0); /* not reachable unless onlyconn not in pending list */
819 /** Mark all connections waiting for <b>address</b> for close. Then cancel
820 * the resolve for <b>address</b> itself, and remove any cached results for
821 * <b>address</b> from the cache.
823 void
824 dns_cancel_pending_resolve(const char *address)
826 pending_connection_t *pend;
827 cached_resolve_t search;
828 cached_resolve_t *resolve, *tmp;
829 edge_connection_t *pendconn;
830 circuit_t *circ;
832 strlcpy(search.address, address, sizeof(search.address));
834 resolve = HT_FIND(cache_map, &cache_root, &search);
835 if (!resolve)
836 return;
838 if (resolve->state != CACHE_STATE_PENDING) {
839 /* We can get into this state if we never actually created the pending
840 * resolve, due to finding an earlier cached error or something. Just
841 * ignore it. */
842 if (resolve->pending_connections) {
843 log_warn(LD_BUG,
844 "Address %s is not pending but has pending connections!",
845 escaped_safe_str(address));
846 tor_fragile_assert();
848 return;
851 if (!resolve->pending_connections) {
852 log_warn(LD_BUG,
853 "Address %s is pending but has no pending connections!",
854 escaped_safe_str(address));
855 tor_fragile_assert();
856 return;
858 tor_assert(resolve->pending_connections);
860 /* mark all pending connections to fail */
861 log_debug(LD_EXIT,
862 "Failing all connections waiting on DNS resolve of %s",
863 escaped_safe_str(address));
864 while (resolve->pending_connections) {
865 pend = resolve->pending_connections;
866 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
867 pendconn = pend->conn;
868 assert_connection_ok(TO_CONN(pendconn), 0);
869 tor_assert(pendconn->_base.s == -1);
870 if (!pendconn->_base.marked_for_close) {
871 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
873 circ = circuit_get_by_edge_conn(pendconn);
874 if (circ)
875 circuit_detach_stream(circ, pendconn);
876 if (!pendconn->_base.marked_for_close)
877 connection_free(TO_CONN(pendconn));
878 resolve->pending_connections = pend->next;
879 tor_free(pend);
882 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
883 if (tmp != resolve) {
884 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
885 " the cache. Tried to purge %s (%p); instead got %s (%p).",
886 resolve->address, (void*)resolve,
887 tmp ? tmp->address : "NULL", (void*)tmp);
889 tor_assert(tmp == resolve);
891 resolve->state = CACHE_STATE_DONE;
894 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
895 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
896 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
897 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
899 static void
900 add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
901 const char *hostname, char outcome, uint32_t ttl)
903 cached_resolve_t *resolve;
904 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
905 return;
907 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
908 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
909 // hostname?hostname:"NULL",(int)outcome);
911 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
912 resolve->magic = CACHED_RESOLVE_MAGIC;
913 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
914 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
915 strlcpy(resolve->address, address, sizeof(resolve->address));
916 resolve->is_reverse = is_reverse;
917 if (is_reverse) {
918 if (outcome == DNS_RESOLVE_SUCCEEDED) {
919 tor_assert(hostname);
920 resolve->result.hostname = tor_strdup(hostname);
921 } else {
922 tor_assert(! hostname);
923 resolve->result.hostname = NULL;
925 } else {
926 tor_assert(!hostname);
927 resolve->result.a.addr = addr;
929 resolve->ttl = ttl;
930 assert_resolve_ok(resolve);
931 HT_INSERT(cache_map, &cache_root, resolve);
932 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
935 /** Return true iff <b>address</b> is one of the addresses we use to verify
936 * that well-known sites aren't being hijacked by our DNS servers. */
937 static INLINE int
938 is_test_address(const char *address)
940 or_options_t *options = get_options();
941 return options->ServerDNSTestAddresses &&
942 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
945 /** Called on the OR side when a DNS worker or the eventdns library tells us
946 * the outcome of a DNS resolve: tell all pending connections about the result
947 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
948 * string containing the address to look up; <b>addr</b> is an IPv4 address in
949 * host order; <b>outcome</b> is one of
950 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
952 static void
953 dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
954 const char *hostname, char outcome, uint32_t ttl)
956 pending_connection_t *pend;
957 cached_resolve_t search;
958 cached_resolve_t *resolve, *removed;
959 edge_connection_t *pendconn;
960 circuit_t *circ;
962 assert_cache_ok();
964 strlcpy(search.address, address, sizeof(search.address));
966 resolve = HT_FIND(cache_map, &cache_root, &search);
967 if (!resolve) {
968 int is_test_addr = is_test_address(address);
969 if (!is_test_addr)
970 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
971 escaped_safe_str(address));
972 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
973 return;
975 assert_resolve_ok(resolve);
977 if (resolve->state != CACHE_STATE_PENDING) {
978 /* XXXX Maybe update addr? or check addr for consistency? Or let
979 * VALID replace FAILED? */
980 int is_test_addr = is_test_address(address);
981 if (!is_test_addr)
982 log_notice(LD_EXIT,
983 "Resolved %s which was already resolved; ignoring",
984 escaped_safe_str(address));
985 tor_assert(resolve->pending_connections == NULL);
986 return;
988 /* Removed this assertion: in fact, we'll sometimes get a double answer
989 * to the same question. This can happen when we ask one worker to resolve
990 * X.Y.Z., then we cancel the request, and then we ask another worker to
991 * resolve X.Y.Z. */
992 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
994 while (resolve->pending_connections) {
995 pend = resolve->pending_connections;
996 pendconn = pend->conn; /* don't pass complex things to the
997 connection_mark_for_close macro */
998 assert_connection_ok(TO_CONN(pendconn),time(NULL));
999 tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
1000 pendconn->address_ttl = ttl;
1002 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1003 /* prevent double-remove. */
1004 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1005 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1006 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1007 /* This detach must happen after we send the end cell. */
1008 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1009 } else {
1010 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1011 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1012 /* This detach must happen after we send the resolved cell. */
1013 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1015 connection_free(TO_CONN(pendconn));
1016 } else {
1017 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1018 tor_assert(!is_reverse);
1019 /* prevent double-remove. */
1020 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1022 circ = circuit_get_by_edge_conn(pend->conn);
1023 tor_assert(circ);
1024 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1025 /* unlink pend->conn from resolving_streams, */
1026 circuit_detach_stream(circ, pend->conn);
1027 /* and link it to n_streams */
1028 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1029 pend->conn->on_circuit = circ;
1030 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1032 connection_exit_connect(pend->conn);
1033 } else {
1034 /* prevent double-remove. This isn't really an accurate state,
1035 * but it does the right thing. */
1036 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1037 if (is_reverse)
1038 send_resolved_hostname_cell(pendconn, hostname);
1039 else
1040 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1041 circ = circuit_get_by_edge_conn(pendconn);
1042 tor_assert(circ);
1043 circuit_detach_stream(circ, pendconn);
1044 connection_free(TO_CONN(pendconn));
1047 resolve->pending_connections = pend->next;
1048 tor_free(pend);
1051 resolve->state = CACHE_STATE_DONE;
1052 removed = HT_REMOVE(cache_map, &cache_root, &search);
1053 if (removed != resolve) {
1054 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1055 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1056 resolve->address, (void*)resolve,
1057 removed ? removed->address : "NULL", (void*)removed);
1059 assert_resolve_ok(resolve);
1060 assert_cache_ok();
1062 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1063 assert_cache_ok();
1066 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1067 * a transient failure. */
1068 static int
1069 evdns_err_is_transient(int err)
1071 switch (err)
1073 case DNS_ERR_SERVERFAILED:
1074 case DNS_ERR_TRUNCATED:
1075 case DNS_ERR_TIMEOUT:
1076 return 1;
1077 default:
1078 return 0;
1082 /** Configure eventdns nameservers if force is true, or if the configuration
1083 * has changed since the last time we called this function, or if we failed on
1084 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1085 * options->ServerDNSResolvConfFile; on Windows, this reads from
1086 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1087 * -1 on failure. */
1088 static int
1089 configure_nameservers(int force)
1091 or_options_t *options;
1092 const char *conf_fname;
1093 struct stat st;
1094 int r;
1095 options = get_options();
1096 conf_fname = options->ServerDNSResolvConfFile;
1097 #ifndef MS_WINDOWS
1098 if (!conf_fname)
1099 conf_fname = "/etc/resolv.conf";
1100 #endif
1102 evdns_set_log_fn(evdns_log_cb);
1103 if (conf_fname) {
1104 if (stat(conf_fname, &st)) {
1105 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1106 conf_fname, strerror(errno));
1107 goto err;
1109 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1110 && st.st_mtime == resolv_conf_mtime) {
1111 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1112 return 0;
1114 if (nameservers_configured) {
1115 evdns_search_clear();
1116 evdns_clear_nameservers_and_suspend();
1118 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1119 if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
1120 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1121 conf_fname, conf_fname, r);
1122 goto err;
1124 if (evdns_count_nameservers() == 0) {
1125 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1126 goto err;
1128 tor_free(resolv_conf_fname);
1129 resolv_conf_fname = tor_strdup(conf_fname);
1130 resolv_conf_mtime = st.st_mtime;
1131 if (nameservers_configured)
1132 evdns_resume();
1134 #ifdef MS_WINDOWS
1135 else {
1136 if (nameservers_configured) {
1137 evdns_search_clear();
1138 evdns_clear_nameservers_and_suspend();
1140 if (evdns_config_windows_nameservers()) {
1141 log_warn(LD_EXIT,"Could not config nameservers.");
1142 goto err;
1144 if (evdns_count_nameservers() == 0) {
1145 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1146 "your Windows configuration.");
1147 goto err;
1149 if (nameservers_configured)
1150 evdns_resume();
1151 tor_free(resolv_conf_fname);
1152 resolv_conf_mtime = 0;
1154 #endif
1156 if (evdns_count_nameservers() == 1) {
1157 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
1158 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
1159 } else {
1160 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
1161 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
1164 dns_servers_relaunch_checks();
1166 nameservers_configured = 1;
1167 if (nameserver_config_failed) {
1168 nameserver_config_failed = 0;
1169 mark_my_descriptor_dirty();
1171 return 0;
1172 err:
1173 nameservers_configured = 0;
1174 if (! nameserver_config_failed) {
1175 nameserver_config_failed = 1;
1176 mark_my_descriptor_dirty();
1178 return -1;
1181 /** For eventdns: Called when we get an answer for a request we launched.
1182 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1184 static void
1185 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1186 void *arg)
1188 char *string_address = arg;
1189 uint8_t is_reverse = 0;
1190 int status = DNS_RESOLVE_FAILED_PERMANENT;
1191 uint32_t addr = 0;
1192 const char *hostname = NULL;
1193 int was_wildcarded = 0;
1195 if (result == DNS_ERR_NONE) {
1196 if (type == DNS_IPv4_A && count) {
1197 char answer_buf[INET_NTOA_BUF_LEN+1];
1198 struct in_addr in;
1199 char *escaped_address;
1200 uint32_t *addrs = addresses;
1201 in.s_addr = addrs[0];
1202 addr = ntohl(addrs[0]);
1203 status = DNS_RESOLVE_SUCCEEDED;
1204 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1205 escaped_address = esc_for_log(string_address);
1207 if (answer_is_wildcarded(answer_buf)) {
1208 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1209 "address %s; treating as a failure.",
1210 safe_str(escaped_address),
1211 escaped_safe_str(answer_buf));
1212 was_wildcarded = 1;
1213 addr = 0;
1214 status = DNS_RESOLVE_FAILED_PERMANENT;
1215 } else {
1216 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1217 safe_str(escaped_address),
1218 escaped_safe_str(answer_buf));
1220 tor_free(escaped_address);
1221 } else if (type == DNS_PTR && count) {
1222 char *escaped_address;
1223 is_reverse = 1;
1224 hostname = ((char**)addresses)[0];
1225 status = DNS_RESOLVE_SUCCEEDED;
1226 escaped_address = esc_for_log(string_address);
1227 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1228 safe_str(escaped_address),
1229 escaped_safe_str(hostname));
1230 tor_free(escaped_address);
1231 } else if (count) {
1232 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1233 escaped_safe_str(string_address));
1234 } else {
1235 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1236 escaped_safe_str(string_address));
1238 } else {
1239 if (evdns_err_is_transient(result))
1240 status = DNS_RESOLVE_FAILED_TRANSIENT;
1242 if (was_wildcarded) {
1243 if (is_test_address(string_address)) {
1244 /* Ick. We're getting redirected on known-good addresses. Our DNS
1245 * server must really hate us. */
1246 add_wildcarded_test_address(string_address);
1249 if (result != DNS_ERR_SHUTDOWN)
1250 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1251 tor_free(string_address);
1254 /** For eventdns: start resolving as necessary to find the target for
1255 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1256 * 0 on "resolve launched." */
1257 static int
1258 launch_resolve(edge_connection_t *exitconn)
1260 char *addr = tor_strdup(exitconn->_base.address);
1261 tor_addr_t a;
1262 int r;
1263 int options = get_options()->ServerDNSSearchDomains ? 0
1264 : DNS_QUERY_NO_SEARCH;
1265 /* What? Nameservers not configured? Sounds like a bug. */
1266 if (!nameservers_configured) {
1267 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1268 "launched. Configuring.");
1269 if (configure_nameservers(1) < 0) {
1270 return -1;
1274 r = tor_addr_parse_reverse_lookup_name(
1275 &a, exitconn->_base.address, AF_UNSPEC, 0);
1276 if (r == 0) {
1277 log_info(LD_EXIT, "Launching eventdns request for %s",
1278 escaped_safe_str(exitconn->_base.address));
1279 r = evdns_resolve_ipv4(exitconn->_base.address, options,
1280 evdns_callback, addr);
1281 } else if (r == 1) {
1282 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1283 escaped_safe_str(exitconn->_base.address));
1284 if (tor_addr_family(&a) == AF_INET)
1285 r = evdns_resolve_reverse(tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
1286 evdns_callback, addr);
1287 else
1288 r = evdns_resolve_reverse_ipv6(tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
1289 evdns_callback, addr);
1290 } else if (r == -1) {
1291 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1294 if (r) {
1295 log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
1296 escaped_safe_str(addr), r);
1297 r = evdns_err_is_transient(r) ? -2 : -1;
1298 tor_free(addr); /* There is no evdns request in progress; stop
1299 * addr from getting leaked. */
1301 return r;
1304 /** How many requests for bogus addresses have we launched so far? */
1305 static int n_wildcard_requests = 0;
1307 /** Map from dotted-quad IP address in response to an int holding how many
1308 * times we've seen it for a randomly generated (hopefully bogus) address. It
1309 * would be easier to use definitely-invalid addresses (as specified by
1310 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1311 static strmap_t *dns_wildcard_response_count = NULL;
1313 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1314 * nameserver wants to return in response to requests for nonexistent domains.
1316 static smartlist_t *dns_wildcard_list = NULL;
1317 /** True iff we've logged about a single address getting wildcarded.
1318 * Subsequent warnings will be less severe. */
1319 static int dns_wildcard_one_notice_given = 0;
1320 /** True iff we've warned that our DNS server is wildcarding too many failures.
1322 static int dns_wildcard_notice_given = 0;
1324 /** List of supposedly good addresses that are getting wildcarded to the
1325 * same addresses as nonexistent addresses. */
1326 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1327 /** True iff we've warned about a test address getting wildcarded */
1328 static int dns_wildcarded_test_address_notice_given = 0;
1329 /** True iff all addresses seem to be getting wildcarded. */
1330 static int dns_is_completely_invalid = 0;
1332 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1333 * a hopefully bogus address. */
1334 static void
1335 wildcard_increment_answer(const char *id)
1337 int *ip;
1338 if (!dns_wildcard_response_count)
1339 dns_wildcard_response_count = strmap_new();
1341 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1342 if (!ip) {
1343 ip = tor_malloc_zero(sizeof(int));
1344 strmap_set(dns_wildcard_response_count, id, ip);
1346 ++*ip;
1348 if (*ip > 5 && n_wildcard_requests > 10) {
1349 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1350 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1351 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1352 "Your DNS provider has given \"%s\" as an answer for %d different "
1353 "invalid addresses. Apparently they are hijacking DNS failures. "
1354 "I'll try to correct for this by treating future occurrences of "
1355 "\"%s\" as 'not found'.", id, *ip, id);
1356 smartlist_add(dns_wildcard_list, tor_strdup(id));
1358 if (!dns_wildcard_notice_given)
1359 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1360 dns_wildcard_notice_given = 1;
1364 /** Note that a single test address (one believed to be good) seems to be
1365 * getting redirected to the same IP as failures are. */
1366 static void
1367 add_wildcarded_test_address(const char *address)
1369 int n, n_test_addrs;
1370 if (!dns_wildcarded_test_address_list)
1371 dns_wildcarded_test_address_list = smartlist_create();
1373 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1374 return;
1376 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1377 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1379 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1380 n = smartlist_len(dns_wildcarded_test_address_list);
1381 if (n > n_test_addrs/2) {
1382 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1383 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1384 "address. It has done this with %d test addresses so far. I'm "
1385 "going to stop being an exit node for now, since our DNS seems so "
1386 "broken.", address, n);
1387 if (!dns_is_completely_invalid) {
1388 dns_is_completely_invalid = 1;
1389 mark_my_descriptor_dirty();
1391 if (!dns_wildcarded_test_address_notice_given)
1392 control_event_server_status(LOG_WARN, "DNS_USELESS");
1393 dns_wildcarded_test_address_notice_given = 1;
1397 /** Callback function when we get an answer (possibly failing) for a request
1398 * for a (hopefully) nonexistent domain. */
1399 static void
1400 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1401 void *addresses, void *arg)
1403 (void)ttl;
1404 ++n_wildcard_requests;
1405 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1406 uint32_t *addrs = addresses;
1407 int i;
1408 char *string_address = arg;
1409 for (i = 0; i < count; ++i) {
1410 char answer_buf[INET_NTOA_BUF_LEN+1];
1411 struct in_addr in;
1412 in.s_addr = addrs[i];
1413 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1414 wildcard_increment_answer(answer_buf);
1416 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1417 "Your DNS provider gave an answer for \"%s\", which "
1418 "is not supposed to exist. Apparently they are hijacking "
1419 "DNS failures. Trying to correct for this. We've noticed %d "
1420 "possibly bad address%s so far.",
1421 string_address, strmap_size(dns_wildcard_response_count),
1422 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1423 dns_wildcard_one_notice_given = 1;
1425 tor_free(arg);
1428 /** Launch a single request for a nonexistent hostname consisting of between
1429 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1430 * <b>suffix</b> */
1431 static void
1432 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1434 char *addr;
1435 int r;
1437 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1438 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1439 "domains with request for bogus hostname \"%s\"", addr);
1441 r = evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1442 addr,
1443 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1444 /* This "addr" is an argument to the callback*/ addr);
1445 if (r) {
1446 /* There is no evdns request in progress; stop addr from getting leaked */
1447 tor_free(addr);
1451 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1452 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1453 static void
1454 launch_test_addresses(int fd, short event, void *args)
1456 or_options_t *options = get_options();
1457 (void)fd;
1458 (void)event;
1459 (void)args;
1461 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1462 "hijack *everything*.");
1463 /* This situation is worse than the failure-hijacking situation. When this
1464 * happens, we're no good for DNS requests at all, and we shouldn't really
1465 * be an exit server.*/
1466 if (!options->ServerDNSTestAddresses)
1467 return;
1468 SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
1470 int r = evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
1471 tor_strdup(address));
1472 if (r)
1473 log_info(LD_EXIT, "eventdns rejected test address %s: error %d",
1474 escaped_safe_str(address), r);
1478 #define N_WILDCARD_CHECKS 2
1480 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1481 * hostnames, and see if we can catch our nameserver trying to hijack them and
1482 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1483 * buy these lovely encyclopedias" page. */
1484 static void
1485 dns_launch_wildcard_checks(void)
1487 int i;
1488 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1489 "to hijack DNS failures.");
1490 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1491 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1492 * to 'comply' with rfc2606, refrain from giving A records for these.
1493 * This is the standards-compliance equivalent of making sure that your
1494 * crackhouse's elevator inspection certificate is up to date.
1496 launch_wildcard_check(2, 16, ".invalid");
1497 launch_wildcard_check(2, 16, ".test");
1499 /* These will break specs if there are ever any number of
1500 * 8+-character top-level domains. */
1501 launch_wildcard_check(8, 16, "");
1503 /* Try some random .com/org/net domains. This will work fine so long as
1504 * not too many resolve to the same place. */
1505 launch_wildcard_check(8, 16, ".com");
1506 launch_wildcard_check(8, 16, ".org");
1507 launch_wildcard_check(8, 16, ".net");
1511 /** If appropriate, start testing whether our DNS servers tend to lie to
1512 * us. */
1513 void
1514 dns_launch_correctness_checks(void)
1516 static struct event launch_event;
1517 struct timeval timeout;
1518 if (!get_options()->ServerDNSDetectHijacking)
1519 return;
1520 dns_launch_wildcard_checks();
1522 /* Wait a while before launching requests for test addresses, so we can
1523 * get the results from checking for wildcarding. */
1524 evtimer_set(&launch_event, launch_test_addresses, NULL);
1525 timeout.tv_sec = 30;
1526 timeout.tv_usec = 0;
1527 if (evtimer_add(&launch_event, &timeout)<0) {
1528 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1532 /** Return true iff our DNS servers lie to us too much to be trustd. */
1534 dns_seems_to_be_broken(void)
1536 return dns_is_completely_invalid;
1539 /** Forget what we've previously learned about our DNS servers' correctness. */
1540 void
1541 dns_reset_correctness_checks(void)
1543 if (dns_wildcard_response_count) {
1544 strmap_free(dns_wildcard_response_count, _tor_free);
1545 dns_wildcard_response_count = NULL;
1547 n_wildcard_requests = 0;
1549 if (dns_wildcard_list) {
1550 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1551 smartlist_clear(dns_wildcard_list);
1553 if (dns_wildcarded_test_address_list) {
1554 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1555 tor_free(cp));
1556 smartlist_clear(dns_wildcarded_test_address_list);
1558 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1559 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1562 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1563 * returned in response to requests for nonexistent hostnames. */
1564 static int
1565 answer_is_wildcarded(const char *ip)
1567 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1570 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1571 static void
1572 assert_resolve_ok(cached_resolve_t *resolve)
1574 tor_assert(resolve);
1575 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1576 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1577 tor_assert(tor_strisnonupper(resolve->address));
1578 if (resolve->state != CACHE_STATE_PENDING) {
1579 tor_assert(!resolve->pending_connections);
1581 if (resolve->state == CACHE_STATE_PENDING ||
1582 resolve->state == CACHE_STATE_DONE) {
1583 tor_assert(!resolve->ttl);
1584 if (resolve->is_reverse)
1585 tor_assert(!resolve->result.hostname);
1586 else
1587 tor_assert(!resolve->result.a.addr);
1591 #ifdef DEBUG_DNS_CACHE
1592 /** Exit with an assertion if the DNS cache is corrupt. */
1593 static void
1594 _assert_cache_ok(void)
1596 cached_resolve_t **resolve;
1597 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1598 if (bad_rep) {
1599 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1600 tor_assert(!bad_rep);
1603 HT_FOREACH(resolve, cache_map, &cache_root) {
1604 assert_resolve_ok(*resolve);
1605 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1607 if (!cached_resolve_pqueue)
1608 return;
1610 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1611 _compare_cached_resolves_by_expiry);
1613 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1615 if (res->state == CACHE_STATE_DONE) {
1616 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1617 tor_assert(!found || found != res);
1618 } else {
1619 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1620 tor_assert(found);
1624 #endif