dns.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  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 */
  5. /**
  6. * \file dns.c
  7. * \brief Implements a local cache for DNS results for Tor servers.
  8. * This is implemented as a wrapper around Adam Langley's eventdns.c code.
  9. * (We can't just use gethostbyname() and friends because we really need to
  10. * be nonblocking.)
  11. **/
  12. #include "or.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "control.h"
  19. #include "dns.h"
  20. #include "router.h"
  21. #include "ht.h"
  22. #ifdef HAVE_EVENT2_DNS_H
  23. #include <event2/event.h>
  24. #include <event2/dns.h>
  25. #else
  26. #include <event.h>
  27. #include "eventdns.h"
  28. #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  29. #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  30. #endif
  31. #endif
  32. #ifndef HAVE_EVENT2_DNS_H
  33. struct evdns_base;
  34. struct evdns_request;
  35. #define evdns_base_new(x,y) tor_malloc(1)
  36. #define evdns_base_clear_nameservers_and_suspend(base) \
  37. evdns_clear_nameservers_and_suspend()
  38. #define evdns_base_search_clear(base) evdns_search_clear()
  39. #define evdns_base_set_default_outgoing_bind_address(base, a, len) \
  40. evdns_set_default_outgoing_bind_address((a),(len))
  41. #define evdns_base_resolv_conf_parse(base, options, fname) \
  42. evdns_resolv_conf_parse((options), (fname))
  43. #define evdns_base_count_nameservers(base) \
  44. evdns_count_nameservers()
  45. #define evdns_base_resume(base) \
  46. evdns_resume()
  47. #define evdns_base_config_windows_nameservers(base) \
  48. evdns_config_windows_nameservers()
  49. #define evdns_base_set_option_(base, opt, val) \
  50. evdns_set_option((opt),(val),DNS_OPTIONS_ALL)
  51. #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
  52. ((evdns_resolve_ipv4(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
  53. #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
  54. ((evdns_resolve_reverse(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
  55. #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
  56. ((evdns_resolve_reverse_ipv6(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
  57. #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
  58. #define evdns_base_set_option_(base, opt, val) \
  59. evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
  60. #else
  61. #define evdns_base_set_option_ evdns_base_set_option
  62. #endif
  63. /** Longest hostname we're willing to resolve. */
  64. #define MAX_ADDRESSLEN 256
  65. /** How long will we wait for an answer from the resolver before we decide
  66. * that the resolver is wedged? */
  67. #define RESOLVE_MAX_TIMEOUT 300
  68. /** Possible outcomes from hostname lookup: permanent failure,
  69. * transient (retryable) failure, and success. */
  70. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  71. #define DNS_RESOLVE_FAILED_PERMANENT 2
  72. #define DNS_RESOLVE_SUCCEEDED 3
  73. /** Our evdns_base; this structure handles all our name lookups. */
  74. static struct evdns_base *the_evdns_base = NULL;
  75. /** Have we currently configured nameservers with eventdns? */
  76. static int nameservers_configured = 0;
  77. /** Did our most recent attempt to configure nameservers with eventdns fail? */
  78. static int nameserver_config_failed = 0;
  79. /** What was the resolv_conf fname we last used when configuring the
  80. * nameservers? Used to check whether we need to reconfigure. */
  81. static char *resolv_conf_fname = NULL;
  82. /** What was the mtime on the resolv.conf file we last used when configuring
  83. * the nameservers? Used to check whether we need to reconfigure. */
  84. static time_t resolv_conf_mtime = 0;
  85. /** Linked list of connections waiting for a DNS answer. */
  86. typedef struct pending_connection_t {
  87. edge_connection_t *conn;
  88. struct pending_connection_t *next;
  89. } pending_connection_t;
  90. /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
  91. * pointers and memory stomping. */
  92. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  93. /* Possible states for a cached resolve_t */
  94. /** We are waiting for the resolver system to tell us an answer here.
  95. * When we get one, or when we time out, the state of this cached_resolve_t
  96. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  97. * entry. This cached_resolve_t will be in the hash table so that we will
  98. * know not to launch more requests for this addr, but rather to add more
  99. * connections to the pending list for the addr. */
  100. #define CACHE_STATE_PENDING 0
  101. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  102. * Now we're waiting for this cached_resolve_t to expire. This should
  103. * have no pending connections, and should not appear in the hash table. */
  104. #define CACHE_STATE_DONE 1
  105. /** We are caching an answer for this address. This should have no pending
  106. * connections, and should appear in the hash table. */
  107. #define CACHE_STATE_CACHED_VALID 2
  108. /** We are caching a failure for this address. This should have no pending
  109. * connections, and should appear in the hash table */
  110. #define CACHE_STATE_CACHED_FAILED 3
  111. /** A DNS request: possibly completed, possibly pending; cached_resolve
  112. * structs are stored at the OR side in a hash table, and as a linked
  113. * list from oldest to newest.
  114. */
  115. typedef struct cached_resolve_t {
  116. HT_ENTRY(cached_resolve_t) node;
  117. uint32_t magic;
  118. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  119. union {
  120. struct {
  121. struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
  122. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  123. } a;
  124. char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
  125. } result;
  126. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  127. uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
  128. time_t expire; /**< Remove items from cache after this time. */
  129. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  130. /** Connections that want to know when we get an answer for this resolve. */
  131. pending_connection_t *pending_connections;
  132. /** Position of this element in the heap*/
  133. int minheap_idx;
  134. } cached_resolve_t;
  135. static void purge_expired_resolves(time_t now);
  136. static void dns_found_answer(const char *address, uint8_t is_reverse,
  137. uint32_t addr, const char *hostname, char outcome,
  138. uint32_t ttl);
  139. static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
  140. static int launch_resolve(edge_connection_t *exitconn);
  141. static void add_wildcarded_test_address(const char *address);
  142. static int configure_nameservers(int force);
  143. static int answer_is_wildcarded(const char *ip);
  144. static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  145. or_circuit_t *oncirc, char **resolved_to_hostname);
  146. #ifdef DEBUG_DNS_CACHE
  147. static void _assert_cache_ok(void);
  148. #define assert_cache_ok() _assert_cache_ok()
  149. #else
  150. #define assert_cache_ok() STMT_NIL
  151. #endif
  152. static void assert_resolve_ok(cached_resolve_t *resolve);
  153. /** Hash table of cached_resolve objects. */
  154. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  155. /** Function to compare hashed resolves on their addresses; used to
  156. * implement hash tables. */
  157. static INLINE int
  158. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  159. {
  160. /* make this smarter one day? */
  161. assert_resolve_ok(a); // Not b; b may be just a search.
  162. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  163. }
  164. /** Hash function for cached_resolve objects */
  165. static INLINE unsigned int
  166. cached_resolve_hash(cached_resolve_t *a)
  167. {
  168. return ht_string_hash(a->address);
  169. }
  170. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  171. cached_resolves_eq)
  172. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  173. cached_resolves_eq, 0.6, malloc, realloc, free)
  174. /** Initialize the DNS cache. */
  175. static void
  176. init_cache_map(void)
  177. {
  178. HT_INIT(cache_map, &cache_root);
  179. }
  180. /** Helper: called by eventdns when eventdns wants to log something. */
  181. static void
  182. evdns_log_cb(int warn, const char *msg)
  183. {
  184. const char *cp;
  185. static int all_down = 0;
  186. int severity = warn ? LOG_WARN : LOG_INFO;
  187. if (!strcmpstart(msg, "Resolve requested for") &&
  188. get_options()->SafeLogging) {
  189. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  190. return;
  191. } else if (!strcmpstart(msg, "Search: ")) {
  192. return;
  193. }
  194. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  195. char *ns = tor_strndup(msg+11, cp-(msg+11));
  196. const char *err = strchr(cp, ':')+2;
  197. tor_assert(err);
  198. /* Don't warn about a single failed nameserver; we'll warn with 'all
  199. * nameservers have failed' if we're completely out of nameservers;
  200. * otherwise, the situation is tolerable. */
  201. severity = LOG_INFO;
  202. control_event_server_status(LOG_NOTICE,
  203. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  204. ns, escaped(err));
  205. tor_free(ns);
  206. } else if (!strcmpstart(msg, "Nameserver ") &&
  207. (cp=strstr(msg, " is back up"))) {
  208. char *ns = tor_strndup(msg+11, cp-(msg+11));
  209. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  210. all_down = 0;
  211. control_event_server_status(LOG_NOTICE,
  212. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  213. tor_free(ns);
  214. } else if (!strcmp(msg, "All nameservers have failed")) {
  215. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  216. all_down = 1;
  217. }
  218. log(severity, LD_EXIT, "eventdns: %s", msg);
  219. }
  220. /** Helper: passed to eventdns.c as a callback so it can generate random
  221. * numbers for transaction IDs and 0x20-hack coding. */
  222. static void
  223. _dns_randfn(char *b, size_t n)
  224. {
  225. crypto_rand(b,n);
  226. }
  227. /** Initialize the DNS subsystem; called by the OR process. */
  228. int
  229. dns_init(void)
  230. {
  231. init_cache_map();
  232. evdns_set_random_bytes_fn(_dns_randfn);
  233. if (server_mode(get_options())) {
  234. int r = configure_nameservers(1);
  235. return r;
  236. }
  237. return 0;
  238. }
  239. /** Called when DNS-related options change (or may have changed). Returns -1
  240. * on failure, 0 on success. */
  241. int
  242. dns_reset(void)
  243. {
  244. or_options_t *options = get_options();
  245. if (! server_mode(options)) {
  246. if (!the_evdns_base) {
  247. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  248. log_err(LD_BUG, "Couldn't create an evdns_base");
  249. return -1;
  250. }
  251. }
  252. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  253. evdns_base_search_clear(the_evdns_base);
  254. nameservers_configured = 0;
  255. tor_free(resolv_conf_fname);
  256. resolv_conf_mtime = 0;
  257. } else {
  258. if (configure_nameservers(0) < 0) {
  259. return -1;
  260. }
  261. }
  262. return 0;
  263. }
  264. /** Return true iff the most recent attempt to initialize the DNS subsystem
  265. * failed. */
  266. int
  267. has_dns_init_failed(void)
  268. {
  269. return nameserver_config_failed;
  270. }
  271. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  272. * OP that asked us to resolve it. */
  273. uint32_t
  274. dns_clip_ttl(uint32_t ttl)
  275. {
  276. if (ttl < MIN_DNS_TTL)
  277. return MIN_DNS_TTL;
  278. else if (ttl > MAX_DNS_TTL)
  279. return MAX_DNS_TTL;
  280. else
  281. return ttl;
  282. }
  283. /** Helper: Given a TTL from a DNS response, determine how long to hold it in
  284. * our cache. */
  285. static uint32_t
  286. dns_get_expiry_ttl(uint32_t ttl)
  287. {
  288. if (ttl < MIN_DNS_TTL)
  289. return MIN_DNS_TTL;
  290. else if (ttl > MAX_DNS_ENTRY_AGE)
  291. return MAX_DNS_ENTRY_AGE;
  292. else
  293. return ttl;
  294. }
  295. /** Helper: free storage held by an entry in the DNS cache. */
  296. static void
  297. _free_cached_resolve(cached_resolve_t *r)
  298. {
  299. if (!r)
  300. return;
  301. while (r->pending_connections) {
  302. pending_connection_t *victim = r->pending_connections;
  303. r->pending_connections = victim->next;
  304. tor_free(victim);
  305. }
  306. if (r->is_reverse)
  307. tor_free(r->result.hostname);
  308. r->magic = 0xFF00FF00;
  309. tor_free(r);
  310. }
  311. /** Compare two cached_resolve_t pointers by expiry time, and return
  312. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  313. * the priority queue implementation. */
  314. static int
  315. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  316. {
  317. const cached_resolve_t *a = _a, *b = _b;
  318. if (a->expire < b->expire)
  319. return -1;
  320. else if (a->expire == b->expire)
  321. return 0;
  322. else
  323. return 1;
  324. }
  325. /** Priority queue of cached_resolve_t objects to let us know when they
  326. * will expire. */
  327. static smartlist_t *cached_resolve_pqueue = NULL;
  328. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  329. * priority queue */
  330. static void
  331. set_expiry(cached_resolve_t *resolve, time_t expires)
  332. {
  333. tor_assert(resolve && resolve->expire == 0);
  334. if (!cached_resolve_pqueue)
  335. cached_resolve_pqueue = smartlist_create();
  336. resolve->expire = expires;
  337. smartlist_pqueue_add(cached_resolve_pqueue,
  338. _compare_cached_resolves_by_expiry,
  339. STRUCT_OFFSET(cached_resolve_t, minheap_idx),
  340. resolve);
  341. }
  342. /** Free all storage held in the DNS cache and related structures. */
  343. void
  344. dns_free_all(void)
  345. {
  346. cached_resolve_t **ptr, **next, *item;
  347. assert_cache_ok();
  348. if (cached_resolve_pqueue) {
  349. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  350. {
  351. if (res->state == CACHE_STATE_DONE)
  352. _free_cached_resolve(res);
  353. });
  354. }
  355. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  356. item = *ptr;
  357. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  358. _free_cached_resolve(item);
  359. }
  360. HT_CLEAR(cache_map, &cache_root);
  361. smartlist_free(cached_resolve_pqueue);
  362. cached_resolve_pqueue = NULL;
  363. tor_free(resolv_conf_fname);
  364. }
  365. /** Remove every cached_resolve whose <b>expire</b> time is before or
  366. * equal to <b>now</b> from the cache. */
  367. static void
  368. purge_expired_resolves(time_t now)
  369. {
  370. cached_resolve_t *resolve, *removed;
  371. pending_connection_t *pend;
  372. edge_connection_t *pendconn;
  373. assert_cache_ok();
  374. if (!cached_resolve_pqueue)
  375. return;
  376. while (smartlist_len(cached_resolve_pqueue)) {
  377. resolve = smartlist_get(cached_resolve_pqueue, 0);
  378. if (resolve->expire > now)
  379. break;
  380. smartlist_pqueue_pop(cached_resolve_pqueue,
  381. _compare_cached_resolves_by_expiry,
  382. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  383. if (resolve->state == CACHE_STATE_PENDING) {
  384. log_debug(LD_EXIT,
  385. "Expiring a dns resolve %s that's still pending. Forgot to "
  386. "cull it? DNS resolve didn't tell us about the timeout?",
  387. escaped_safe_str(resolve->address));
  388. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  389. resolve->state == CACHE_STATE_CACHED_FAILED) {
  390. log_debug(LD_EXIT,
  391. "Forgetting old cached resolve (address %s, expires %lu)",
  392. escaped_safe_str(resolve->address),
  393. (unsigned long)resolve->expire);
  394. tor_assert(!resolve->pending_connections);
  395. } else {
  396. tor_assert(resolve->state == CACHE_STATE_DONE);
  397. tor_assert(!resolve->pending_connections);
  398. }
  399. if (resolve->pending_connections) {
  400. log_debug(LD_EXIT,
  401. "Closing pending connections on timed-out DNS resolve!");
  402. tor_fragile_assert();
  403. while (resolve->pending_connections) {
  404. pend = resolve->pending_connections;
  405. resolve->pending_connections = pend->next;
  406. /* Connections should only be pending if they have no socket. */
  407. tor_assert(pend->conn->_base.s == -1);
  408. pendconn = pend->conn;
  409. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  410. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  411. connection_free(TO_CONN(pendconn));
  412. tor_free(pend);
  413. }
  414. }
  415. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  416. resolve->state == CACHE_STATE_CACHED_FAILED ||
  417. resolve->state == CACHE_STATE_PENDING) {
  418. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  419. if (removed != resolve) {
  420. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  421. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  422. resolve->address, (void*)resolve,
  423. removed ? removed->address : "NULL", (void*)removed);
  424. }
  425. tor_assert(removed == resolve);
  426. } else {
  427. /* This should be in state DONE. Make sure it's not in the cache. */
  428. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  429. tor_assert(tmp != resolve);
  430. }
  431. if (resolve->is_reverse)
  432. tor_free(resolve->result.hostname);
  433. resolve->magic = 0xF0BBF0BB;
  434. tor_free(resolve);
  435. }
  436. assert_cache_ok();
  437. }
  438. /** Send a response to the RESOLVE request of a connection.
  439. * <b>answer_type</b> must be one of
  440. * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
  441. *
  442. * If <b>circ</b> is provided, and we have a cached answer, send the
  443. * answer back along circ; otherwise, send the answer back along
  444. * <b>conn</b>'s attached circuit.
  445. */
  446. static void
  447. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
  448. {
  449. char buf[RELAY_PAYLOAD_SIZE];
  450. size_t buflen;
  451. uint32_t ttl;
  452. buf[0] = answer_type;
  453. ttl = dns_clip_ttl(conn->address_ttl);
  454. switch (answer_type)
  455. {
  456. case RESOLVED_TYPE_IPV4:
  457. buf[1] = 4;
  458. set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
  459. set_uint32(buf+6, htonl(ttl));
  460. buflen = 10;
  461. break;
  462. /*XXXX IP6 need ipv6 implementation */
  463. case RESOLVED_TYPE_ERROR_TRANSIENT:
  464. case RESOLVED_TYPE_ERROR:
  465. {
  466. const char *errmsg = "Error resolving hostname";
  467. size_t msglen = strlen(errmsg);
  468. buf[1] = msglen;
  469. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  470. set_uint32(buf+2+msglen, htonl(ttl));
  471. buflen = 6+msglen;
  472. break;
  473. }
  474. default:
  475. tor_assert(0);
  476. return;
  477. }
  478. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  479. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  480. }
  481. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  482. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  483. * The answer type will be RESOLVED_HOSTNAME.
  484. *
  485. * If <b>circ</b> is provided, and we have a cached answer, send the
  486. * answer back along circ; otherwise, send the answer back along
  487. * <b>conn</b>'s attached circuit.
  488. */
  489. static void
  490. send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
  491. {
  492. char buf[RELAY_PAYLOAD_SIZE];
  493. size_t buflen;
  494. uint32_t ttl;
  495. size_t namelen = strlen(hostname);
  496. tor_assert(hostname);
  497. tor_assert(namelen < 256);
  498. ttl = dns_clip_ttl(conn->address_ttl);
  499. buf[0] = RESOLVED_TYPE_HOSTNAME;
  500. buf[1] = (uint8_t)namelen;
  501. memcpy(buf+2, hostname, namelen);
  502. set_uint32(buf+2+namelen, htonl(ttl));
  503. buflen = 2+namelen+4;
  504. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  505. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  506. // log_notice(LD_EXIT, "Sent");
  507. }
  508. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  509. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  510. * If resolve failed, free exitconn and return -1.
  511. *
  512. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  513. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  514. * need to send back an END cell, since connection_exit_begin_conn will
  515. * do that for us.)
  516. *
  517. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  518. * circuit.
  519. *
  520. * Else, if seen before and pending, add conn to the pending list,
  521. * and return 0.
  522. *
  523. * Else, if not seen before, add conn to pending list, hand to
  524. * dns farm, and return 0.
  525. *
  526. * Exitconn's on_circuit field must be set, but exitconn should not
  527. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  528. * On success, link the connection to n_streams if it's an exit connection.
  529. * On "pending", link the connection to resolving streams. Otherwise,
  530. * clear its on_circuit field.
  531. */
  532. int
  533. dns_resolve(edge_connection_t *exitconn)
  534. {
  535. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  536. int is_resolve, r;
  537. char *hostname = NULL;
  538. is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
  539. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
  540. switch (r) {
  541. case 1:
  542. /* We got an answer without a lookup -- either the answer was
  543. * cached, or it was obvious (like an IP address). */
  544. if (is_resolve) {
  545. /* Send the answer back right now, and detach. */
  546. if (hostname)
  547. send_resolved_hostname_cell(exitconn, hostname);
  548. else
  549. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  550. exitconn->on_circuit = NULL;
  551. } else {
  552. /* Add to the n_streams list; the calling function will send back a
  553. * connected cell. */
  554. exitconn->next_stream = oncirc->n_streams;
  555. oncirc->n_streams = exitconn;
  556. }
  557. break;
  558. case 0:
  559. /* The request is pending: add the connection into the linked list of
  560. * resolving_streams on this circuit. */
  561. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  562. exitconn->next_stream = oncirc->resolving_streams;
  563. oncirc->resolving_streams = exitconn;
  564. break;
  565. case -2:
  566. case -1:
  567. /* The request failed before it could start: cancel this connection,
  568. * and stop everybody waiting for the same connection. */
  569. if (is_resolve) {
  570. send_resolved_cell(exitconn,
  571. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  572. }
  573. exitconn->on_circuit = NULL;
  574. dns_cancel_pending_resolve(exitconn->_base.address);
  575. if (!exitconn->_base.marked_for_close) {
  576. connection_free(TO_CONN(exitconn));
  577. // XXX ... and we just leak exitconn otherwise? -RD
  578. // If it's marked for close, it's on closeable_connection_lst in
  579. // main.c. If it's on the closeable list, it will get freed from
  580. // main.c. -NM
  581. // "<armadev> If that's true, there are other bugs around, where we
  582. // don't check if it's marked, and will end up double-freeing."
  583. // On the other hand, I don't know of any actual bugs here, so this
  584. // shouldn't be holding up the rc. -RD
  585. }
  586. break;
  587. default:
  588. tor_assert(0);
  589. }
  590. tor_free(hostname);
  591. return r;
  592. }
  593. /** Helper function for dns_resolve: same functionality, but does not handle:
  594. * - marking connections on error and clearing their on_circuit
  595. * - linking connections to n_streams/resolving_streams,
  596. * - sending resolved cells if we have an answer/error right away,
  597. *
  598. * Return -2 on a transient error. If it's a reverse resolve and it's
  599. * successful, sets *<b>hostname_out</b> to a newly allocated string
  600. * holding the cached reverse DNS value.
  601. */
  602. static int
  603. dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  604. or_circuit_t *oncirc, char **hostname_out)
  605. {
  606. cached_resolve_t *resolve;
  607. cached_resolve_t search;
  608. pending_connection_t *pending_connection;
  609. routerinfo_t *me;
  610. tor_addr_t addr;
  611. time_t now = time(NULL);
  612. uint8_t is_reverse = 0;
  613. int r;
  614. assert_connection_ok(TO_CONN(exitconn), 0);
  615. tor_assert(exitconn->_base.s == -1);
  616. assert_cache_ok();
  617. tor_assert(oncirc);
  618. /* first check if exitconn->_base.address is an IP. If so, we already
  619. * know the answer. */
  620. if (tor_addr_from_str(&addr, exitconn->_base.address) >= 0) {
  621. if (tor_addr_family(&addr) == AF_INET) {
  622. tor_addr_copy(&exitconn->_base.addr, &addr);
  623. exitconn->address_ttl = DEFAULT_DNS_TTL;
  624. return 1;
  625. } else {
  626. /* XXXX IPv6 */
  627. return -1;
  628. }
  629. }
  630. /* If we're a non-exit, don't even do DNS lookups. */
  631. if (!(me = router_get_my_routerinfo()) ||
  632. policy_is_reject_star(me->exit_policy)) {
  633. return -1;
  634. }
  635. if (address_is_invalid_destination(exitconn->_base.address, 0)) {
  636. log(LOG_PROTOCOL_WARN, LD_EXIT,
  637. "Rejecting invalid destination address %s",
  638. escaped_safe_str(exitconn->_base.address));
  639. return -1;
  640. }
  641. /* then take this opportunity to see if there are any expired
  642. * resolves in the hash table. */
  643. purge_expired_resolves(now);
  644. /* lower-case exitconn->_base.address, so it's in canonical form */
  645. tor_strlower(exitconn->_base.address);
  646. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  647. * .in-addr.arpa address but this isn't a resolve request, kill the
  648. * connection.
  649. */
  650. if ((r = tor_addr_parse_reverse_lookup_name(&addr, exitconn->_base.address,
  651. AF_UNSPEC, 0)) != 0) {
  652. if (r == 1) {
  653. is_reverse = 1;
  654. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  655. return -1;
  656. }
  657. if (!is_reverse || !is_resolve) {
  658. if (!is_reverse)
  659. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  660. escaped_safe_str(exitconn->_base.address));
  661. else if (!is_resolve)
  662. log_info(LD_EXIT,
  663. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  664. "sending error.",
  665. escaped_safe_str(exitconn->_base.address));
  666. return -1;
  667. }
  668. //log_notice(LD_EXIT, "Looks like an address %s",
  669. //exitconn->_base.address);
  670. }
  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);
  697. }
  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();
  707. }
  708. tor_assert(0);
  709. }
  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->minheap_idx = -1;
  716. resolve->is_reverse = is_reverse;
  717. 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;
  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);
  725. log_debug(LD_EXIT,"Launching %s.",
  726. escaped_safe_str(exitconn->_base.address));
  727. assert_cache_ok();
  728. return launch_resolve(exitconn);
  729. }
  730. /** Log an error and abort if conn is waiting for a DNS resolve.
  731. */
  732. void
  733. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  734. {
  735. pending_connection_t *pend;
  736. cached_resolve_t search;
  737. #if 1
  738. cached_resolve_t *resolve;
  739. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  740. resolve = HT_FIND(cache_map, &cache_root, &search);
  741. if (!resolve)
  742. return;
  743. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  744. tor_assert(pend->conn != conn);
  745. }
  746. #else
  747. cached_resolve_t **resolve;
  748. HT_FOREACH(resolve, cache_map, &cache_root) {
  749. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  750. tor_assert(pend->conn != conn);
  751. }
  752. }
  753. #endif
  754. }
  755. /** Log an error and abort if any connection waiting for a DNS resolve is
  756. * corrupted. */
  757. void
  758. assert_all_pending_dns_resolves_ok(void)
  759. {
  760. pending_connection_t *pend;
  761. cached_resolve_t **resolve;
  762. HT_FOREACH(resolve, cache_map, &cache_root) {
  763. for (pend = (*resolve)->pending_connections;
  764. pend;
  765. pend = pend->next) {
  766. assert_connection_ok(TO_CONN(pend->conn), 0);
  767. tor_assert(pend->conn->_base.s == -1);
  768. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  769. }
  770. }
  771. }
  772. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  773. */
  774. void
  775. connection_dns_remove(edge_connection_t *conn)
  776. {
  777. pending_connection_t *pend, *victim;
  778. cached_resolve_t search;
  779. cached_resolve_t *resolve;
  780. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  781. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  782. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  783. resolve = HT_FIND(cache_map, &cache_root, &search);
  784. if (!resolve) {
  785. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  786. escaped_safe_str(conn->_base.address));
  787. return;
  788. }
  789. tor_assert(resolve->pending_connections);
  790. assert_connection_ok(TO_CONN(conn),0);
  791. pend = resolve->pending_connections;
  792. if (pend->conn == conn) {
  793. resolve->pending_connections = pend->next;
  794. tor_free(pend);
  795. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  796. "for resolve of %s",
  797. conn->_base.s,
  798. escaped_safe_str(conn->_base.address));
  799. return;
  800. } else {
  801. for ( ; pend->next; pend = pend->next) {
  802. if (pend->next->conn == conn) {
  803. victim = pend->next;
  804. pend->next = victim->next;
  805. tor_free(victim);
  806. log_debug(LD_EXIT,
  807. "Connection (fd %d) no longer waiting for resolve of %s",
  808. conn->_base.s, escaped_safe_str(conn->_base.address));
  809. return; /* more are pending */
  810. }
  811. }
  812. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  813. }
  814. }
  815. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  816. * the resolve for <b>address</b> itself, and remove any cached results for
  817. * <b>address</b> from the cache.
  818. */
  819. void
  820. dns_cancel_pending_resolve(const char *address)
  821. {
  822. pending_connection_t *pend;
  823. cached_resolve_t search;
  824. cached_resolve_t *resolve, *tmp;
  825. edge_connection_t *pendconn;
  826. circuit_t *circ;
  827. strlcpy(search.address, address, sizeof(search.address));
  828. resolve = HT_FIND(cache_map, &cache_root, &search);
  829. if (!resolve)
  830. return;
  831. if (resolve->state != CACHE_STATE_PENDING) {
  832. /* We can get into this state if we never actually created the pending
  833. * resolve, due to finding an earlier cached error or something. Just
  834. * ignore it. */
  835. if (resolve->pending_connections) {
  836. log_warn(LD_BUG,
  837. "Address %s is not pending but has pending connections!",
  838. escaped_safe_str(address));
  839. tor_fragile_assert();
  840. }
  841. return;
  842. }
  843. if (!resolve->pending_connections) {
  844. log_warn(LD_BUG,
  845. "Address %s is pending but has no pending connections!",
  846. escaped_safe_str(address));
  847. tor_fragile_assert();
  848. return;
  849. }
  850. tor_assert(resolve->pending_connections);
  851. /* mark all pending connections to fail */
  852. log_debug(LD_EXIT,
  853. "Failing all connections waiting on DNS resolve of %s",
  854. escaped_safe_str(address));
  855. while (resolve->pending_connections) {
  856. pend = resolve->pending_connections;
  857. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  858. pendconn = pend->conn;
  859. assert_connection_ok(TO_CONN(pendconn), 0);
  860. tor_assert(pendconn->_base.s == -1);
  861. if (!pendconn->_base.marked_for_close) {
  862. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  863. }
  864. circ = circuit_get_by_edge_conn(pendconn);
  865. if (circ)
  866. circuit_detach_stream(circ, pendconn);
  867. if (!pendconn->_base.marked_for_close)
  868. connection_free(TO_CONN(pendconn));
  869. resolve->pending_connections = pend->next;
  870. tor_free(pend);
  871. }
  872. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  873. if (tmp != resolve) {
  874. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  875. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  876. resolve->address, (void*)resolve,
  877. tmp ? tmp->address : "NULL", (void*)tmp);
  878. }
  879. tor_assert(tmp == resolve);
  880. resolve->state = CACHE_STATE_DONE;
  881. }
  882. /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
  883. * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
  884. * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
  885. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  886. **/
  887. static void
  888. add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
  889. const char *hostname, char outcome, uint32_t ttl)
  890. {
  891. cached_resolve_t *resolve;
  892. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  893. return;
  894. //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
  895. // address, is_reverse?"(reverse)":"", (unsigned long)addr,
  896. // hostname?hostname:"NULL",(int)outcome);
  897. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  898. resolve->magic = CACHED_RESOLVE_MAGIC;
  899. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  900. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  901. strlcpy(resolve->address, address, sizeof(resolve->address));
  902. resolve->is_reverse = is_reverse;
  903. if (is_reverse) {
  904. if (outcome == DNS_RESOLVE_SUCCEEDED) {
  905. tor_assert(hostname);
  906. resolve->result.hostname = tor_strdup(hostname);
  907. } else {
  908. tor_assert(! hostname);
  909. resolve->result.hostname = NULL;
  910. }
  911. } else {
  912. tor_assert(!hostname);
  913. resolve->result.a.addr = addr;
  914. }
  915. resolve->ttl = ttl;
  916. assert_resolve_ok(resolve);
  917. HT_INSERT(cache_map, &cache_root, resolve);
  918. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  919. }
  920. /** Return true iff <b>address</b> is one of the addresses we use to verify
  921. * that well-known sites aren't being hijacked by our DNS servers. */
  922. static INLINE int
  923. is_test_address(const char *address)
  924. {
  925. or_options_t *options = get_options();
  926. return options->ServerDNSTestAddresses &&
  927. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  928. }
  929. /** Called on the OR side when a DNS worker or the eventdns library tells us
  930. * the outcome of a DNS resolve: tell all pending connections about the result
  931. * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
  932. * string containing the address to look up; <b>addr</b> is an IPv4 address in
  933. * host order; <b>outcome</b> is one of
  934. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  935. */
  936. static void
  937. dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
  938. const char *hostname, char outcome, uint32_t ttl)
  939. {
  940. pending_connection_t *pend;
  941. cached_resolve_t search;
  942. cached_resolve_t *resolve, *removed;
  943. edge_connection_t *pendconn;
  944. circuit_t *circ;
  945. assert_cache_ok();
  946. strlcpy(search.address, address, sizeof(search.address));
  947. resolve = HT_FIND(cache_map, &cache_root, &search);
  948. if (!resolve) {
  949. int is_test_addr = is_test_address(address);
  950. if (!is_test_addr)
  951. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  952. escaped_safe_str(address));
  953. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  954. return;
  955. }
  956. assert_resolve_ok(resolve);
  957. if (resolve->state != CACHE_STATE_PENDING) {
  958. /* XXXX Maybe update addr? or check addr for consistency? Or let
  959. * VALID replace FAILED? */
  960. int is_test_addr = is_test_address(address);
  961. if (!is_test_addr)
  962. log_notice(LD_EXIT,
  963. "Resolved %s which was already resolved; ignoring",
  964. escaped_safe_str(address));
  965. tor_assert(resolve->pending_connections == NULL);
  966. return;
  967. }
  968. /* Removed this assertion: in fact, we'll sometimes get a double answer
  969. * to the same question. This can happen when we ask one worker to resolve
  970. * X.Y.Z., then we cancel the request, and then we ask another worker to
  971. * resolve X.Y.Z. */
  972. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  973. while (resolve->pending_connections) {
  974. pend = resolve->pending_connections;
  975. pendconn = pend->conn; /* don't pass complex things to the
  976. connection_mark_for_close macro */
  977. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  978. tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
  979. pendconn->address_ttl = ttl;
  980. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  981. /* prevent double-remove. */
  982. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  983. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  984. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  985. /* This detach must happen after we send the end cell. */
  986. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  987. } else {
  988. send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
  989. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  990. /* This detach must happen after we send the resolved cell. */
  991. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  992. }
  993. connection_free(TO_CONN(pendconn));
  994. } else {
  995. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  996. tor_assert(!is_reverse);
  997. /* prevent double-remove. */
  998. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  999. circ = circuit_get_by_edge_conn(pend->conn);
  1000. tor_assert(circ);
  1001. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1002. /* unlink pend->conn from resolving_streams, */
  1003. circuit_detach_stream(circ, pend->conn);
  1004. /* and link it to n_streams */
  1005. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1006. pend->conn->on_circuit = circ;
  1007. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1008. connection_exit_connect(pend->conn);
  1009. } else {
  1010. /* prevent double-remove. This isn't really an accurate state,
  1011. * but it does the right thing. */
  1012. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1013. if (is_reverse)
  1014. send_resolved_hostname_cell(pendconn, hostname);
  1015. else
  1016. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  1017. circ = circuit_get_by_edge_conn(pendconn);
  1018. tor_assert(circ);
  1019. circuit_detach_stream(circ, pendconn);
  1020. connection_free(TO_CONN(pendconn));
  1021. }
  1022. }
  1023. resolve->pending_connections = pend->next;
  1024. tor_free(pend);
  1025. }
  1026. resolve->state = CACHE_STATE_DONE;
  1027. removed = HT_REMOVE(cache_map, &cache_root, &search);
  1028. if (removed != resolve) {
  1029. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1030. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1031. resolve->address, (void*)resolve,
  1032. removed ? removed->address : "NULL", (void*)removed);
  1033. }
  1034. assert_resolve_ok(resolve);
  1035. assert_cache_ok();
  1036. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  1037. assert_cache_ok();
  1038. }
  1039. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1040. * a transient failure. */
  1041. static int
  1042. evdns_err_is_transient(int err)
  1043. {
  1044. switch (err)
  1045. {
  1046. case DNS_ERR_SERVERFAILED:
  1047. case DNS_ERR_TRUNCATED:
  1048. case DNS_ERR_TIMEOUT:
  1049. return 1;
  1050. default:
  1051. return 0;
  1052. }
  1053. }
  1054. /** Configure eventdns nameservers if force is true, or if the configuration
  1055. * has changed since the last time we called this function, or if we failed on
  1056. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1057. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1058. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1059. * -1 on failure. */
  1060. static int
  1061. configure_nameservers(int force)
  1062. {
  1063. or_options_t *options;
  1064. const char *conf_fname;
  1065. struct stat st;
  1066. int r;
  1067. options = get_options();
  1068. conf_fname = options->ServerDNSResolvConfFile;
  1069. #ifndef MS_WINDOWS
  1070. if (!conf_fname)
  1071. conf_fname = "/etc/resolv.conf";
  1072. #endif
  1073. if (!the_evdns_base) {
  1074. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1075. log_err(LD_BUG, "Couldn't create an evdns_base");
  1076. return -1;
  1077. }
  1078. }
  1079. #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  1080. if (options->OutboundBindAddress) {
  1081. tor_addr_t addr;
  1082. if (tor_addr_from_str(&addr, options->OutboundBindAddress) < 0) {
  1083. log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  1084. options->OutboundBindAddress);
  1085. } else {
  1086. int socklen;
  1087. struct sockaddr_storage ss;
  1088. socklen = tor_addr_to_sockaddr(&addr, 0,
  1089. (struct sockaddr *)&ss, sizeof(ss));
  1090. if (socklen < 0) {
  1091. log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
  1092. " Ignoring.");
  1093. } else {
  1094. evdns_base_set_default_outgoing_bind_address(the_evdns_base,
  1095. (struct sockaddr *)&ss,
  1096. socklen);
  1097. }
  1098. }
  1099. }
  1100. #endif
  1101. evdns_set_log_fn(evdns_log_cb);
  1102. if (conf_fname) {
  1103. if (stat(conf_fname, &st)) {
  1104. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1105. conf_fname, strerror(errno));
  1106. goto err;
  1107. }
  1108. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1109. && st.st_mtime == resolv_conf_mtime) {
  1110. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1111. return 0;
  1112. }
  1113. if (nameservers_configured) {
  1114. evdns_base_search_clear(the_evdns_base);
  1115. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1116. }
  1117. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1118. if ((r = evdns_base_resolv_conf_parse(the_evdns_base,
  1119. 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;
  1123. }
  1124. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1125. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1126. goto err;
  1127. }
  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_base_resume(the_evdns_base);
  1133. }
  1134. #ifdef MS_WINDOWS
  1135. else {
  1136. if (nameservers_configured) {
  1137. evdns_base_search_clear(the_evdns_base);
  1138. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1139. }
  1140. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1141. log_warn(LD_EXIT,"Could not config nameservers.");
  1142. goto err;
  1143. }
  1144. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1145. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1146. "your Windows configuration.");
  1147. goto err;
  1148. }
  1149. if (nameservers_configured)
  1150. evdns_base_resume(the_evdns_base);
  1151. tor_free(resolv_conf_fname);
  1152. resolv_conf_mtime = 0;
  1153. }
  1154. #endif
  1155. #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
  1156. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1157. SET("max-timeouts:", "16");
  1158. SET("timeout:", "10");
  1159. } else {
  1160. SET("max-timeouts:", "3");
  1161. SET("timeout:", "5");
  1162. }
  1163. if (options->ServerDNSRandomizeCase)
  1164. SET("randomize-case:", "1");
  1165. else
  1166. SET("randomize-case:", "0");
  1167. #undef SET
  1168. dns_servers_relaunch_checks();
  1169. nameservers_configured = 1;
  1170. if (nameserver_config_failed) {
  1171. nameserver_config_failed = 0;
  1172. mark_my_descriptor_dirty();
  1173. }
  1174. return 0;
  1175. err:
  1176. nameservers_configured = 0;
  1177. if (! nameserver_config_failed) {
  1178. nameserver_config_failed = 1;
  1179. mark_my_descriptor_dirty();
  1180. }
  1181. return -1;
  1182. }
  1183. /** For eventdns: Called when we get an answer for a request we launched.
  1184. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1185. */
  1186. static void
  1187. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1188. void *arg)
  1189. {
  1190. char *string_address = arg;
  1191. uint8_t is_reverse = 0;
  1192. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1193. uint32_t addr = 0;
  1194. const char *hostname = NULL;
  1195. int was_wildcarded = 0;
  1196. if (result == DNS_ERR_NONE) {
  1197. if (type == DNS_IPv4_A && count) {
  1198. char answer_buf[INET_NTOA_BUF_LEN+1];
  1199. struct in_addr in;
  1200. char *escaped_address;
  1201. uint32_t *addrs = addresses;
  1202. in.s_addr = addrs[0];
  1203. addr = ntohl(addrs[0]);
  1204. status = DNS_RESOLVE_SUCCEEDED;
  1205. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1206. 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));
  1219. }
  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));
  1237. }
  1238. } else {
  1239. if (evdns_err_is_transient(result))
  1240. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1241. }
  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);
  1247. }
  1248. }
  1249. if (result != DNS_ERR_SHUTDOWN)
  1250. dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
  1251. tor_free(string_address);
  1252. }
  1253. /** For eventdns: start resolving as necessary to find the target for
  1254. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1255. * 0 on "resolve launched." */
  1256. static int
  1257. launch_resolve(edge_connection_t *exitconn)
  1258. {
  1259. char *addr = tor_strdup(exitconn->_base.address);
  1260. struct evdns_request *req = NULL;
  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;
  1271. }
  1272. }
  1273. r = tor_addr_parse_reverse_lookup_name(
  1274. &a, exitconn->_base.address, AF_UNSPEC, 0);
  1275. tor_assert(the_evdns_base);
  1276. if (r == 0) {
  1277. log_info(LD_EXIT, "Launching eventdns request for %s",
  1278. escaped_safe_str(exitconn->_base.address));
  1279. req = evdns_base_resolve_ipv4(the_evdns_base,
  1280. exitconn->_base.address, options,
  1281. evdns_callback, addr);
  1282. } else if (r == 1) {
  1283. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1284. escaped_safe_str(exitconn->_base.address));
  1285. if (tor_addr_family(&a) == AF_INET)
  1286. req = evdns_base_resolve_reverse(the_evdns_base,
  1287. tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
  1288. evdns_callback, addr);
  1289. else
  1290. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1291. tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
  1292. evdns_callback, addr);
  1293. } else if (r == -1) {
  1294. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1295. }
  1296. r = 0;
  1297. if (!req) {
  1298. log_warn(LD_EXIT, "eventdns rejected address %s.",
  1299. escaped_safe_str(addr));
  1300. r = -1;
  1301. tor_free(addr); /* There is no evdns request in progress; stop
  1302. * addr from getting leaked. */
  1303. }
  1304. return r;
  1305. }
  1306. /** How many requests for bogus addresses have we launched so far? */
  1307. static int n_wildcard_requests = 0;
  1308. /** Map from dotted-quad IP address in response to an int holding how many
  1309. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1310. * would be easier to use definitely-invalid addresses (as specified by
  1311. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1312. 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.
  1315. */
  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.
  1321. */
  1322. static int dns_wildcard_notice_given = 0;
  1323. /** List of supposedly good addresses that are getting wildcarded to the
  1324. * same addresses as nonexistent addresses. */
  1325. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1326. /** True iff we've warned about a test address getting wildcarded */
  1327. static int dns_wildcarded_test_address_notice_given = 0;
  1328. /** True iff all addresses seem to be getting wildcarded. */
  1329. static int dns_is_completely_invalid = 0;
  1330. /** Called when we see <b>id</b> (a dotted quad) in response to a request for
  1331. * a hopefully bogus address. */
  1332. static void
  1333. wildcard_increment_answer(const char *id)
  1334. {
  1335. int *ip;
  1336. if (!dns_wildcard_response_count)
  1337. dns_wildcard_response_count = strmap_new();
  1338. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1339. if (!ip) {
  1340. ip = tor_malloc_zero(sizeof(int));
  1341. strmap_set(dns_wildcard_response_count, id, ip);
  1342. }
  1343. ++*ip;
  1344. if (*ip > 5 && n_wildcard_requests > 10) {
  1345. if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
  1346. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1347. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1348. "Your DNS provider has given \"%s\" as an answer for %d different "
  1349. "invalid addresses. Apparently they are hijacking DNS failures. "
  1350. "I'll try to correct for this by treating future occurrences of "
  1351. "\"%s\" as 'not found'.", id, *ip, id);
  1352. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1353. }
  1354. if (!dns_wildcard_notice_given)
  1355. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1356. dns_wildcard_notice_given = 1;
  1357. }
  1358. }
  1359. /** Note that a single test address (one believed to be good) seems to be
  1360. * getting redirected to the same IP as failures are. */
  1361. static void
  1362. add_wildcarded_test_address(const char *address)
  1363. {
  1364. int n, n_test_addrs;
  1365. if (!dns_wildcarded_test_address_list)
  1366. dns_wildcarded_test_address_list = smartlist_create();
  1367. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1368. return;
  1369. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1370. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1371. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1372. n = smartlist_len(dns_wildcarded_test_address_list);
  1373. if (n > n_test_addrs/2) {
  1374. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1375. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1376. "address. It has done this with %d test addresses so far. I'm "
  1377. "going to stop being an exit node for now, since our DNS seems so "
  1378. "broken.", address, n);
  1379. if (!dns_is_completely_invalid) {
  1380. dns_is_completely_invalid = 1;
  1381. mark_my_descriptor_dirty();
  1382. }
  1383. if (!dns_wildcarded_test_address_notice_given)
  1384. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1385. dns_wildcarded_test_address_notice_given = 1;
  1386. }
  1387. }
  1388. /** Callback function when we get an answer (possibly failing) for a request
  1389. * for a (hopefully) nonexistent domain. */
  1390. static void
  1391. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1392. void *addresses, void *arg)
  1393. {
  1394. (void)ttl;
  1395. ++n_wildcard_requests;
  1396. if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
  1397. uint32_t *addrs = addresses;
  1398. int i;
  1399. char *string_address = arg;
  1400. for (i = 0; i < count; ++i) {
  1401. char answer_buf[INET_NTOA_BUF_LEN+1];
  1402. struct in_addr in;
  1403. in.s_addr = addrs[i];
  1404. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1405. wildcard_increment_answer(answer_buf);
  1406. }
  1407. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1408. "Your DNS provider gave an answer for \"%s\", which "
  1409. "is not supposed to exist. Apparently they are hijacking "
  1410. "DNS failures. Trying to correct for this. We've noticed %d "
  1411. "possibly bad address%s so far.",
  1412. string_address, strmap_size(dns_wildcard_response_count),
  1413. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1414. dns_wildcard_one_notice_given = 1;
  1415. }
  1416. tor_free(arg);
  1417. }
  1418. /** Launch a single request for a nonexistent hostname consisting of between
  1419. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1420. * <b>suffix</b> */
  1421. static void
  1422. launch_wildcard_check(int min_len, int max_len, const char *suffix)
  1423. {
  1424. char *addr;
  1425. struct evdns_request *req;
  1426. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1427. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1428. "domains with request for bogus hostname \"%s\"", addr);
  1429. tor_assert(the_evdns_base);
  1430. req = evdns_base_resolve_ipv4(
  1431. the_evdns_base,
  1432. /* This "addr" tells us which address to resolve */
  1433. addr,
  1434. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1435. /* This "addr" is an argument to the callback*/ addr);
  1436. if (!req) {
  1437. /* There is no evdns request in progress; stop addr from getting leaked */
  1438. tor_free(addr);
  1439. }
  1440. }
  1441. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1442. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1443. static void
  1444. launch_test_addresses(int fd, short event, void *args)
  1445. {
  1446. or_options_t *options = get_options();
  1447. struct evdns_request *req;
  1448. (void)fd;
  1449. (void)event;
  1450. (void)args;
  1451. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1452. "hijack *everything*.");
  1453. /* This situation is worse than the failure-hijacking situation. When this
  1454. * happens, we're no good for DNS requests at all, and we shouldn't really
  1455. * be an exit server.*/
  1456. if (!options->ServerDNSTestAddresses)
  1457. return;
  1458. tor_assert(the_evdns_base);
  1459. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1460. const char *, address) {
  1461. char *a = tor_strdup(address);
  1462. req = evdns_base_resolve_ipv4(the_evdns_base,
  1463. address, DNS_QUERY_NO_SEARCH, evdns_callback, a);
  1464. if (!req) {
  1465. log_info(LD_EXIT, "eventdns rejected test address %s",
  1466. escaped_safe_str(address));
  1467. tor_free(a);
  1468. }
  1469. } SMARTLIST_FOREACH_END(address);
  1470. }
  1471. #define N_WILDCARD_CHECKS 2
  1472. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1473. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1474. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1475. * buy these lovely encyclopedias" page. */
  1476. static void
  1477. dns_launch_wildcard_checks(void)
  1478. {
  1479. int i;
  1480. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1481. "to hijack DNS failures.");
  1482. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1483. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
  1484. * to 'comply' with rfc2606, refrain from giving A records for these.
  1485. * This is the standards-compliance equivalent of making sure that your
  1486. * crackhouse's elevator inspection certificate is up to date.
  1487. */
  1488. launch_wildcard_check(2, 16, ".invalid");
  1489. launch_wildcard_check(2, 16, ".test");
  1490. /* These will break specs if there are ever any number of
  1491. * 8+-character top-level domains. */
  1492. launch_wildcard_check(8, 16, "");
  1493. /* Try some random .com/org/net domains. This will work fine so long as
  1494. * not too many resolve to the same place. */
  1495. launch_wildcard_check(8, 16, ".com");
  1496. launch_wildcard_check(8, 16, ".org");
  1497. launch_wildcard_check(8, 16, ".net");
  1498. }
  1499. }
  1500. /** If appropriate, start testing whether our DNS servers tend to lie to
  1501. * us. */
  1502. void
  1503. dns_launch_correctness_checks(void)
  1504. {
  1505. static struct event *launch_event = NULL;
  1506. struct timeval timeout;
  1507. if (!get_options()->ServerDNSDetectHijacking)
  1508. return;
  1509. dns_launch_wildcard_checks();
  1510. /* Wait a while before launching requests for test addresses, so we can
  1511. * get the results from checking for wildcarding. */
  1512. if (! launch_event)
  1513. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1514. launch_test_addresses, NULL);
  1515. timeout.tv_sec = 30;
  1516. timeout.tv_usec = 0;
  1517. if (evtimer_add(launch_event, &timeout)<0) {
  1518. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1519. }
  1520. }
  1521. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1522. int
  1523. dns_seems_to_be_broken(void)
  1524. {
  1525. return dns_is_completely_invalid;
  1526. }
  1527. /** Forget what we've previously learned about our DNS servers' correctness. */
  1528. void
  1529. dns_reset_correctness_checks(void)
  1530. {
  1531. strmap_free(dns_wildcard_response_count, _tor_free);
  1532. dns_wildcard_response_count = NULL;
  1533. n_wildcard_requests = 0;
  1534. if (dns_wildcard_list) {
  1535. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1536. smartlist_clear(dns_wildcard_list);
  1537. }
  1538. if (dns_wildcarded_test_address_list) {
  1539. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1540. tor_free(cp));
  1541. smartlist_clear(dns_wildcarded_test_address_list);
  1542. }
  1543. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1544. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
  1545. }
  1546. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1547. * returned in response to requests for nonexistent hostnames. */
  1548. static int
  1549. answer_is_wildcarded(const char *ip)
  1550. {
  1551. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1552. }
  1553. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1554. static void
  1555. assert_resolve_ok(cached_resolve_t *resolve)
  1556. {
  1557. tor_assert(resolve);
  1558. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1559. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1560. tor_assert(tor_strisnonupper(resolve->address));
  1561. if (resolve->state != CACHE_STATE_PENDING) {
  1562. tor_assert(!resolve->pending_connections);
  1563. }
  1564. if (resolve->state == CACHE_STATE_PENDING ||
  1565. resolve->state == CACHE_STATE_DONE) {
  1566. tor_assert(!resolve->ttl);
  1567. if (resolve->is_reverse)
  1568. tor_assert(!resolve->result.hostname);
  1569. else
  1570. tor_assert(!resolve->result.a.addr);
  1571. }
  1572. }
  1573. /** Return the number of DNS cache entries as an int */
  1574. static int
  1575. dns_cache_entry_count(void)
  1576. {
  1577. return HT_SIZE(&cache_root);
  1578. }
  1579. /** Log memory information about our internal DNS cache at level 'severity'. */
  1580. void
  1581. dump_dns_mem_usage(int severity)
  1582. {
  1583. /* This should never be larger than INT_MAX. */
  1584. int hash_count = dns_cache_entry_count();
  1585. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1586. hash_mem += HT_MEM_USAGE(&cache_root);
  1587. /* Print out the count and estimated size of our &cache_root. It undercounts
  1588. hostnames in cached reverse resolves.
  1589. */
  1590. log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1591. log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1592. (unsigned)hash_mem);
  1593. }
  1594. #ifdef DEBUG_DNS_CACHE
  1595. /** Exit with an assertion if the DNS cache is corrupt. */
  1596. static void
  1597. _assert_cache_ok(void)
  1598. {
  1599. cached_resolve_t **resolve;
  1600. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1601. if (bad_rep) {
  1602. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1603. tor_assert(!bad_rep);
  1604. }
  1605. HT_FOREACH(resolve, cache_map, &cache_root) {
  1606. assert_resolve_ok(*resolve);
  1607. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1608. }
  1609. if (!cached_resolve_pqueue)
  1610. return;
  1611. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1612. _compare_cached_resolves_by_expiry,
  1613. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  1614. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1615. {
  1616. if (res->state == CACHE_STATE_DONE) {
  1617. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1618. tor_assert(!found || found != res);
  1619. } else {
  1620. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1621. tor_assert(found);
  1622. }
  1623. });
  1624. }
  1625. #endif