Update Tor Project copyright years
[tor/rransom.git] / src / or / dns.c
blob98eb27f8b316e667ac8ba7f7f8e2bccbf60d32a1
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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.)
12 **/
14 #include "or.h"
15 #include "ht.h"
16 #include "eventdns.h"
18 /** Longest hostname we're willing to resolve. */
19 #define MAX_ADDRESSLEN 256
21 /** How long will we wait for an answer from the resolver before we decide
22 * that the resolver is wedged? */
23 #define RESOLVE_MAX_TIMEOUT 300
25 /** Possible outcomes from hostname lookup: permanent failure,
26 * transient (retryable) failure, and success. */
27 #define DNS_RESOLVE_FAILED_TRANSIENT 1
28 #define DNS_RESOLVE_FAILED_PERMANENT 2
29 #define DNS_RESOLVE_SUCCEEDED 3
31 /** Have we currently configured nameservers with eventdns? */
32 static int nameservers_configured = 0;
33 /** Did our most recent attempt to configure nameservers with eventdns fail? */
34 static int nameserver_config_failed = 0;
35 /** What was the resolv_conf fname we last used when configuring the
36 * nameservers? Used to check whether we need to reconfigure. */
37 static char *resolv_conf_fname = NULL;
38 /** What was the mtime on the resolv.conf file we last used when configuring
39 * the nameservers? Used to check whether we need to reconfigure. */
40 static time_t resolv_conf_mtime = 0;
42 /** Linked list of connections waiting for a DNS answer. */
43 typedef struct pending_connection_t {
44 edge_connection_t *conn;
45 struct pending_connection_t *next;
46 } pending_connection_t;
48 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
49 * pointers and memory stomping. */
50 #define CACHED_RESOLVE_MAGIC 0x1234F00D
52 /* Possible states for a cached resolve_t */
53 /** We are waiting for the resolver system to tell us an answer here.
54 * When we get one, or when we time out, the state of this cached_resolve_t
55 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
56 * entry. This cached_resolve_t will be in the hash table so that we will
57 * know not to launch more requests for this addr, but rather to add more
58 * connections to the pending list for the addr. */
59 #define CACHE_STATE_PENDING 0
60 /** This used to be a pending cached_resolve_t, and we got an answer for it.
61 * Now we're waiting for this cached_resolve_t to expire. This should
62 * have no pending connections, and should not appear in the hash table. */
63 #define CACHE_STATE_DONE 1
64 /** We are caching an answer for this address. This should have no pending
65 * connections, and should appear in the hash table. */
66 #define CACHE_STATE_CACHED_VALID 2
67 /** We are caching a failure for this address. This should have no pending
68 * connections, and should appear in the hash table */
69 #define CACHE_STATE_CACHED_FAILED 3
71 /** A DNS request: possibly completed, possibly pending; cached_resolve
72 * structs are stored at the OR side in a hash table, and as a linked
73 * list from oldest to newest.
75 typedef struct cached_resolve_t {
76 HT_ENTRY(cached_resolve_t) node;
77 uint32_t magic;
78 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
79 union {
80 struct {
81 struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
82 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
83 } a;
84 char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
85 } result;
86 uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
87 uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
88 time_t expire; /**< Remove items from cache after this time. */
89 uint32_t ttl; /**< What TTL did the nameserver tell us? */
90 /** Connections that want to know when we get an answer for this resolve. */
91 pending_connection_t *pending_connections;
92 } cached_resolve_t;
94 static void purge_expired_resolves(time_t now);
95 static void dns_found_answer(const char *address, uint8_t is_reverse,
96 uint32_t addr, const char *hostname, char outcome,
97 uint32_t ttl);
98 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
99 static int launch_resolve(edge_connection_t *exitconn);
100 static void add_wildcarded_test_address(const char *address);
101 static int configure_nameservers(int force);
102 static int answer_is_wildcarded(const char *ip);
103 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
104 or_circuit_t *oncirc, char **resolved_to_hostname);
105 #ifdef DEBUG_DNS_CACHE
106 static void _assert_cache_ok(void);
107 #define assert_cache_ok() _assert_cache_ok()
108 #else
109 #define assert_cache_ok() STMT_NIL
110 #endif
111 static void assert_resolve_ok(cached_resolve_t *resolve);
113 /** Hash table of cached_resolve objects. */
114 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
116 /** Function to compare hashed resolves on their addresses; used to
117 * implement hash tables. */
118 static INLINE int
119 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
121 /* make this smarter one day? */
122 assert_resolve_ok(a); // Not b; b may be just a search.
123 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
126 /** Hash function for cached_resolve objects */
127 static INLINE unsigned int
128 cached_resolve_hash(cached_resolve_t *a)
130 return ht_string_hash(a->address);
133 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
134 cached_resolves_eq)
135 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
136 cached_resolves_eq, 0.6, malloc, realloc, free)
138 /** Initialize the DNS cache. */
139 static void
140 init_cache_map(void)
142 HT_INIT(cache_map, &cache_root);
145 /** Helper: called by eventdns when eventdns wants to log something. */
146 static void
147 evdns_log_cb(int warn, const char *msg)
149 const char *cp;
150 static int all_down = 0;
151 int severity = warn ? LOG_WARN : LOG_INFO;
152 if (!strcmpstart(msg, "Resolve requested for") &&
153 get_options()->SafeLogging) {
154 log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
155 return;
156 } else if (!strcmpstart(msg, "Search: ")) {
157 return;
159 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
160 char *ns = tor_strndup(msg+11, cp-(msg+11));
161 const char *err = strchr(cp, ':')+2;
162 tor_assert(err);
163 /* Don't warn about a single failed nameserver; we'll warn with 'all
164 * nameservers have failed' if we're completely out of nameservers;
165 * otherwise, the situation is tolerable. */
166 severity = LOG_INFO;
167 control_event_server_status(LOG_NOTICE,
168 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
169 ns, escaped(err));
170 tor_free(ns);
171 } else if (!strcmpstart(msg, "Nameserver ") &&
172 (cp=strstr(msg, " is back up"))) {
173 char *ns = tor_strndup(msg+11, cp-(msg+11));
174 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
175 all_down = 0;
176 control_event_server_status(LOG_NOTICE,
177 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
178 tor_free(ns);
179 } else if (!strcmp(msg, "All nameservers have failed")) {
180 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
181 all_down = 1;
183 log(severity, LD_EXIT, "eventdns: %s", msg);
186 /** Helper: passed to eventdns.c as a callback so it can generate random
187 * numbers for transaction IDs and 0x20-hack coding. */
188 static void
189 _dns_randfn(char *b, size_t n)
191 crypto_rand(b,n);
194 /** Initialize the DNS subsystem; called by the OR process. */
196 dns_init(void)
198 init_cache_map();
199 evdns_set_random_bytes_fn(_dns_randfn);
200 if (server_mode(get_options())) {
201 int r = configure_nameservers(1);
202 return r;
204 return 0;
207 /** Called when DNS-related options change (or may have changed). Returns -1
208 * on failure, 0 on success. */
210 dns_reset(void)
212 or_options_t *options = get_options();
213 if (! server_mode(options)) {
214 evdns_clear_nameservers_and_suspend();
215 evdns_search_clear();
216 nameservers_configured = 0;
217 tor_free(resolv_conf_fname);
218 resolv_conf_mtime = 0;
219 } else {
220 if (configure_nameservers(0) < 0) {
221 return -1;
224 return 0;
227 /** Return true iff the most recent attempt to initialize the DNS subsystem
228 * failed. */
230 has_dns_init_failed(void)
232 return nameserver_config_failed;
235 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
236 * OP that asked us to resolve it. */
237 uint32_t
238 dns_clip_ttl(uint32_t ttl)
240 if (ttl < MIN_DNS_TTL)
241 return MIN_DNS_TTL;
242 else if (ttl > MAX_DNS_TTL)
243 return MAX_DNS_TTL;
244 else
245 return ttl;
248 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
249 * our cache. */
250 static uint32_t
251 dns_get_expiry_ttl(uint32_t ttl)
253 if (ttl < MIN_DNS_TTL)
254 return MIN_DNS_TTL;
255 else if (ttl > MAX_DNS_ENTRY_AGE)
256 return MAX_DNS_ENTRY_AGE;
257 else
258 return ttl;
261 /** Helper: free storage held by an entry in the DNS cache. */
262 static void
263 _free_cached_resolve(cached_resolve_t *r)
265 while (r->pending_connections) {
266 pending_connection_t *victim = r->pending_connections;
267 r->pending_connections = victim->next;
268 tor_free(victim);
270 if (r->is_reverse)
271 tor_free(r->result.hostname);
272 r->magic = 0xFF00FF00;
273 tor_free(r);
276 /** Compare two cached_resolve_t pointers by expiry time, and return
277 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
278 * the priority queue implementation. */
279 static int
280 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
282 const cached_resolve_t *a = _a, *b = _b;
283 if (a->expire < b->expire)
284 return -1;
285 else if (a->expire == b->expire)
286 return 0;
287 else
288 return 1;
291 /** Priority queue of cached_resolve_t objects to let us know when they
292 * will expire. */
293 static smartlist_t *cached_resolve_pqueue = NULL;
295 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
296 * priority queue */
297 static void
298 set_expiry(cached_resolve_t *resolve, time_t expires)
300 tor_assert(resolve && resolve->expire == 0);
301 if (!cached_resolve_pqueue)
302 cached_resolve_pqueue = smartlist_create();
303 resolve->expire = expires;
304 smartlist_pqueue_add(cached_resolve_pqueue,
305 _compare_cached_resolves_by_expiry,
306 resolve);
309 /** Free all storage held in the DNS cache and related structures. */
310 void
311 dns_free_all(void)
313 cached_resolve_t **ptr, **next, *item;
314 assert_cache_ok();
315 if (cached_resolve_pqueue) {
316 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
318 if (res->state == CACHE_STATE_DONE)
319 _free_cached_resolve(res);
322 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
323 item = *ptr;
324 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
325 _free_cached_resolve(item);
327 HT_CLEAR(cache_map, &cache_root);
328 if (cached_resolve_pqueue)
329 smartlist_free(cached_resolve_pqueue);
330 cached_resolve_pqueue = NULL;
331 tor_free(resolv_conf_fname);
334 /** Remove every cached_resolve whose <b>expire</b> time is before or
335 * equal to <b>now</b> from the cache. */
336 static void
337 purge_expired_resolves(time_t now)
339 cached_resolve_t *resolve, *removed;
340 pending_connection_t *pend;
341 edge_connection_t *pendconn;
343 assert_cache_ok();
344 if (!cached_resolve_pqueue)
345 return;
347 while (smartlist_len(cached_resolve_pqueue)) {
348 resolve = smartlist_get(cached_resolve_pqueue, 0);
349 if (resolve->expire > now)
350 break;
351 smartlist_pqueue_pop(cached_resolve_pqueue,
352 _compare_cached_resolves_by_expiry);
354 if (resolve->state == CACHE_STATE_PENDING) {
355 log_debug(LD_EXIT,
356 "Expiring a dns resolve %s that's still pending. Forgot to "
357 "cull it? DNS resolve didn't tell us about the timeout?",
358 escaped_safe_str(resolve->address));
359 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
360 resolve->state == CACHE_STATE_CACHED_FAILED) {
361 log_debug(LD_EXIT,
362 "Forgetting old cached resolve (address %s, expires %lu)",
363 escaped_safe_str(resolve->address),
364 (unsigned long)resolve->expire);
365 tor_assert(!resolve->pending_connections);
366 } else {
367 tor_assert(resolve->state == CACHE_STATE_DONE);
368 tor_assert(!resolve->pending_connections);
371 if (resolve->pending_connections) {
372 log_debug(LD_EXIT,
373 "Closing pending connections on timed-out DNS resolve!");
374 tor_fragile_assert();
375 while (resolve->pending_connections) {
376 pend = resolve->pending_connections;
377 resolve->pending_connections = pend->next;
378 /* Connections should only be pending if they have no socket. */
379 tor_assert(pend->conn->_base.s == -1);
380 pendconn = pend->conn;
381 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
382 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
383 connection_free(TO_CONN(pendconn));
384 tor_free(pend);
388 if (resolve->state == CACHE_STATE_CACHED_VALID ||
389 resolve->state == CACHE_STATE_CACHED_FAILED ||
390 resolve->state == CACHE_STATE_PENDING) {
391 removed = HT_REMOVE(cache_map, &cache_root, resolve);
392 if (removed != resolve) {
393 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
394 " the cache. Tried to purge %s (%p); instead got %s (%p).",
395 resolve->address, (void*)resolve,
396 removed ? removed->address : "NULL", (void*)remove);
398 tor_assert(removed == resolve);
399 } else {
400 /* This should be in state DONE. Make sure it's not in the cache. */
401 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
402 tor_assert(tmp != resolve);
404 if (resolve->is_reverse)
405 tor_free(resolve->result.hostname);
406 resolve->magic = 0xF0BBF0BB;
407 tor_free(resolve);
410 assert_cache_ok();
413 /** Send a response to the RESOLVE request of a connection.
414 * <b>answer_type</b> must be one of
415 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
417 * If <b>circ</b> is provided, and we have a cached answer, send the
418 * answer back along circ; otherwise, send the answer back along
419 * <b>conn</b>'s attached circuit.
421 static void
422 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
424 char buf[RELAY_PAYLOAD_SIZE];
425 size_t buflen;
426 uint32_t ttl;
428 buf[0] = answer_type;
429 ttl = dns_clip_ttl(conn->address_ttl);
431 switch (answer_type)
433 case RESOLVED_TYPE_IPV4:
434 buf[1] = 4;
435 set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
436 set_uint32(buf+6, htonl(ttl));
437 buflen = 10;
438 break;
439 /*XXXX IP6 need ipv6 implementation */
440 case RESOLVED_TYPE_ERROR_TRANSIENT:
441 case RESOLVED_TYPE_ERROR:
443 const char *errmsg = "Error resolving hostname";
444 size_t msglen = strlen(errmsg);
446 buf[1] = msglen;
447 strlcpy(buf+2, errmsg, sizeof(buf)-2);
448 set_uint32(buf+2+msglen, htonl(ttl));
449 buflen = 6+msglen;
450 break;
452 default:
453 tor_assert(0);
454 return;
456 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
458 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
461 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
462 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
463 * The answer type will be RESOLVED_HOSTNAME.
465 * If <b>circ</b> is provided, and we have a cached answer, send the
466 * answer back along circ; otherwise, send the answer back along
467 * <b>conn</b>'s attached circuit.
469 static void
470 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
472 char buf[RELAY_PAYLOAD_SIZE];
473 size_t buflen;
474 uint32_t ttl;
475 size_t namelen = strlen(hostname);
476 tor_assert(hostname);
478 tor_assert(namelen < 256);
479 ttl = dns_clip_ttl(conn->address_ttl);
481 buf[0] = RESOLVED_TYPE_HOSTNAME;
482 buf[1] = (uint8_t)namelen;
483 memcpy(buf+2, hostname, namelen);
484 set_uint32(buf+2+namelen, htonl(ttl));
485 buflen = 2+namelen+4;
487 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
488 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
489 // log_notice(LD_EXIT, "Sent");
492 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
493 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
494 * If resolve failed, free exitconn and return -1.
496 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
497 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
498 * need to send back an END cell, since connection_exit_begin_conn will
499 * do that for us.)
501 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
502 * circuit.
504 * Else, if seen before and pending, add conn to the pending list,
505 * and return 0.
507 * Else, if not seen before, add conn to pending list, hand to
508 * dns farm, and return 0.
510 * Exitconn's on_circuit field must be set, but exitconn should not
511 * yet be linked onto the n_streams/resolving_streams list of that circuit.
512 * On success, link the connection to n_streams if it's an exit connection.
513 * On "pending", link the connection to resolving streams. Otherwise,
514 * clear its on_circuit field.
517 dns_resolve(edge_connection_t *exitconn)
519 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
520 int is_resolve, r;
521 char *hostname = NULL;
522 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
524 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
526 switch (r) {
527 case 1:
528 /* We got an answer without a lookup -- either the answer was
529 * cached, or it was obvious (like an IP address). */
530 if (is_resolve) {
531 /* Send the answer back right now, and detach. */
532 if (hostname)
533 send_resolved_hostname_cell(exitconn, hostname);
534 else
535 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
536 exitconn->on_circuit = NULL;
537 } else {
538 /* Add to the n_streams list; the calling function will send back a
539 * connected cell. */
540 exitconn->next_stream = oncirc->n_streams;
541 oncirc->n_streams = exitconn;
543 break;
544 case 0:
545 /* The request is pending: add the connection into the linked list of
546 * resolving_streams on this circuit. */
547 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
548 exitconn->next_stream = oncirc->resolving_streams;
549 oncirc->resolving_streams = exitconn;
550 break;
551 case -2:
552 case -1:
553 /* The request failed before it could start: cancel this connection,
554 * and stop everybody waiting for the same connection. */
555 if (is_resolve) {
556 send_resolved_cell(exitconn,
557 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
560 exitconn->on_circuit = NULL;
562 dns_cancel_pending_resolve(exitconn->_base.address);
564 if (!exitconn->_base.marked_for_close) {
565 connection_free(TO_CONN(exitconn));
566 // XXX ... and we just leak exitconn otherwise? -RD
567 // If it's marked for close, it's on closeable_connection_lst in
568 // main.c. If it's on the closeable list, it will get freed from
569 // main.c. -NM
570 // "<armadev> If that's true, there are other bugs around, where we
571 // don't check if it's marked, and will end up double-freeing."
572 // On the other hand, I don't know of any actual bugs here, so this
573 // shouldn't be holding up the rc. -RD
575 break;
576 default:
577 tor_assert(0);
580 tor_free(hostname);
581 return r;
584 /** Helper function for dns_resolve: same functionality, but does not handle:
585 * - marking connections on error and clearing their on_circuit
586 * - linking connections to n_streams/resolving_streams,
587 * - sending resolved cells if we have an answer/error right away,
589 * Return -2 on a transient error. If it's a reverse resolve and it's
590 * successful, sets *<b>hostname_out</b> to a newly allocated string
591 * holding the cached reverse DNS value.
593 static int
594 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
595 or_circuit_t *oncirc, char **hostname_out)
597 cached_resolve_t *resolve;
598 cached_resolve_t search;
599 pending_connection_t *pending_connection;
600 routerinfo_t *me;
601 tor_addr_t addr;
602 time_t now = time(NULL);
603 uint8_t is_reverse = 0;
604 int r;
605 assert_connection_ok(TO_CONN(exitconn), 0);
606 tor_assert(exitconn->_base.s == -1);
607 assert_cache_ok();
608 tor_assert(oncirc);
610 /* first check if exitconn->_base.address is an IP. If so, we already
611 * know the answer. */
612 if (tor_addr_from_str(&addr, exitconn->_base.address) >= 0) {
613 if (tor_addr_family(&addr) == AF_INET) {
614 tor_addr_assign(&exitconn->_base.addr, &addr);
615 exitconn->address_ttl = DEFAULT_DNS_TTL;
616 return 1;
617 } else {
618 /* XXXX IPv6 */
619 return -1;
623 /* If we're a non-exit, don't even do DNS lookups. */
624 if (!(me = router_get_my_routerinfo()) ||
625 policy_is_reject_star(me->exit_policy)) {
626 return -1;
628 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
629 log(LOG_PROTOCOL_WARN, LD_EXIT,
630 "Rejecting invalid destination address %s",
631 escaped_safe_str(exitconn->_base.address));
632 return -1;
635 /* then take this opportunity to see if there are any expired
636 * resolves in the hash table. */
637 purge_expired_resolves(now);
639 /* lower-case exitconn->_base.address, so it's in canonical form */
640 tor_strlower(exitconn->_base.address);
642 /* Check whether this is a reverse lookup. If it's malformed, or it's a
643 * .in-addr.arpa address but this isn't a resolve request, kill the
644 * connection.
646 if ((r = tor_addr_parse_reverse_lookup_name(&addr, exitconn->_base.address,
647 AF_UNSPEC, 0)) != 0) {
648 if (r == 1) {
649 is_reverse = 1;
650 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
651 return -1;
654 if (!is_reverse || !is_resolve) {
655 if (!is_reverse)
656 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
657 escaped_safe_str(exitconn->_base.address));
658 else if (!is_resolve)
659 log_info(LD_EXIT,
660 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
661 "sending error.",
662 escaped_safe_str(exitconn->_base.address));
664 return -1;
666 //log_notice(LD_EXIT, "Looks like an address %s",
667 //exitconn->_base.address);
670 /* now check the hash table to see if 'address' is already there. */
671 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
672 resolve = HT_FIND(cache_map, &cache_root, &search);
673 if (resolve && resolve->expire > now) { /* already there */
674 switch (resolve->state) {
675 case CACHE_STATE_PENDING:
676 /* add us to the pending list */
677 pending_connection = tor_malloc_zero(
678 sizeof(pending_connection_t));
679 pending_connection->conn = exitconn;
680 pending_connection->next = resolve->pending_connections;
681 resolve->pending_connections = pending_connection;
682 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
683 "resolve of %s", exitconn->_base.s,
684 escaped_safe_str(exitconn->_base.address));
685 return 0;
686 case CACHE_STATE_CACHED_VALID:
687 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
688 exitconn->_base.s,
689 escaped_safe_str(resolve->address));
690 exitconn->address_ttl = resolve->ttl;
691 if (resolve->is_reverse) {
692 tor_assert(is_resolve);
693 *hostname_out = tor_strdup(resolve->result.hostname);
694 } else {
695 tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
697 return 1;
698 case CACHE_STATE_CACHED_FAILED:
699 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
700 exitconn->_base.s,
701 escaped_safe_str(exitconn->_base.address));
702 return -1;
703 case CACHE_STATE_DONE:
704 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
705 tor_fragile_assert();
707 tor_assert(0);
709 tor_assert(!resolve);
710 /* not there, need to add it */
711 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
712 resolve->magic = CACHED_RESOLVE_MAGIC;
713 resolve->state = CACHE_STATE_PENDING;
714 resolve->is_reverse = is_reverse;
715 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
717 /* add this connection to the pending list */
718 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
719 pending_connection->conn = exitconn;
720 resolve->pending_connections = pending_connection;
722 /* Add this resolve to the cache and priority queue. */
723 HT_INSERT(cache_map, &cache_root, resolve);
724 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
726 log_debug(LD_EXIT,"Launching %s.",
727 escaped_safe_str(exitconn->_base.address));
728 assert_cache_ok();
730 return launch_resolve(exitconn);
733 /** Log an error and abort if conn is waiting for a DNS resolve.
735 void
736 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
738 pending_connection_t *pend;
739 cached_resolve_t search;
741 #if 1
742 cached_resolve_t *resolve;
743 strlcpy(search.address, conn->_base.address, sizeof(search.address));
744 resolve = HT_FIND(cache_map, &cache_root, &search);
745 if (!resolve)
746 return;
747 for (pend = resolve->pending_connections; pend; pend = pend->next) {
748 tor_assert(pend->conn != conn);
750 #else
751 cached_resolve_t **resolve;
752 HT_FOREACH(resolve, cache_map, &cache_root) {
753 for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
754 tor_assert(pend->conn != conn);
757 #endif
760 /** Log an error and abort if any connection waiting for a DNS resolve is
761 * corrupted. */
762 void
763 assert_all_pending_dns_resolves_ok(void)
765 pending_connection_t *pend;
766 cached_resolve_t **resolve;
768 HT_FOREACH(resolve, cache_map, &cache_root) {
769 for (pend = (*resolve)->pending_connections;
770 pend;
771 pend = pend->next) {
772 assert_connection_ok(TO_CONN(pend->conn), 0);
773 tor_assert(pend->conn->_base.s == -1);
774 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
779 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
781 void
782 connection_dns_remove(edge_connection_t *conn)
784 pending_connection_t *pend, *victim;
785 cached_resolve_t search;
786 cached_resolve_t *resolve;
788 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
789 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
791 strlcpy(search.address, conn->_base.address, sizeof(search.address));
793 resolve = HT_FIND(cache_map, &cache_root, &search);
794 if (!resolve) {
795 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
796 escaped_safe_str(conn->_base.address));
797 return;
800 tor_assert(resolve->pending_connections);
801 assert_connection_ok(TO_CONN(conn),0);
803 pend = resolve->pending_connections;
805 if (pend->conn == conn) {
806 resolve->pending_connections = pend->next;
807 tor_free(pend);
808 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
809 "for resolve of %s",
810 conn->_base.s, escaped_safe_str(conn->_base.address));
811 return;
812 } else {
813 for ( ; pend->next; pend = pend->next) {
814 if (pend->next->conn == conn) {
815 victim = pend->next;
816 pend->next = victim->next;
817 tor_free(victim);
818 log_debug(LD_EXIT,
819 "Connection (fd %d) no longer waiting for resolve of %s",
820 conn->_base.s, escaped_safe_str(conn->_base.address));
821 return; /* more are pending */
824 tor_assert(0); /* not reachable unless onlyconn not in pending list */
828 /** Mark all connections waiting for <b>address</b> for close. Then cancel
829 * the resolve for <b>address</b> itself, and remove any cached results for
830 * <b>address</b> from the cache.
832 void
833 dns_cancel_pending_resolve(const char *address)
835 pending_connection_t *pend;
836 cached_resolve_t search;
837 cached_resolve_t *resolve, *tmp;
838 edge_connection_t *pendconn;
839 circuit_t *circ;
841 strlcpy(search.address, address, sizeof(search.address));
843 resolve = HT_FIND(cache_map, &cache_root, &search);
844 if (!resolve)
845 return;
847 if (resolve->state != CACHE_STATE_PENDING) {
848 /* We can get into this state if we never actually created the pending
849 * resolve, due to finding an earlier cached error or something. Just
850 * ignore it. */
851 if (resolve->pending_connections) {
852 log_warn(LD_BUG,
853 "Address %s is not pending but has pending connections!",
854 escaped_safe_str(address));
855 tor_fragile_assert();
857 return;
860 if (!resolve->pending_connections) {
861 log_warn(LD_BUG,
862 "Address %s is pending but has no pending connections!",
863 escaped_safe_str(address));
864 tor_fragile_assert();
865 return;
867 tor_assert(resolve->pending_connections);
869 /* mark all pending connections to fail */
870 log_debug(LD_EXIT,
871 "Failing all connections waiting on DNS resolve of %s",
872 escaped_safe_str(address));
873 while (resolve->pending_connections) {
874 pend = resolve->pending_connections;
875 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
876 pendconn = pend->conn;
877 assert_connection_ok(TO_CONN(pendconn), 0);
878 tor_assert(pendconn->_base.s == -1);
879 if (!pendconn->_base.marked_for_close) {
880 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
882 circ = circuit_get_by_edge_conn(pendconn);
883 if (circ)
884 circuit_detach_stream(circ, pendconn);
885 if (!pendconn->_base.marked_for_close)
886 connection_free(TO_CONN(pendconn));
887 resolve->pending_connections = pend->next;
888 tor_free(pend);
891 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
892 if (tmp != resolve) {
893 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
894 " the cache. Tried to purge %s (%p); instead got %s (%p).",
895 resolve->address, (void*)resolve,
896 tmp ? tmp->address : "NULL", (void*)tmp);
898 tor_assert(tmp == resolve);
900 resolve->state = CACHE_STATE_DONE;
903 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
904 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
905 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
906 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
908 static void
909 add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
910 const char *hostname, char outcome, uint32_t ttl)
912 cached_resolve_t *resolve;
913 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
914 return;
916 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
917 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
918 // hostname?hostname:"NULL",(int)outcome);
920 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
921 resolve->magic = CACHED_RESOLVE_MAGIC;
922 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
923 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
924 strlcpy(resolve->address, address, sizeof(resolve->address));
925 resolve->is_reverse = is_reverse;
926 if (is_reverse) {
927 if (outcome == DNS_RESOLVE_SUCCEEDED) {
928 tor_assert(hostname);
929 resolve->result.hostname = tor_strdup(hostname);
930 } else {
931 tor_assert(! hostname);
932 resolve->result.hostname = NULL;
934 } else {
935 tor_assert(!hostname);
936 resolve->result.a.addr = addr;
938 resolve->ttl = ttl;
939 assert_resolve_ok(resolve);
940 HT_INSERT(cache_map, &cache_root, resolve);
941 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
944 /** Return true iff <b>address</b> is one of the addresses we use to verify
945 * that well-known sites aren't being hijacked by our DNS servers. */
946 static INLINE int
947 is_test_address(const char *address)
949 or_options_t *options = get_options();
950 return options->ServerDNSTestAddresses &&
951 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
954 /** Called on the OR side when a DNS worker or the eventdns library tells us
955 * the outcome of a DNS resolve: tell all pending connections about the result
956 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
957 * string containing the address to look up; <b>addr</b> is an IPv4 address in
958 * host order; <b>outcome</b> is one of
959 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
961 static void
962 dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
963 const char *hostname, char outcome, uint32_t ttl)
965 pending_connection_t *pend;
966 cached_resolve_t search;
967 cached_resolve_t *resolve, *removed;
968 edge_connection_t *pendconn;
969 circuit_t *circ;
971 assert_cache_ok();
973 strlcpy(search.address, address, sizeof(search.address));
975 resolve = HT_FIND(cache_map, &cache_root, &search);
976 if (!resolve) {
977 int is_test_addr = is_test_address(address);
978 if (!is_test_addr)
979 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
980 escaped_safe_str(address));
981 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
982 return;
984 assert_resolve_ok(resolve);
986 if (resolve->state != CACHE_STATE_PENDING) {
987 /* XXXX Maybe update addr? or check addr for consistency? Or let
988 * VALID replace FAILED? */
989 int is_test_addr = is_test_address(address);
990 if (!is_test_addr)
991 log_notice(LD_EXIT,
992 "Resolved %s which was already resolved; ignoring",
993 escaped_safe_str(address));
994 tor_assert(resolve->pending_connections == NULL);
995 return;
997 /* Removed this assertion: in fact, we'll sometimes get a double answer
998 * to the same question. This can happen when we ask one worker to resolve
999 * X.Y.Z., then we cancel the request, and then we ask another worker to
1000 * resolve X.Y.Z. */
1001 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1003 while (resolve->pending_connections) {
1004 pend = resolve->pending_connections;
1005 pendconn = pend->conn; /* don't pass complex things to the
1006 connection_mark_for_close macro */
1007 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1008 tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
1009 pendconn->address_ttl = ttl;
1011 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1012 /* prevent double-remove. */
1013 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1014 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1015 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1016 /* This detach must happen after we send the end cell. */
1017 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1018 } else {
1019 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1020 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1021 /* This detach must happen after we send the resolved cell. */
1022 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1024 connection_free(TO_CONN(pendconn));
1025 } else {
1026 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1027 tor_assert(!is_reverse);
1028 /* prevent double-remove. */
1029 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1031 circ = circuit_get_by_edge_conn(pend->conn);
1032 tor_assert(circ);
1033 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1034 /* unlink pend->conn from resolving_streams, */
1035 circuit_detach_stream(circ, pend->conn);
1036 /* and link it to n_streams */
1037 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1038 pend->conn->on_circuit = circ;
1039 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1041 connection_exit_connect(pend->conn);
1042 } else {
1043 /* prevent double-remove. This isn't really an accurate state,
1044 * but it does the right thing. */
1045 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1046 if (is_reverse)
1047 send_resolved_hostname_cell(pendconn, hostname);
1048 else
1049 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1050 circ = circuit_get_by_edge_conn(pendconn);
1051 tor_assert(circ);
1052 circuit_detach_stream(circ, pendconn);
1053 connection_free(TO_CONN(pendconn));
1056 resolve->pending_connections = pend->next;
1057 tor_free(pend);
1060 resolve->state = CACHE_STATE_DONE;
1061 removed = HT_REMOVE(cache_map, &cache_root, &search);
1062 if (removed != resolve) {
1063 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1064 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1065 resolve->address, (void*)resolve,
1066 removed ? removed->address : "NULL", (void*)removed);
1068 assert_resolve_ok(resolve);
1069 assert_cache_ok();
1071 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1072 assert_cache_ok();
1075 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1076 * a transient failure. */
1077 static int
1078 evdns_err_is_transient(int err)
1080 switch (err)
1082 case DNS_ERR_SERVERFAILED:
1083 case DNS_ERR_TRUNCATED:
1084 case DNS_ERR_TIMEOUT:
1085 return 1;
1086 default:
1087 return 0;
1091 /** Configure eventdns nameservers if force is true, or if the configuration
1092 * has changed since the last time we called this function, or if we failed on
1093 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1094 * options->ServerDNSResolvConfFile; on Windows, this reads from
1095 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1096 * -1 on failure. */
1097 static int
1098 configure_nameservers(int force)
1100 or_options_t *options;
1101 const char *conf_fname;
1102 struct stat st;
1103 int r;
1104 options = get_options();
1105 conf_fname = options->ServerDNSResolvConfFile;
1106 #ifndef MS_WINDOWS
1107 if (!conf_fname)
1108 conf_fname = "/etc/resolv.conf";
1109 #endif
1111 if (options->OutboundBindAddress) {
1112 tor_addr_t addr;
1113 if (tor_addr_from_str(&addr, options->OutboundBindAddress) < 0) {
1114 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
1115 options->OutboundBindAddress);
1116 } else {
1117 int socklen;
1118 struct sockaddr_storage ss;
1119 socklen = tor_addr_to_sockaddr(&addr, 0,
1120 (struct sockaddr *)&ss, sizeof(ss));
1121 if (socklen < 0) {
1122 log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
1123 " Ignoring.");
1124 } else {
1125 evdns_set_default_outgoing_bind_address((struct sockaddr *)&ss,
1126 socklen);
1131 if (options->ServerDNSRandomizeCase)
1132 evdns_set_option("randomize-case:", "1", DNS_OPTIONS_ALL);
1133 else
1134 evdns_set_option("randomize-case:", "0", DNS_OPTIONS_ALL);
1136 evdns_set_log_fn(evdns_log_cb);
1137 if (conf_fname) {
1138 if (stat(conf_fname, &st)) {
1139 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1140 conf_fname, strerror(errno));
1141 goto err;
1143 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1144 && st.st_mtime == resolv_conf_mtime) {
1145 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1146 return 0;
1148 if (nameservers_configured) {
1149 evdns_search_clear();
1150 evdns_clear_nameservers_and_suspend();
1152 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1153 if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
1154 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1155 conf_fname, conf_fname, r);
1156 goto err;
1158 if (evdns_count_nameservers() == 0) {
1159 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1160 goto err;
1162 tor_free(resolv_conf_fname);
1163 resolv_conf_fname = tor_strdup(conf_fname);
1164 resolv_conf_mtime = st.st_mtime;
1165 if (nameservers_configured)
1166 evdns_resume();
1168 #ifdef MS_WINDOWS
1169 else {
1170 if (nameservers_configured) {
1171 evdns_search_clear();
1172 evdns_clear_nameservers_and_suspend();
1174 if (evdns_config_windows_nameservers()) {
1175 log_warn(LD_EXIT,"Could not config nameservers.");
1176 goto err;
1178 if (evdns_count_nameservers() == 0) {
1179 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1180 "your Windows configuration.");
1181 goto err;
1183 if (nameservers_configured)
1184 evdns_resume();
1185 tor_free(resolv_conf_fname);
1186 resolv_conf_mtime = 0;
1188 #endif
1190 if (evdns_count_nameservers() == 1) {
1191 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
1192 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
1193 } else {
1194 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
1195 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
1198 dns_servers_relaunch_checks();
1200 nameservers_configured = 1;
1201 if (nameserver_config_failed) {
1202 nameserver_config_failed = 0;
1203 mark_my_descriptor_dirty();
1205 return 0;
1206 err:
1207 nameservers_configured = 0;
1208 if (! nameserver_config_failed) {
1209 nameserver_config_failed = 1;
1210 mark_my_descriptor_dirty();
1212 return -1;
1215 /** For eventdns: Called when we get an answer for a request we launched.
1216 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1218 static void
1219 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1220 void *arg)
1222 char *string_address = arg;
1223 uint8_t is_reverse = 0;
1224 int status = DNS_RESOLVE_FAILED_PERMANENT;
1225 uint32_t addr = 0;
1226 const char *hostname = NULL;
1227 int was_wildcarded = 0;
1229 if (result == DNS_ERR_NONE) {
1230 if (type == DNS_IPv4_A && count) {
1231 char answer_buf[INET_NTOA_BUF_LEN+1];
1232 struct in_addr in;
1233 char *escaped_address;
1234 uint32_t *addrs = addresses;
1235 in.s_addr = addrs[0];
1236 addr = ntohl(addrs[0]);
1237 status = DNS_RESOLVE_SUCCEEDED;
1238 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1239 escaped_address = esc_for_log(string_address);
1241 if (answer_is_wildcarded(answer_buf)) {
1242 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1243 "address %s; treating as a failure.",
1244 safe_str(escaped_address),
1245 escaped_safe_str(answer_buf));
1246 was_wildcarded = 1;
1247 addr = 0;
1248 status = DNS_RESOLVE_FAILED_PERMANENT;
1249 } else {
1250 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1251 safe_str(escaped_address),
1252 escaped_safe_str(answer_buf));
1254 tor_free(escaped_address);
1255 } else if (type == DNS_PTR && count) {
1256 char *escaped_address;
1257 is_reverse = 1;
1258 hostname = ((char**)addresses)[0];
1259 status = DNS_RESOLVE_SUCCEEDED;
1260 escaped_address = esc_for_log(string_address);
1261 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1262 safe_str(escaped_address),
1263 escaped_safe_str(hostname));
1264 tor_free(escaped_address);
1265 } else if (count) {
1266 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1267 escaped_safe_str(string_address));
1268 } else {
1269 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1270 escaped_safe_str(string_address));
1272 } else {
1273 if (evdns_err_is_transient(result))
1274 status = DNS_RESOLVE_FAILED_TRANSIENT;
1276 if (was_wildcarded) {
1277 if (is_test_address(string_address)) {
1278 /* Ick. We're getting redirected on known-good addresses. Our DNS
1279 * server must really hate us. */
1280 add_wildcarded_test_address(string_address);
1283 if (result != DNS_ERR_SHUTDOWN)
1284 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1285 tor_free(string_address);
1288 /** For eventdns: start resolving as necessary to find the target for
1289 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1290 * 0 on "resolve launched." */
1291 static int
1292 launch_resolve(edge_connection_t *exitconn)
1294 char *addr = tor_strdup(exitconn->_base.address);
1295 tor_addr_t a;
1296 int r;
1297 int options = get_options()->ServerDNSSearchDomains ? 0
1298 : DNS_QUERY_NO_SEARCH;
1299 /* What? Nameservers not configured? Sounds like a bug. */
1300 if (!nameservers_configured) {
1301 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1302 "launched. Configuring.");
1303 if (configure_nameservers(1) < 0) {
1304 return -1;
1308 r = tor_addr_parse_reverse_lookup_name(
1309 &a, exitconn->_base.address, AF_UNSPEC, 0);
1310 if (r == 0) {
1311 log_info(LD_EXIT, "Launching eventdns request for %s",
1312 escaped_safe_str(exitconn->_base.address));
1313 r = evdns_resolve_ipv4(exitconn->_base.address, options,
1314 evdns_callback, addr);
1315 } else if (r == 1) {
1316 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1317 escaped_safe_str(exitconn->_base.address));
1318 if (tor_addr_family(&a) == AF_INET)
1319 r = evdns_resolve_reverse(tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
1320 evdns_callback, addr);
1321 else
1322 r = evdns_resolve_reverse_ipv6(tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
1323 evdns_callback, addr);
1324 } else if (r == -1) {
1325 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1328 if (r) {
1329 log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
1330 escaped_safe_str(addr), r);
1331 r = evdns_err_is_transient(r) ? -2 : -1;
1332 tor_free(addr); /* There is no evdns request in progress; stop
1333 * addr from getting leaked. */
1335 return r;
1338 /** How many requests for bogus addresses have we launched so far? */
1339 static int n_wildcard_requests = 0;
1341 /** Map from dotted-quad IP address in response to an int holding how many
1342 * times we've seen it for a randomly generated (hopefully bogus) address. It
1343 * would be easier to use definitely-invalid addresses (as specified by
1344 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1345 static strmap_t *dns_wildcard_response_count = NULL;
1347 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1348 * nameserver wants to return in response to requests for nonexistent domains.
1350 static smartlist_t *dns_wildcard_list = NULL;
1351 /** True iff we've logged about a single address getting wildcarded.
1352 * Subsequent warnings will be less severe. */
1353 static int dns_wildcard_one_notice_given = 0;
1354 /** True iff we've warned that our DNS server is wildcarding too many failures.
1356 static int dns_wildcard_notice_given = 0;
1358 /** List of supposedly good addresses that are getting wildcarded to the
1359 * same addresses as nonexistent addresses. */
1360 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1361 /** True iff we've warned about a test address getting wildcarded */
1362 static int dns_wildcarded_test_address_notice_given = 0;
1363 /** True iff all addresses seem to be getting wildcarded. */
1364 static int dns_is_completely_invalid = 0;
1366 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1367 * a hopefully bogus address. */
1368 static void
1369 wildcard_increment_answer(const char *id)
1371 int *ip;
1372 if (!dns_wildcard_response_count)
1373 dns_wildcard_response_count = strmap_new();
1375 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1376 if (!ip) {
1377 ip = tor_malloc_zero(sizeof(int));
1378 strmap_set(dns_wildcard_response_count, id, ip);
1380 ++*ip;
1382 if (*ip > 5 && n_wildcard_requests > 10) {
1383 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1384 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1385 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1386 "Your DNS provider has given \"%s\" as an answer for %d different "
1387 "invalid addresses. Apparently they are hijacking DNS failures. "
1388 "I'll try to correct for this by treating future occurrences of "
1389 "\"%s\" as 'not found'.", id, *ip, id);
1390 smartlist_add(dns_wildcard_list, tor_strdup(id));
1392 if (!dns_wildcard_notice_given)
1393 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1394 dns_wildcard_notice_given = 1;
1398 /** Note that a single test address (one believed to be good) seems to be
1399 * getting redirected to the same IP as failures are. */
1400 static void
1401 add_wildcarded_test_address(const char *address)
1403 int n, n_test_addrs;
1404 if (!dns_wildcarded_test_address_list)
1405 dns_wildcarded_test_address_list = smartlist_create();
1407 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1408 return;
1410 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1411 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1413 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1414 n = smartlist_len(dns_wildcarded_test_address_list);
1415 if (n > n_test_addrs/2) {
1416 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1417 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1418 "address. It has done this with %d test addresses so far. I'm "
1419 "going to stop being an exit node for now, since our DNS seems so "
1420 "broken.", address, n);
1421 if (!dns_is_completely_invalid) {
1422 dns_is_completely_invalid = 1;
1423 mark_my_descriptor_dirty();
1425 if (!dns_wildcarded_test_address_notice_given)
1426 control_event_server_status(LOG_WARN, "DNS_USELESS");
1427 dns_wildcarded_test_address_notice_given = 1;
1431 /** Callback function when we get an answer (possibly failing) for a request
1432 * for a (hopefully) nonexistent domain. */
1433 static void
1434 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1435 void *addresses, void *arg)
1437 (void)ttl;
1438 ++n_wildcard_requests;
1439 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1440 uint32_t *addrs = addresses;
1441 int i;
1442 char *string_address = arg;
1443 for (i = 0; i < count; ++i) {
1444 char answer_buf[INET_NTOA_BUF_LEN+1];
1445 struct in_addr in;
1446 in.s_addr = addrs[i];
1447 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1448 wildcard_increment_answer(answer_buf);
1450 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1451 "Your DNS provider gave an answer for \"%s\", which "
1452 "is not supposed to exist. Apparently they are hijacking "
1453 "DNS failures. Trying to correct for this. We've noticed %d "
1454 "possibly bad address%s so far.",
1455 string_address, strmap_size(dns_wildcard_response_count),
1456 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1457 dns_wildcard_one_notice_given = 1;
1459 tor_free(arg);
1462 /** Launch a single request for a nonexistent hostname consisting of between
1463 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1464 * <b>suffix</b> */
1465 static void
1466 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1468 char *addr;
1469 int r;
1471 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1472 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1473 "domains with request for bogus hostname \"%s\"", addr);
1475 r = evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1476 addr,
1477 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1478 /* This "addr" is an argument to the callback*/ addr);
1479 if (r) {
1480 /* There is no evdns request in progress; stop addr from getting leaked */
1481 tor_free(addr);
1485 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1486 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1487 static void
1488 launch_test_addresses(int fd, short event, void *args)
1490 or_options_t *options = get_options();
1491 (void)fd;
1492 (void)event;
1493 (void)args;
1495 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1496 "hijack *everything*.");
1497 /* This situation is worse than the failure-hijacking situation. When this
1498 * happens, we're no good for DNS requests at all, and we shouldn't really
1499 * be an exit server.*/
1500 if (!options->ServerDNSTestAddresses)
1501 return;
1502 SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
1504 int r = evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
1505 tor_strdup(address));
1506 if (r)
1507 log_info(LD_EXIT, "eventdns rejected test address %s: error %d",
1508 escaped_safe_str(address), r);
1512 #define N_WILDCARD_CHECKS 2
1514 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1515 * hostnames, and see if we can catch our nameserver trying to hijack them and
1516 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1517 * buy these lovely encyclopedias" page. */
1518 static void
1519 dns_launch_wildcard_checks(void)
1521 int i;
1522 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1523 "to hijack DNS failures.");
1524 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1525 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1526 * to 'comply' with rfc2606, refrain from giving A records for these.
1527 * This is the standards-compliance equivalent of making sure that your
1528 * crackhouse's elevator inspection certificate is up to date.
1530 launch_wildcard_check(2, 16, ".invalid");
1531 launch_wildcard_check(2, 16, ".test");
1533 /* These will break specs if there are ever any number of
1534 * 8+-character top-level domains. */
1535 launch_wildcard_check(8, 16, "");
1537 /* Try some random .com/org/net domains. This will work fine so long as
1538 * not too many resolve to the same place. */
1539 launch_wildcard_check(8, 16, ".com");
1540 launch_wildcard_check(8, 16, ".org");
1541 launch_wildcard_check(8, 16, ".net");
1545 /** If appropriate, start testing whether our DNS servers tend to lie to
1546 * us. */
1547 void
1548 dns_launch_correctness_checks(void)
1550 static struct event launch_event;
1551 struct timeval timeout;
1552 if (!get_options()->ServerDNSDetectHijacking)
1553 return;
1554 dns_launch_wildcard_checks();
1556 /* Wait a while before launching requests for test addresses, so we can
1557 * get the results from checking for wildcarding. */
1558 evtimer_set(&launch_event, launch_test_addresses, NULL);
1559 timeout.tv_sec = 30;
1560 timeout.tv_usec = 0;
1561 if (evtimer_add(&launch_event, &timeout)<0) {
1562 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1566 /** Return true iff our DNS servers lie to us too much to be trusted. */
1568 dns_seems_to_be_broken(void)
1570 return dns_is_completely_invalid;
1573 /** Forget what we've previously learned about our DNS servers' correctness. */
1574 void
1575 dns_reset_correctness_checks(void)
1577 if (dns_wildcard_response_count) {
1578 strmap_free(dns_wildcard_response_count, _tor_free);
1579 dns_wildcard_response_count = NULL;
1581 n_wildcard_requests = 0;
1583 if (dns_wildcard_list) {
1584 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1585 smartlist_clear(dns_wildcard_list);
1587 if (dns_wildcarded_test_address_list) {
1588 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1589 tor_free(cp));
1590 smartlist_clear(dns_wildcarded_test_address_list);
1592 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1593 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1596 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1597 * returned in response to requests for nonexistent hostnames. */
1598 static int
1599 answer_is_wildcarded(const char *ip)
1601 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1604 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1605 static void
1606 assert_resolve_ok(cached_resolve_t *resolve)
1608 tor_assert(resolve);
1609 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1610 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1611 tor_assert(tor_strisnonupper(resolve->address));
1612 if (resolve->state != CACHE_STATE_PENDING) {
1613 tor_assert(!resolve->pending_connections);
1615 if (resolve->state == CACHE_STATE_PENDING ||
1616 resolve->state == CACHE_STATE_DONE) {
1617 tor_assert(!resolve->ttl);
1618 if (resolve->is_reverse)
1619 tor_assert(!resolve->result.hostname);
1620 else
1621 tor_assert(!resolve->result.a.addr);
1625 #ifdef DEBUG_DNS_CACHE
1626 /** Exit with an assertion if the DNS cache is corrupt. */
1627 static void
1628 _assert_cache_ok(void)
1630 cached_resolve_t **resolve;
1631 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1632 if (bad_rep) {
1633 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1634 tor_assert(!bad_rep);
1637 HT_FOREACH(resolve, cache_map, &cache_root) {
1638 assert_resolve_ok(*resolve);
1639 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1641 if (!cached_resolve_pqueue)
1642 return;
1644 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1645 _compare_cached_resolves_by_expiry);
1647 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1649 if (res->state == CACHE_STATE_DONE) {
1650 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1651 tor_assert(!found || found != res);
1652 } else {
1653 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1654 tor_assert(found);
1658 #endif