dns.c 62 KB

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