dns.c 63 KB

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