dns.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, 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. * There are three main cases when a Tor relay uses dns.c to launch a DNS
  13. * request:
  14. * <ol>
  15. * <li>To check whether the DNS server is working more or less correctly.
  16. * This happens via dns_launch_correctness_checks(). The answer is
  17. * reported in the return value from later calls to
  18. * dns_seems_to_be_broken().
  19. * <li>When a client has asked the relay, in a RELAY_BEGIN cell, to connect
  20. * to a given server by hostname. This happens via dns_resolve().
  21. * <li>When a client has asked the relay, in a RELAY_RESOLVE cell, to look
  22. * up a given server's IP address(es) by hostname. This also happens via
  23. * dns_resolve().
  24. * </ol>
  25. *
  26. * Each of these gets handled a little differently.
  27. *
  28. * To check for correctness, we look up some hostname we expect to exist and
  29. * have real entries, some hostnames which we expect to definitely not exist,
  30. * and some hostnames that we expect to probably not exist. If too many of
  31. * the hostnames that shouldn't exist do exist, that's a DNS hijacking
  32. * attempt. If too many of the hostnames that should exist have the same
  33. * addresses as the ones that shouldn't exist, that's a very bad DNS hijacking
  34. * attempt, or a very naughty captive portal. And if the hostnames that
  35. * should exist simply don't exist, we probably have a broken nameserver.
  36. *
  37. * To handle client requests, we first check our cache for answers. If there
  38. * isn't something up-to-date, we've got to launch A or AAAA requests as
  39. * appropriate. How we handle responses to those in particular is a bit
  40. * complex; see dns_lookup() and set_exitconn_info_from_resolve().
  41. *
  42. * When a lookup is finally complete, the inform_pending_connections()
  43. * function will tell all of the streams that have been waiting for the
  44. * resolve, by calling connection_exit_connect() if the client sent a
  45. * RELAY_BEGIN cell, and by calling send_resolved_cell() or
  46. * send_hostname_cell() if the client sent a RELAY_RESOLVE cell.
  47. **/
  48. #define DNS_PRIVATE
  49. #include "core/or/or.h"
  50. #include "core/or/circuitlist.h"
  51. #include "core/or/circuituse.h"
  52. #include "app/config/config.h"
  53. #include "core/mainloop/connection.h"
  54. #include "core/or/connection_edge.h"
  55. #include "feature/control/control.h"
  56. #include "lib/crypt_ops/crypto_rand.h"
  57. #include "feature/relay/dns.h"
  58. #include "core/mainloop/main.h"
  59. #include "core/or/policies.h"
  60. #include "core/or/relay.h"
  61. #include "feature/relay/router.h"
  62. #include "ht.h"
  63. #include "lib/sandbox/sandbox.h"
  64. #include "lib/evloop/compat_libevent.h"
  65. #include "core/or/edge_connection_st.h"
  66. #include "core/or/or_circuit_st.h"
  67. #ifdef HAVE_SYS_STAT_H
  68. #include <sys/stat.h>
  69. #endif
  70. #include <event2/event.h>
  71. #include <event2/dns.h>
  72. /** How long will we wait for an answer from the resolver before we decide
  73. * that the resolver is wedged? */
  74. #define RESOLVE_MAX_TIMEOUT 300
  75. /** Our evdns_base; this structure handles all our name lookups. */
  76. static struct evdns_base *the_evdns_base = NULL;
  77. /** Have we currently configured nameservers with eventdns? */
  78. static int nameservers_configured = 0;
  79. /** Did our most recent attempt to configure nameservers with eventdns fail? */
  80. static int nameserver_config_failed = 0;
  81. /** What was the resolv_conf fname we last used when configuring the
  82. * nameservers? Used to check whether we need to reconfigure. */
  83. static char *resolv_conf_fname = NULL;
  84. /** What was the mtime on the resolv.conf file we last used when configuring
  85. * the nameservers? Used to check whether we need to reconfigure. */
  86. static time_t resolv_conf_mtime = 0;
  87. static void purge_expired_resolves(time_t now);
  88. static void dns_found_answer(const char *address, uint8_t query_type,
  89. int dns_answer,
  90. const tor_addr_t *addr,
  91. const char *hostname,
  92. uint32_t ttl);
  93. static void add_wildcarded_test_address(const char *address);
  94. static int configure_nameservers(int force);
  95. static int answer_is_wildcarded(const char *ip);
  96. static int evdns_err_is_transient(int err);
  97. static void inform_pending_connections(cached_resolve_t *resolve);
  98. static void make_pending_resolve_cached(cached_resolve_t *cached);
  99. #ifdef DEBUG_DNS_CACHE
  100. static void assert_cache_ok_(void);
  101. #define assert_cache_ok() assert_cache_ok_()
  102. #else
  103. #define assert_cache_ok() STMT_NIL
  104. #endif /* defined(DEBUG_DNS_CACHE) */
  105. static void assert_resolve_ok(cached_resolve_t *resolve);
  106. /** Hash table of cached_resolve objects. */
  107. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  108. /** Global: how many IPv6 requests have we made in all? */
  109. static uint64_t n_ipv6_requests_made = 0;
  110. /** Global: how many IPv6 requests have timed out? */
  111. static uint64_t n_ipv6_timeouts = 0;
  112. /** Global: Do we think that IPv6 DNS is broken? */
  113. static int dns_is_broken_for_ipv6 = 0;
  114. /** Function to compare hashed resolves on their addresses; used to
  115. * implement hash tables. */
  116. static inline int
  117. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  118. {
  119. /* make this smarter one day? */
  120. assert_resolve_ok(a); // Not b; b may be just a search.
  121. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  122. }
  123. /** Hash function for cached_resolve objects */
  124. static inline unsigned int
  125. cached_resolve_hash(cached_resolve_t *a)
  126. {
  127. return (unsigned) siphash24g((const uint8_t*)a->address, strlen(a->address));
  128. }
  129. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  130. cached_resolves_eq)
  131. HT_GENERATE2(cache_map, cached_resolve_t, node, cached_resolve_hash,
  132. cached_resolves_eq, 0.6, tor_reallocarray_, tor_free_)
  133. /** Initialize the DNS cache. */
  134. static void
  135. init_cache_map(void)
  136. {
  137. HT_INIT(cache_map, &cache_root);
  138. }
  139. /** Helper: called by eventdns when eventdns wants to log something. */
  140. static void
  141. evdns_log_cb(int warn, const char *msg)
  142. {
  143. const char *cp;
  144. static int all_down = 0;
  145. int severity = warn ? LOG_WARN : LOG_INFO;
  146. if (!strcmpstart(msg, "Resolve requested for") &&
  147. get_options()->SafeLogging) {
  148. log_info(LD_EXIT, "eventdns: Resolve requested.");
  149. return;
  150. } else if (!strcmpstart(msg, "Search: ")) {
  151. return;
  152. }
  153. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  154. char *ns = tor_strndup(msg+11, cp-(msg+11));
  155. const char *colon = strchr(cp, ':');
  156. tor_assert(colon);
  157. const char *err = colon+2;
  158. /* Don't warn about a single failed nameserver; we'll warn with 'all
  159. * nameservers have failed' if we're completely out of nameservers;
  160. * otherwise, the situation is tolerable. */
  161. severity = LOG_INFO;
  162. control_event_server_status(LOG_NOTICE,
  163. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  164. ns, escaped(err));
  165. tor_free(ns);
  166. } else if (!strcmpstart(msg, "Nameserver ") &&
  167. (cp=strstr(msg, " is back up"))) {
  168. char *ns = tor_strndup(msg+11, cp-(msg+11));
  169. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  170. all_down = 0;
  171. control_event_server_status(LOG_NOTICE,
  172. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  173. tor_free(ns);
  174. } else if (!strcmp(msg, "All nameservers have failed")) {
  175. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  176. all_down = 1;
  177. } else if (!strcmpstart(msg, "Address mismatch on received DNS")) {
  178. static ratelim_t mismatch_limit = RATELIM_INIT(3600);
  179. const char *src = strstr(msg, " Apparent source");
  180. if (!src || get_options()->SafeLogging) {
  181. src = "";
  182. }
  183. log_fn_ratelim(&mismatch_limit, severity, LD_EXIT,
  184. "eventdns: Received a DNS packet from "
  185. "an IP address to which we did not send a request. This "
  186. "could be a DNS spoofing attempt, or some kind of "
  187. "misconfiguration.%s", src);
  188. return;
  189. }
  190. tor_log(severity, LD_EXIT, "eventdns: %s", msg);
  191. }
  192. /** Helper: passed to eventdns.c as a callback so it can generate random
  193. * numbers for transaction IDs and 0x20-hack coding. */
  194. static void
  195. dns_randfn_(char *b, size_t n)
  196. {
  197. crypto_rand(b,n);
  198. }
  199. /** Initialize the DNS subsystem; called by the OR process. */
  200. int
  201. dns_init(void)
  202. {
  203. init_cache_map();
  204. evdns_set_random_bytes_fn(dns_randfn_);
  205. if (server_mode(get_options())) {
  206. int r = configure_nameservers(1);
  207. return r;
  208. }
  209. return 0;
  210. }
  211. /** Called when DNS-related options change (or may have changed). Returns -1
  212. * on failure, 0 on success. */
  213. int
  214. dns_reset(void)
  215. {
  216. const or_options_t *options = get_options();
  217. if (! server_mode(options)) {
  218. if (!the_evdns_base) {
  219. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  220. log_err(LD_BUG, "Couldn't create an evdns_base");
  221. return -1;
  222. }
  223. }
  224. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  225. evdns_base_search_clear(the_evdns_base);
  226. nameservers_configured = 0;
  227. tor_free(resolv_conf_fname);
  228. resolv_conf_mtime = 0;
  229. } else {
  230. if (configure_nameservers(0) < 0) {
  231. return -1;
  232. }
  233. }
  234. return 0;
  235. }
  236. /** Return true iff the most recent attempt to initialize the DNS subsystem
  237. * failed. */
  238. int
  239. has_dns_init_failed(void)
  240. {
  241. return nameserver_config_failed;
  242. }
  243. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  244. * OP that asked us to resolve it, and how long to cache that record
  245. * ourselves. */
  246. uint32_t
  247. dns_clip_ttl(uint32_t ttl)
  248. {
  249. /* This logic is a defense against "DefectTor" DNS-based traffic
  250. * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
  251. * We only give two values: a "low" value and a "high" value.
  252. */
  253. if (ttl < MIN_DNS_TTL_AT_EXIT)
  254. return MIN_DNS_TTL_AT_EXIT;
  255. else
  256. return MAX_DNS_TTL_AT_EXIT;
  257. }
  258. /** Helper: free storage held by an entry in the DNS cache. */
  259. static void
  260. free_cached_resolve_(cached_resolve_t *r)
  261. {
  262. if (!r)
  263. return;
  264. while (r->pending_connections) {
  265. pending_connection_t *victim = r->pending_connections;
  266. r->pending_connections = victim->next;
  267. tor_free(victim);
  268. }
  269. if (r->res_status_hostname == RES_STATUS_DONE_OK)
  270. tor_free(r->result_ptr.hostname);
  271. r->magic = 0xFF00FF00;
  272. tor_free(r);
  273. }
  274. /** Compare two cached_resolve_t pointers by expiry time, and return
  275. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  276. * the priority queue implementation. */
  277. static int
  278. compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
  279. {
  280. const cached_resolve_t *a = _a, *b = _b;
  281. if (a->expire < b->expire)
  282. return -1;
  283. else if (a->expire == b->expire)
  284. return 0;
  285. else
  286. return 1;
  287. }
  288. /** Priority queue of cached_resolve_t objects to let us know when they
  289. * will expire. */
  290. static smartlist_t *cached_resolve_pqueue = NULL;
  291. static void
  292. cached_resolve_add_answer(cached_resolve_t *resolve,
  293. int query_type,
  294. int dns_result,
  295. const tor_addr_t *answer_addr,
  296. const char *answer_hostname,
  297. uint32_t ttl)
  298. {
  299. if (query_type == DNS_PTR) {
  300. if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
  301. return;
  302. if (dns_result == DNS_ERR_NONE && answer_hostname) {
  303. resolve->result_ptr.hostname = tor_strdup(answer_hostname);
  304. resolve->res_status_hostname = RES_STATUS_DONE_OK;
  305. } else {
  306. resolve->result_ptr.err_hostname = dns_result;
  307. resolve->res_status_hostname = RES_STATUS_DONE_ERR;
  308. }
  309. resolve->ttl_hostname = ttl;
  310. } else if (query_type == DNS_IPv4_A) {
  311. if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
  312. return;
  313. if (dns_result == DNS_ERR_NONE && answer_addr &&
  314. tor_addr_family(answer_addr) == AF_INET) {
  315. resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
  316. resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
  317. } else {
  318. resolve->result_ipv4.err_ipv4 = dns_result;
  319. resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
  320. }
  321. resolve->ttl_ipv4 = ttl;
  322. } else if (query_type == DNS_IPv6_AAAA) {
  323. if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
  324. return;
  325. if (dns_result == DNS_ERR_NONE && answer_addr &&
  326. tor_addr_family(answer_addr) == AF_INET6) {
  327. memcpy(&resolve->result_ipv6.addr_ipv6,
  328. tor_addr_to_in6(answer_addr),
  329. sizeof(struct in6_addr));
  330. resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
  331. } else {
  332. resolve->result_ipv6.err_ipv6 = dns_result;
  333. resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
  334. }
  335. resolve->ttl_ipv6 = ttl;
  336. }
  337. }
  338. /** Return true iff there are no in-flight requests for <b>resolve</b>. */
  339. static int
  340. cached_resolve_have_all_answers(const cached_resolve_t *resolve)
  341. {
  342. return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
  343. resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
  344. resolve->res_status_hostname != RES_STATUS_INFLIGHT);
  345. }
  346. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  347. * priority queue */
  348. static void
  349. set_expiry(cached_resolve_t *resolve, time_t expires)
  350. {
  351. tor_assert(resolve && resolve->expire == 0);
  352. if (!cached_resolve_pqueue)
  353. cached_resolve_pqueue = smartlist_new();
  354. resolve->expire = expires;
  355. smartlist_pqueue_add(cached_resolve_pqueue,
  356. compare_cached_resolves_by_expiry_,
  357. offsetof(cached_resolve_t, minheap_idx),
  358. resolve);
  359. }
  360. /** Free all storage held in the DNS cache and related structures. */
  361. void
  362. dns_free_all(void)
  363. {
  364. cached_resolve_t **ptr, **next, *item;
  365. assert_cache_ok();
  366. if (cached_resolve_pqueue) {
  367. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  368. {
  369. if (res->state == CACHE_STATE_DONE)
  370. free_cached_resolve_(res);
  371. });
  372. }
  373. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  374. item = *ptr;
  375. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  376. free_cached_resolve_(item);
  377. }
  378. HT_CLEAR(cache_map, &cache_root);
  379. smartlist_free(cached_resolve_pqueue);
  380. cached_resolve_pqueue = NULL;
  381. tor_free(resolv_conf_fname);
  382. }
  383. /** Remove every cached_resolve whose <b>expire</b> time is before or
  384. * equal to <b>now</b> from the cache. */
  385. static void
  386. purge_expired_resolves(time_t now)
  387. {
  388. cached_resolve_t *resolve, *removed;
  389. pending_connection_t *pend;
  390. edge_connection_t *pendconn;
  391. assert_cache_ok();
  392. if (!cached_resolve_pqueue)
  393. return;
  394. while (smartlist_len(cached_resolve_pqueue)) {
  395. resolve = smartlist_get(cached_resolve_pqueue, 0);
  396. if (resolve->expire > now)
  397. break;
  398. smartlist_pqueue_pop(cached_resolve_pqueue,
  399. compare_cached_resolves_by_expiry_,
  400. offsetof(cached_resolve_t, minheap_idx));
  401. if (resolve->state == CACHE_STATE_PENDING) {
  402. log_debug(LD_EXIT,
  403. "Expiring a dns resolve %s that's still pending. Forgot to "
  404. "cull it? DNS resolve didn't tell us about the timeout?",
  405. escaped_safe_str(resolve->address));
  406. } else if (resolve->state == CACHE_STATE_CACHED) {
  407. log_debug(LD_EXIT,
  408. "Forgetting old cached resolve (address %s, expires %lu)",
  409. escaped_safe_str(resolve->address),
  410. (unsigned long)resolve->expire);
  411. tor_assert(!resolve->pending_connections);
  412. } else {
  413. tor_assert(resolve->state == CACHE_STATE_DONE);
  414. tor_assert(!resolve->pending_connections);
  415. }
  416. if (resolve->pending_connections) {
  417. log_debug(LD_EXIT,
  418. "Closing pending connections on timed-out DNS resolve!");
  419. while (resolve->pending_connections) {
  420. pend = resolve->pending_connections;
  421. resolve->pending_connections = pend->next;
  422. /* Connections should only be pending if they have no socket. */
  423. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  424. pendconn = pend->conn;
  425. /* Prevent double-remove */
  426. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  427. if (!pendconn->base_.marked_for_close) {
  428. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  429. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  430. connection_free_(TO_CONN(pendconn));
  431. }
  432. tor_free(pend);
  433. }
  434. }
  435. if (resolve->state == CACHE_STATE_CACHED ||
  436. resolve->state == CACHE_STATE_PENDING) {
  437. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  438. if (removed != resolve) {
  439. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  440. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  441. resolve->address, (void*)resolve,
  442. removed ? removed->address : "NULL", (void*)removed);
  443. }
  444. tor_assert(removed == resolve);
  445. } else {
  446. /* This should be in state DONE. Make sure it's not in the cache. */
  447. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  448. tor_assert(tmp != resolve);
  449. }
  450. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  451. tor_free(resolve->result_ptr.hostname);
  452. resolve->magic = 0xF0BBF0BB;
  453. tor_free(resolve);
  454. }
  455. assert_cache_ok();
  456. }
  457. /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
  458. * or ipv6 depending on the connection's address". */
  459. #define RESOLVED_TYPE_AUTO 0xff
  460. /** Send a response to the RESOLVE request of a connection.
  461. * <b>answer_type</b> must be one of
  462. * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
  463. *
  464. * If <b>circ</b> is provided, and we have a cached answer, send the
  465. * answer back along circ; otherwise, send the answer back along
  466. * <b>conn</b>'s attached circuit.
  467. */
  468. MOCK_IMPL(STATIC void,
  469. send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type,
  470. const cached_resolve_t *resolved))
  471. {
  472. char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
  473. size_t buflen = 0;
  474. uint32_t ttl;
  475. buf[0] = answer_type;
  476. ttl = dns_clip_ttl(conn->address_ttl);
  477. switch (answer_type)
  478. {
  479. case RESOLVED_TYPE_AUTO:
  480. if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
  481. cp[0] = RESOLVED_TYPE_IPV4;
  482. cp[1] = 4;
  483. set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
  484. set_uint32(cp+6, htonl(ttl));
  485. cp += 10;
  486. }
  487. if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
  488. const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
  489. cp[0] = RESOLVED_TYPE_IPV6;
  490. cp[1] = 16;
  491. memcpy(cp+2, bytes, 16);
  492. set_uint32(cp+18, htonl(ttl));
  493. cp += 22;
  494. }
  495. if (cp != buf) {
  496. buflen = cp - buf;
  497. break;
  498. } else {
  499. answer_type = RESOLVED_TYPE_ERROR;
  500. /* fall through. */
  501. }
  502. /* Falls through. */
  503. case RESOLVED_TYPE_ERROR_TRANSIENT:
  504. case RESOLVED_TYPE_ERROR:
  505. {
  506. const char *errmsg = "Error resolving hostname";
  507. size_t msglen = strlen(errmsg);
  508. buf[0] = answer_type;
  509. buf[1] = msglen;
  510. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  511. set_uint32(buf+2+msglen, htonl(ttl));
  512. buflen = 6+msglen;
  513. break;
  514. }
  515. default:
  516. tor_assert(0);
  517. return;
  518. }
  519. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  520. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  521. }
  522. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  523. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  524. * The answer type will be RESOLVED_HOSTNAME.
  525. *
  526. * If <b>circ</b> is provided, and we have a cached answer, send the
  527. * answer back along circ; otherwise, send the answer back along
  528. * <b>conn</b>'s attached circuit.
  529. */
  530. MOCK_IMPL(STATIC void,
  531. send_resolved_hostname_cell,(edge_connection_t *conn,
  532. const char *hostname))
  533. {
  534. char buf[RELAY_PAYLOAD_SIZE];
  535. size_t buflen;
  536. uint32_t ttl;
  537. size_t namelen = strlen(hostname);
  538. tor_assert(hostname);
  539. tor_assert(namelen < 256);
  540. ttl = dns_clip_ttl(conn->address_ttl);
  541. buf[0] = RESOLVED_TYPE_HOSTNAME;
  542. buf[1] = (uint8_t)namelen;
  543. memcpy(buf+2, hostname, namelen);
  544. set_uint32(buf+2+namelen, htonl(ttl));
  545. buflen = 2+namelen+4;
  546. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  547. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  548. // log_notice(LD_EXIT, "Sent");
  549. }
  550. /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
  551. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  552. * If resolve failed, free exitconn and return -1.
  553. *
  554. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  555. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  556. * need to send back an END cell, since connection_exit_begin_conn will
  557. * do that for us.)
  558. *
  559. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  560. * circuit.
  561. *
  562. * Else, if seen before and pending, add conn to the pending list,
  563. * and return 0.
  564. *
  565. * Else, if not seen before, add conn to pending list, hand to
  566. * dns farm, and return 0.
  567. *
  568. * Exitconn's on_circuit field must be set, but exitconn should not
  569. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  570. * On success, link the connection to n_streams if it's an exit connection.
  571. * On "pending", link the connection to resolving streams. Otherwise,
  572. * clear its on_circuit field.
  573. */
  574. int
  575. dns_resolve(edge_connection_t *exitconn)
  576. {
  577. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  578. int is_resolve, r;
  579. int made_connection_pending = 0;
  580. char *hostname = NULL;
  581. cached_resolve_t *resolve = NULL;
  582. is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  583. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
  584. &made_connection_pending, &resolve);
  585. switch (r) {
  586. case 1:
  587. /* We got an answer without a lookup -- either the answer was
  588. * cached, or it was obvious (like an IP address). */
  589. if (is_resolve) {
  590. /* Send the answer back right now, and detach. */
  591. if (hostname)
  592. send_resolved_hostname_cell(exitconn, hostname);
  593. else
  594. send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
  595. exitconn->on_circuit = NULL;
  596. } else {
  597. /* Add to the n_streams list; the calling function will send back a
  598. * connected cell. */
  599. exitconn->next_stream = oncirc->n_streams;
  600. oncirc->n_streams = exitconn;
  601. }
  602. break;
  603. case 0:
  604. /* The request is pending: add the connection into the linked list of
  605. * resolving_streams on this circuit. */
  606. exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
  607. exitconn->next_stream = oncirc->resolving_streams;
  608. oncirc->resolving_streams = exitconn;
  609. break;
  610. case -2:
  611. case -1:
  612. /* The request failed before it could start: cancel this connection,
  613. * and stop everybody waiting for the same connection. */
  614. if (is_resolve) {
  615. send_resolved_cell(exitconn,
  616. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  617. NULL);
  618. }
  619. exitconn->on_circuit = NULL;
  620. dns_cancel_pending_resolve(exitconn->base_.address);
  621. if (!made_connection_pending && !exitconn->base_.marked_for_close) {
  622. /* If we made the connection pending, then we freed it already in
  623. * dns_cancel_pending_resolve(). If we marked it for close, it'll
  624. * get freed from the main loop. Otherwise, can free it now. */
  625. connection_free_(TO_CONN(exitconn));
  626. }
  627. break;
  628. default:
  629. tor_assert(0);
  630. }
  631. tor_free(hostname);
  632. return r;
  633. }
  634. /** Helper function for dns_resolve: same functionality, but does not handle:
  635. * - marking connections on error and clearing their on_circuit
  636. * - linking connections to n_streams/resolving_streams,
  637. * - sending resolved cells if we have an answer/error right away,
  638. *
  639. * Return -2 on a transient error. If it's a reverse resolve and it's
  640. * successful, sets *<b>hostname_out</b> to a newly allocated string
  641. * holding the cached reverse DNS value.
  642. *
  643. * Set *<b>made_connection_pending_out</b> to true if we have placed
  644. * <b>exitconn</b> on the list of pending connections for some resolve; set it
  645. * to false otherwise.
  646. *
  647. * Set *<b>resolve_out</b> to a cached resolve, if we found one.
  648. */
  649. MOCK_IMPL(STATIC int,
  650. dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
  651. or_circuit_t *oncirc, char **hostname_out,
  652. int *made_connection_pending_out,
  653. cached_resolve_t **resolve_out))
  654. {
  655. cached_resolve_t *resolve;
  656. cached_resolve_t search;
  657. pending_connection_t *pending_connection;
  658. int is_reverse = 0;
  659. tor_addr_t addr;
  660. time_t now = time(NULL);
  661. int r;
  662. assert_connection_ok(TO_CONN(exitconn), 0);
  663. tor_assert(!SOCKET_OK(exitconn->base_.s));
  664. assert_cache_ok();
  665. tor_assert(oncirc);
  666. *made_connection_pending_out = 0;
  667. /* first check if exitconn->base_.address is an IP. If so, we already
  668. * know the answer. */
  669. if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
  670. if (tor_addr_family(&addr) == AF_INET ||
  671. tor_addr_family(&addr) == AF_INET6) {
  672. tor_addr_copy(&exitconn->base_.addr, &addr);
  673. exitconn->address_ttl = DEFAULT_DNS_TTL;
  674. return 1;
  675. } else {
  676. /* XXXX unspec? Bogus? */
  677. return -1;
  678. }
  679. }
  680. /* If we're a non-exit, don't even do DNS lookups. */
  681. if (router_my_exit_policy_is_reject_star())
  682. return -1;
  683. if (address_is_invalid_destination(exitconn->base_.address, 0)) {
  684. tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
  685. "Rejecting invalid destination address %s",
  686. escaped_safe_str(exitconn->base_.address));
  687. return -1;
  688. }
  689. /* then take this opportunity to see if there are any expired
  690. * resolves in the hash table. */
  691. purge_expired_resolves(now);
  692. /* lower-case exitconn->base_.address, so it's in canonical form */
  693. tor_strlower(exitconn->base_.address);
  694. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  695. * .in-addr.arpa address but this isn't a resolve request, kill the
  696. * connection.
  697. */
  698. if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
  699. AF_UNSPEC, 0)) != 0) {
  700. if (r == 1) {
  701. is_reverse = 1;
  702. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  703. return -1;
  704. }
  705. if (!is_reverse || !is_resolve) {
  706. if (!is_reverse)
  707. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  708. escaped_safe_str(exitconn->base_.address));
  709. else if (!is_resolve)
  710. log_info(LD_EXIT,
  711. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  712. "sending error.",
  713. escaped_safe_str(exitconn->base_.address));
  714. return -1;
  715. }
  716. //log_notice(LD_EXIT, "Looks like an address %s",
  717. //exitconn->base_.address);
  718. }
  719. exitconn->is_reverse_dns_lookup = is_reverse;
  720. /* now check the hash table to see if 'address' is already there. */
  721. strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
  722. resolve = HT_FIND(cache_map, &cache_root, &search);
  723. if (resolve && resolve->expire > now) { /* already there */
  724. switch (resolve->state) {
  725. case CACHE_STATE_PENDING:
  726. /* add us to the pending list */
  727. pending_connection = tor_malloc_zero(
  728. sizeof(pending_connection_t));
  729. pending_connection->conn = exitconn;
  730. pending_connection->next = resolve->pending_connections;
  731. resolve->pending_connections = pending_connection;
  732. *made_connection_pending_out = 1;
  733. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
  734. "for pending DNS resolve of %s", exitconn->base_.s,
  735. escaped_safe_str(exitconn->base_.address));
  736. return 0;
  737. case CACHE_STATE_CACHED:
  738. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
  739. "cached answer for %s",
  740. exitconn->base_.s,
  741. escaped_safe_str(resolve->address));
  742. *resolve_out = resolve;
  743. return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
  744. case CACHE_STATE_DONE:
  745. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  746. tor_fragile_assert();
  747. }
  748. tor_assert(0);
  749. }
  750. tor_assert(!resolve);
  751. /* not there, need to add it */
  752. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  753. resolve->magic = CACHED_RESOLVE_MAGIC;
  754. resolve->state = CACHE_STATE_PENDING;
  755. resolve->minheap_idx = -1;
  756. strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
  757. /* add this connection to the pending list */
  758. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  759. pending_connection->conn = exitconn;
  760. resolve->pending_connections = pending_connection;
  761. *made_connection_pending_out = 1;
  762. /* Add this resolve to the cache and priority queue. */
  763. HT_INSERT(cache_map, &cache_root, resolve);
  764. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  765. log_debug(LD_EXIT,"Launching %s.",
  766. escaped_safe_str(exitconn->base_.address));
  767. assert_cache_ok();
  768. return launch_resolve(resolve);
  769. }
  770. /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
  771. * <b>resolve</b> whose DNS lookups have all either succeeded or failed,
  772. * update the appropriate fields (address_ttl and addr) of <b>exitconn</b>.
  773. *
  774. * The logic can be complicated here, since we might have launched both
  775. * an A lookup and an AAAA lookup, and since either of those might have
  776. * succeeded or failed, and since we want to answer a RESOLVE cell with
  777. * a full answer but answer a BEGIN cell with whatever answer the client
  778. * would accept <i>and</i> we could still connect to.
  779. *
  780. * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
  781. * copy of the name resulting hostname.
  782. *
  783. * Return -2 on a transient error, -1 on a permenent error, and 1 on
  784. * a successful lookup.
  785. */
  786. MOCK_IMPL(STATIC int,
  787. set_exitconn_info_from_resolve,(edge_connection_t *exitconn,
  788. const cached_resolve_t *resolve,
  789. char **hostname_out))
  790. {
  791. int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
  792. uint32_t begincell_flags;
  793. const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  794. tor_assert(exitconn);
  795. tor_assert(resolve);
  796. if (exitconn->is_reverse_dns_lookup) {
  797. exitconn->address_ttl = resolve->ttl_hostname;
  798. if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
  799. *hostname_out = tor_strdup(resolve->result_ptr.hostname);
  800. return 1;
  801. } else {
  802. return -1;
  803. }
  804. }
  805. /* If we're here then the connection wants one or either of ipv4, ipv6, and
  806. * we can give it one or both. */
  807. if (is_resolve) {
  808. begincell_flags = BEGIN_FLAG_IPV6_OK;
  809. } else {
  810. begincell_flags = exitconn->begincell_flags;
  811. }
  812. ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
  813. ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
  814. ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
  815. (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
  816. get_options()->IPv6Exit;
  817. /* Now decide which one to actually give. */
  818. if (ipv4_ok && ipv6_ok && is_resolve) {
  819. answer_with_ipv4 = 1;
  820. } else if (ipv4_ok && ipv6_ok) {
  821. /* If we have both, see if our exit policy has an opinion. */
  822. const uint16_t port = exitconn->base_.port;
  823. int ipv4_allowed, ipv6_allowed;
  824. tor_addr_t a4, a6;
  825. tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
  826. tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
  827. ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
  828. ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
  829. if (ipv4_allowed && !ipv6_allowed) {
  830. answer_with_ipv4 = 1;
  831. } else if (ipv6_allowed && !ipv4_allowed) {
  832. answer_with_ipv4 = 0;
  833. } else {
  834. /* Our exit policy would permit both. Answer with whichever the user
  835. * prefers */
  836. answer_with_ipv4 = !(begincell_flags &
  837. BEGIN_FLAG_IPV6_PREFERRED);
  838. }
  839. } else {
  840. /* Otherwise if one is okay, send it back. */
  841. if (ipv4_ok) {
  842. answer_with_ipv4 = 1;
  843. } else if (ipv6_ok) {
  844. answer_with_ipv4 = 0;
  845. } else {
  846. /* Neither one was okay. Choose based on user preference. */
  847. answer_with_ipv4 = !(begincell_flags &
  848. BEGIN_FLAG_IPV6_PREFERRED);
  849. }
  850. }
  851. /* Finally, we write the answer back. */
  852. r = 1;
  853. if (answer_with_ipv4) {
  854. if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
  855. tor_addr_from_ipv4h(&exitconn->base_.addr,
  856. resolve->result_ipv4.addr_ipv4);
  857. } else {
  858. r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
  859. }
  860. exitconn->address_ttl = resolve->ttl_ipv4;
  861. } else {
  862. if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
  863. tor_addr_from_in6(&exitconn->base_.addr,
  864. &resolve->result_ipv6.addr_ipv6);
  865. } else {
  866. r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
  867. }
  868. exitconn->address_ttl = resolve->ttl_ipv6;
  869. }
  870. return r;
  871. }
  872. /** Log an error and abort if conn is waiting for a DNS resolve.
  873. */
  874. void
  875. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  876. {
  877. pending_connection_t *pend;
  878. cached_resolve_t search;
  879. #if 1
  880. cached_resolve_t *resolve;
  881. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  882. resolve = HT_FIND(cache_map, &cache_root, &search);
  883. if (!resolve)
  884. return;
  885. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  886. tor_assert(pend->conn != conn);
  887. }
  888. #else /* !(1) */
  889. cached_resolve_t **resolve;
  890. HT_FOREACH(resolve, cache_map, &cache_root) {
  891. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  892. tor_assert(pend->conn != conn);
  893. }
  894. }
  895. #endif /* 1 */
  896. }
  897. /** Log an error and abort if any connection waiting for a DNS resolve is
  898. * corrupted. */
  899. void
  900. assert_all_pending_dns_resolves_ok(void)
  901. {
  902. pending_connection_t *pend;
  903. cached_resolve_t **resolve;
  904. HT_FOREACH(resolve, cache_map, &cache_root) {
  905. for (pend = (*resolve)->pending_connections;
  906. pend;
  907. pend = pend->next) {
  908. assert_connection_ok(TO_CONN(pend->conn), 0);
  909. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  910. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  911. }
  912. }
  913. }
  914. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  915. */
  916. void
  917. connection_dns_remove(edge_connection_t *conn)
  918. {
  919. pending_connection_t *pend, *victim;
  920. cached_resolve_t search;
  921. cached_resolve_t *resolve;
  922. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  923. tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
  924. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  925. resolve = HT_FIND(cache_map, &cache_root, &search);
  926. if (!resolve) {
  927. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  928. escaped_safe_str(conn->base_.address));
  929. return;
  930. }
  931. tor_assert(resolve->pending_connections);
  932. assert_connection_ok(TO_CONN(conn),0);
  933. pend = resolve->pending_connections;
  934. if (pend->conn == conn) {
  935. resolve->pending_connections = pend->next;
  936. tor_free(pend);
  937. log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
  938. "longer waiting for resolve of %s",
  939. conn->base_.s,
  940. escaped_safe_str(conn->base_.address));
  941. return;
  942. } else {
  943. for ( ; pend->next; pend = pend->next) {
  944. if (pend->next->conn == conn) {
  945. victim = pend->next;
  946. pend->next = victim->next;
  947. tor_free(victim);
  948. log_debug(LD_EXIT,
  949. "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
  950. "for resolve of %s",
  951. conn->base_.s, escaped_safe_str(conn->base_.address));
  952. return; /* more are pending */
  953. }
  954. }
  955. log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
  956. "for a resolve of %s, but we tried to remove it.",
  957. conn->base_.s, escaped_safe_str(conn->base_.address));
  958. }
  959. }
  960. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  961. * the resolve for <b>address</b> itself, and remove any cached results for
  962. * <b>address</b> from the cache.
  963. */
  964. MOCK_IMPL(void,
  965. dns_cancel_pending_resolve,(const char *address))
  966. {
  967. pending_connection_t *pend;
  968. cached_resolve_t search;
  969. cached_resolve_t *resolve, *tmp;
  970. edge_connection_t *pendconn;
  971. circuit_t *circ;
  972. strlcpy(search.address, address, sizeof(search.address));
  973. resolve = HT_FIND(cache_map, &cache_root, &search);
  974. if (!resolve)
  975. return;
  976. if (resolve->state != CACHE_STATE_PENDING) {
  977. /* We can get into this state if we never actually created the pending
  978. * resolve, due to finding an earlier cached error or something. Just
  979. * ignore it. */
  980. if (resolve->pending_connections) {
  981. log_warn(LD_BUG,
  982. "Address %s is not pending but has pending connections!",
  983. escaped_safe_str(address));
  984. tor_fragile_assert();
  985. }
  986. return;
  987. }
  988. if (!resolve->pending_connections) {
  989. log_warn(LD_BUG,
  990. "Address %s is pending but has no pending connections!",
  991. escaped_safe_str(address));
  992. tor_fragile_assert();
  993. return;
  994. }
  995. tor_assert(resolve->pending_connections);
  996. /* mark all pending connections to fail */
  997. log_debug(LD_EXIT,
  998. "Failing all connections waiting on DNS resolve of %s",
  999. escaped_safe_str(address));
  1000. while (resolve->pending_connections) {
  1001. pend = resolve->pending_connections;
  1002. pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1003. pendconn = pend->conn;
  1004. assert_connection_ok(TO_CONN(pendconn), 0);
  1005. tor_assert(!SOCKET_OK(pendconn->base_.s));
  1006. if (!pendconn->base_.marked_for_close) {
  1007. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1008. }
  1009. circ = circuit_get_by_edge_conn(pendconn);
  1010. if (circ)
  1011. circuit_detach_stream(circ, pendconn);
  1012. if (!pendconn->base_.marked_for_close)
  1013. connection_free_(TO_CONN(pendconn));
  1014. resolve->pending_connections = pend->next;
  1015. tor_free(pend);
  1016. }
  1017. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  1018. if (tmp != resolve) {
  1019. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  1020. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1021. resolve->address, (void*)resolve,
  1022. tmp ? tmp->address : "NULL", (void*)tmp);
  1023. }
  1024. tor_assert(tmp == resolve);
  1025. resolve->state = CACHE_STATE_DONE;
  1026. }
  1027. /** Return true iff <b>address</b> is one of the addresses we use to verify
  1028. * that well-known sites aren't being hijacked by our DNS servers. */
  1029. static inline int
  1030. is_test_address(const char *address)
  1031. {
  1032. const or_options_t *options = get_options();
  1033. return options->ServerDNSTestAddresses &&
  1034. smartlist_contains_string_case(options->ServerDNSTestAddresses, address);
  1035. }
  1036. /** Called on the OR side when the eventdns library tells us the outcome of a
  1037. * single DNS resolve: remember the answer, and tell all pending connections
  1038. * about the result of the lookup if the lookup is now done. (<b>address</b>
  1039. * is a NUL-terminated string containing the address to look up;
  1040. * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
  1041. * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
  1042. * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
  1043. * <b>ttl</b> is the time-to-live of this answer, in seconds.)
  1044. */
  1045. static void
  1046. dns_found_answer(const char *address, uint8_t query_type,
  1047. int dns_answer,
  1048. const tor_addr_t *addr,
  1049. const char *hostname, uint32_t ttl)
  1050. {
  1051. cached_resolve_t search;
  1052. cached_resolve_t *resolve;
  1053. assert_cache_ok();
  1054. strlcpy(search.address, address, sizeof(search.address));
  1055. resolve = HT_FIND(cache_map, &cache_root, &search);
  1056. if (!resolve) {
  1057. int is_test_addr = is_test_address(address);
  1058. if (!is_test_addr)
  1059. log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
  1060. escaped_safe_str(address));
  1061. return;
  1062. }
  1063. assert_resolve_ok(resolve);
  1064. if (resolve->state != CACHE_STATE_PENDING) {
  1065. /* XXXX Maybe update addr? or check addr for consistency? Or let
  1066. * VALID replace FAILED? */
  1067. int is_test_addr = is_test_address(address);
  1068. if (!is_test_addr)
  1069. log_notice(LD_EXIT,
  1070. "Resolved %s which was already resolved; ignoring",
  1071. escaped_safe_str(address));
  1072. tor_assert(resolve->pending_connections == NULL);
  1073. return;
  1074. }
  1075. cached_resolve_add_answer(resolve, query_type, dns_answer,
  1076. addr, hostname, ttl);
  1077. if (cached_resolve_have_all_answers(resolve)) {
  1078. inform_pending_connections(resolve);
  1079. make_pending_resolve_cached(resolve);
  1080. }
  1081. }
  1082. /** Given a pending cached_resolve_t that we just finished resolving,
  1083. * inform every connection that was waiting for the outcome of that
  1084. * resolution.
  1085. *
  1086. * Do this by sending a RELAY_RESOLVED cell (if the pending stream had sent us
  1087. * RELAY_RESOLVE cell), or by launching an exit connection (if the pending
  1088. * stream had send us a RELAY_BEGIN cell).
  1089. */
  1090. static void
  1091. inform_pending_connections(cached_resolve_t *resolve)
  1092. {
  1093. pending_connection_t *pend;
  1094. edge_connection_t *pendconn;
  1095. int r;
  1096. while (resolve->pending_connections) {
  1097. char *hostname = NULL;
  1098. pend = resolve->pending_connections;
  1099. pendconn = pend->conn; /* don't pass complex things to the
  1100. connection_mark_for_close macro */
  1101. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  1102. if (pendconn->base_.marked_for_close) {
  1103. /* prevent double-remove. */
  1104. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1105. resolve->pending_connections = pend->next;
  1106. tor_free(pend);
  1107. continue;
  1108. }
  1109. r = set_exitconn_info_from_resolve(pendconn,
  1110. resolve,
  1111. &hostname);
  1112. if (r < 0) {
  1113. /* prevent double-remove. */
  1114. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1115. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1116. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1117. /* This detach must happen after we send the end cell. */
  1118. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1119. } else {
  1120. send_resolved_cell(pendconn, r == -1 ?
  1121. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  1122. NULL);
  1123. /* This detach must happen after we send the resolved cell. */
  1124. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1125. }
  1126. connection_free_(TO_CONN(pendconn));
  1127. } else {
  1128. circuit_t *circ;
  1129. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1130. /* prevent double-remove. */
  1131. pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  1132. circ = circuit_get_by_edge_conn(pend->conn);
  1133. tor_assert(circ);
  1134. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1135. /* unlink pend->conn from resolving_streams, */
  1136. circuit_detach_stream(circ, pend->conn);
  1137. /* and link it to n_streams */
  1138. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1139. pend->conn->on_circuit = circ;
  1140. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1141. connection_exit_connect(pend->conn);
  1142. } else {
  1143. /* prevent double-remove. This isn't really an accurate state,
  1144. * but it does the right thing. */
  1145. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1146. if (pendconn->is_reverse_dns_lookup)
  1147. send_resolved_hostname_cell(pendconn, hostname);
  1148. else
  1149. send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
  1150. circ = circuit_get_by_edge_conn(pendconn);
  1151. tor_assert(circ);
  1152. circuit_detach_stream(circ, pendconn);
  1153. connection_free_(TO_CONN(pendconn));
  1154. }
  1155. }
  1156. resolve->pending_connections = pend->next;
  1157. tor_free(pend);
  1158. tor_free(hostname);
  1159. }
  1160. }
  1161. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1162. * corresponding cached cached_resolve_t.
  1163. *
  1164. * This function is only necessary because of the perversity of our
  1165. * cache timeout code; see inline comment for ideas on eliminating it.
  1166. **/
  1167. static void
  1168. make_pending_resolve_cached(cached_resolve_t *resolve)
  1169. {
  1170. cached_resolve_t *removed;
  1171. resolve->state = CACHE_STATE_DONE;
  1172. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1173. if (removed != resolve) {
  1174. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1175. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1176. resolve->address, (void*)resolve,
  1177. removed ? removed->address : "NULL", (void*)removed);
  1178. }
  1179. assert_resolve_ok(resolve);
  1180. assert_cache_ok();
  1181. /* The resolve will eventually just hit the time-out in the expiry queue and
  1182. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1183. * way. XXXXX we could do better!*/
  1184. {
  1185. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1186. sizeof(cached_resolve_t));
  1187. uint32_t ttl = UINT32_MAX;
  1188. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1189. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1190. new_resolve->result_ptr.hostname =
  1191. tor_strdup(resolve->result_ptr.hostname);
  1192. new_resolve->state = CACHE_STATE_CACHED;
  1193. assert_resolve_ok(new_resolve);
  1194. HT_INSERT(cache_map, &cache_root, new_resolve);
  1195. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1196. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1197. resolve->ttl_ipv4 < ttl)
  1198. ttl = resolve->ttl_ipv4;
  1199. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1200. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1201. resolve->ttl_ipv6 < ttl)
  1202. ttl = resolve->ttl_ipv6;
  1203. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1204. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1205. resolve->ttl_hostname < ttl)
  1206. ttl = resolve->ttl_hostname;
  1207. set_expiry(new_resolve, time(NULL) + dns_clip_ttl(ttl));
  1208. }
  1209. assert_cache_ok();
  1210. }
  1211. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1212. * a transient failure. */
  1213. static int
  1214. evdns_err_is_transient(int err)
  1215. {
  1216. switch (err)
  1217. {
  1218. case DNS_ERR_SERVERFAILED:
  1219. case DNS_ERR_TRUNCATED:
  1220. case DNS_ERR_TIMEOUT:
  1221. return 1;
  1222. default:
  1223. return 0;
  1224. }
  1225. }
  1226. /** Configure eventdns nameservers if force is true, or if the configuration
  1227. * has changed since the last time we called this function, or if we failed on
  1228. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1229. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1230. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1231. * -1 on failure. */
  1232. static int
  1233. configure_nameservers(int force)
  1234. {
  1235. const or_options_t *options;
  1236. const char *conf_fname;
  1237. struct stat st;
  1238. int r, flags;
  1239. options = get_options();
  1240. conf_fname = options->ServerDNSResolvConfFile;
  1241. #ifndef _WIN32
  1242. if (!conf_fname)
  1243. conf_fname = "/etc/resolv.conf";
  1244. #endif
  1245. flags = DNS_OPTIONS_ALL;
  1246. if (!the_evdns_base) {
  1247. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1248. log_err(LD_BUG, "Couldn't create an evdns_base");
  1249. return -1;
  1250. }
  1251. }
  1252. evdns_set_log_fn(evdns_log_cb);
  1253. if (conf_fname) {
  1254. log_debug(LD_FS, "stat()ing %s", conf_fname);
  1255. if (stat(sandbox_intern_string(conf_fname), &st)) {
  1256. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1257. conf_fname, strerror(errno));
  1258. goto err;
  1259. }
  1260. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1261. && st.st_mtime == resolv_conf_mtime) {
  1262. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1263. return 0;
  1264. }
  1265. if (nameservers_configured) {
  1266. evdns_base_search_clear(the_evdns_base);
  1267. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1268. }
  1269. #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
  1270. if (flags & DNS_OPTION_HOSTSFILE) {
  1271. flags ^= DNS_OPTION_HOSTSFILE;
  1272. log_debug(LD_FS, "Loading /etc/hosts");
  1273. evdns_base_load_hosts(the_evdns_base,
  1274. sandbox_intern_string("/etc/hosts"));
  1275. }
  1276. #endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
  1277. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1278. if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
  1279. sandbox_intern_string(conf_fname)))) {
  1280. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1281. conf_fname, conf_fname, r);
  1282. goto err;
  1283. }
  1284. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1285. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1286. goto err;
  1287. }
  1288. tor_free(resolv_conf_fname);
  1289. resolv_conf_fname = tor_strdup(conf_fname);
  1290. resolv_conf_mtime = st.st_mtime;
  1291. if (nameservers_configured)
  1292. evdns_base_resume(the_evdns_base);
  1293. }
  1294. #ifdef _WIN32
  1295. else {
  1296. if (nameservers_configured) {
  1297. evdns_base_search_clear(the_evdns_base);
  1298. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1299. }
  1300. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1301. log_warn(LD_EXIT,"Could not config nameservers.");
  1302. goto err;
  1303. }
  1304. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1305. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1306. "your Windows configuration.");
  1307. goto err;
  1308. }
  1309. if (nameservers_configured)
  1310. evdns_base_resume(the_evdns_base);
  1311. tor_free(resolv_conf_fname);
  1312. resolv_conf_mtime = 0;
  1313. }
  1314. #endif /* defined(_WIN32) */
  1315. #define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
  1316. // If we only have one nameserver, it does not make sense to back off
  1317. // from it for a timeout. Unfortunately, the value for max-timeouts is
  1318. // currently clamped by libevent to 255, but it does not hurt to set
  1319. // it higher in case libevent gets a patch for this. Higher-than-
  1320. // default maximum of 3 with multiple nameservers to avoid spuriously
  1321. // marking one down on bursts of timeouts resulting from scans/attacks
  1322. // against non-responding authoritative DNS servers.
  1323. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1324. SET("max-timeouts:", "1000000");
  1325. } else {
  1326. SET("max-timeouts:", "10");
  1327. }
  1328. // Elongate the queue of maximum inflight dns requests, so if a bunch
  1329. // remain pending at the resolver (happens commonly with Unbound) we won't
  1330. // stall every other DNS request. This potentially means some wasted
  1331. // CPU as there's a walk over a linear queue involved, but this is a
  1332. // much better tradeoff compared to just failing DNS requests because
  1333. // of a full queue.
  1334. SET("max-inflight:", "8192");
  1335. // Two retries at 5 and 10 seconds for bind9/named which relies on
  1336. // clients to handle retries. Second retry for retried circuits with
  1337. // extended 15 second timeout. Superfluous with local-system Unbound
  1338. // instance--has its own elaborate retry scheme.
  1339. SET("timeout:", "5");
  1340. SET("attempts:","3");
  1341. if (options->ServerDNSRandomizeCase)
  1342. SET("randomize-case:", "1");
  1343. else
  1344. SET("randomize-case:", "0");
  1345. #undef SET
  1346. dns_servers_relaunch_checks();
  1347. nameservers_configured = 1;
  1348. if (nameserver_config_failed) {
  1349. nameserver_config_failed = 0;
  1350. /* XXX the three calls to republish the descriptor might be producing
  1351. * descriptors that are only cosmetically different, especially on
  1352. * non-exit relays! -RD */
  1353. mark_my_descriptor_dirty("dns resolvers back");
  1354. }
  1355. return 0;
  1356. err:
  1357. nameservers_configured = 0;
  1358. if (! nameserver_config_failed) {
  1359. nameserver_config_failed = 1;
  1360. mark_my_descriptor_dirty("dns resolvers failed");
  1361. }
  1362. return -1;
  1363. }
  1364. /** For eventdns: Called when we get an answer for a request we launched.
  1365. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1366. */
  1367. static void
  1368. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1369. void *arg)
  1370. {
  1371. char *arg_ = arg;
  1372. uint8_t orig_query_type = arg_[0];
  1373. char *string_address = arg_ + 1;
  1374. tor_addr_t addr;
  1375. const char *hostname = NULL;
  1376. int was_wildcarded = 0;
  1377. tor_addr_make_unspec(&addr);
  1378. /* Keep track of whether IPv6 is working */
  1379. if (type == DNS_IPv6_AAAA) {
  1380. if (result == DNS_ERR_TIMEOUT) {
  1381. ++n_ipv6_timeouts;
  1382. }
  1383. if (n_ipv6_timeouts > 10 &&
  1384. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1385. if (! dns_is_broken_for_ipv6) {
  1386. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1387. "have timed out. I'm going to assume I can't get AAAA "
  1388. "responses.");
  1389. dns_is_broken_for_ipv6 = 1;
  1390. }
  1391. }
  1392. }
  1393. if (result == DNS_ERR_NONE) {
  1394. if (type == DNS_IPv4_A && count) {
  1395. char answer_buf[INET_NTOA_BUF_LEN+1];
  1396. char *escaped_address;
  1397. uint32_t *addrs = addresses;
  1398. tor_addr_from_ipv4n(&addr, addrs[0]);
  1399. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1400. escaped_address = esc_for_log(string_address);
  1401. if (answer_is_wildcarded(answer_buf)) {
  1402. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1403. "address %s; treating as a failure.",
  1404. safe_str(escaped_address),
  1405. escaped_safe_str(answer_buf));
  1406. was_wildcarded = 1;
  1407. tor_addr_make_unspec(&addr);
  1408. result = DNS_ERR_NOTEXIST;
  1409. } else {
  1410. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1411. safe_str(escaped_address),
  1412. escaped_safe_str(answer_buf));
  1413. }
  1414. tor_free(escaped_address);
  1415. } else if (type == DNS_IPv6_AAAA && count) {
  1416. char answer_buf[TOR_ADDR_BUF_LEN];
  1417. char *escaped_address;
  1418. struct in6_addr *addrs = addresses;
  1419. tor_addr_from_in6(&addr, &addrs[0]);
  1420. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1421. escaped_address = esc_for_log(string_address);
  1422. if (answer_is_wildcarded(answer_buf)) {
  1423. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1424. "address %s; treating as a failure.",
  1425. safe_str(escaped_address),
  1426. escaped_safe_str(answer_buf));
  1427. was_wildcarded = 1;
  1428. tor_addr_make_unspec(&addr);
  1429. result = DNS_ERR_NOTEXIST;
  1430. } else {
  1431. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1432. safe_str(escaped_address),
  1433. escaped_safe_str(answer_buf));
  1434. }
  1435. tor_free(escaped_address);
  1436. } else if (type == DNS_PTR && count) {
  1437. char *escaped_address;
  1438. hostname = ((char**)addresses)[0];
  1439. escaped_address = esc_for_log(string_address);
  1440. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1441. safe_str(escaped_address),
  1442. escaped_safe_str(hostname));
  1443. tor_free(escaped_address);
  1444. } else if (count) {
  1445. log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
  1446. " for %s.",
  1447. escaped_safe_str(string_address));
  1448. } else {
  1449. log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
  1450. escaped_safe_str(string_address));
  1451. }
  1452. }
  1453. if (was_wildcarded) {
  1454. if (is_test_address(string_address)) {
  1455. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1456. * server must really hate us. */
  1457. add_wildcarded_test_address(string_address);
  1458. }
  1459. }
  1460. if (orig_query_type && type && orig_query_type != type) {
  1461. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1462. (int)orig_query_type, (int)type);
  1463. }
  1464. if (result != DNS_ERR_SHUTDOWN)
  1465. dns_found_answer(string_address, orig_query_type,
  1466. result, &addr, hostname, ttl);
  1467. tor_free(arg_);
  1468. }
  1469. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1470. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1471. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1472. static int
  1473. launch_one_resolve(const char *address, uint8_t query_type,
  1474. const tor_addr_t *ptr_address)
  1475. {
  1476. const int options = get_options()->ServerDNSSearchDomains ? 0
  1477. : DNS_QUERY_NO_SEARCH;
  1478. const size_t addr_len = strlen(address);
  1479. struct evdns_request *req = 0;
  1480. char *addr = tor_malloc(addr_len + 2);
  1481. addr[0] = (char) query_type;
  1482. memcpy(addr+1, address, addr_len + 1);
  1483. switch (query_type) {
  1484. case DNS_IPv4_A:
  1485. req = evdns_base_resolve_ipv4(the_evdns_base,
  1486. address, options, evdns_callback, addr);
  1487. break;
  1488. case DNS_IPv6_AAAA:
  1489. req = evdns_base_resolve_ipv6(the_evdns_base,
  1490. address, options, evdns_callback, addr);
  1491. ++n_ipv6_requests_made;
  1492. break;
  1493. case DNS_PTR:
  1494. if (tor_addr_family(ptr_address) == AF_INET)
  1495. req = evdns_base_resolve_reverse(the_evdns_base,
  1496. tor_addr_to_in(ptr_address),
  1497. DNS_QUERY_NO_SEARCH,
  1498. evdns_callback, addr);
  1499. else if (tor_addr_family(ptr_address) == AF_INET6)
  1500. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1501. tor_addr_to_in6(ptr_address),
  1502. DNS_QUERY_NO_SEARCH,
  1503. evdns_callback, addr);
  1504. else
  1505. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1506. break;
  1507. default:
  1508. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1509. break;
  1510. }
  1511. if (req) {
  1512. return 0;
  1513. } else {
  1514. tor_free(addr);
  1515. return -1;
  1516. }
  1517. }
  1518. /** For eventdns: start resolving as necessary to find the target for
  1519. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1520. * 0 on "resolve launched." */
  1521. MOCK_IMPL(STATIC int,
  1522. launch_resolve,(cached_resolve_t *resolve))
  1523. {
  1524. tor_addr_t a;
  1525. int r;
  1526. if (net_is_disabled())
  1527. return -1;
  1528. /* What? Nameservers not configured? Sounds like a bug. */
  1529. if (!nameservers_configured) {
  1530. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1531. "launched. Configuring.");
  1532. if (configure_nameservers(1) < 0) {
  1533. return -1;
  1534. }
  1535. }
  1536. r = tor_addr_parse_PTR_name(
  1537. &a, resolve->address, AF_UNSPEC, 0);
  1538. tor_assert(the_evdns_base);
  1539. if (r == 0) {
  1540. log_info(LD_EXIT, "Launching eventdns request for %s",
  1541. escaped_safe_str(resolve->address));
  1542. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1543. if (get_options()->IPv6Exit)
  1544. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1545. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1546. resolve->res_status_ipv4 = 0;
  1547. r = -1;
  1548. }
  1549. if (r==0 && get_options()->IPv6Exit) {
  1550. /* We ask for an IPv6 address for *everything*. */
  1551. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1552. resolve->res_status_ipv6 = 0;
  1553. r = -1;
  1554. }
  1555. }
  1556. } else if (r == 1) {
  1557. r = 0;
  1558. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1559. escaped_safe_str(resolve->address));
  1560. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1561. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1562. resolve->res_status_hostname = 0;
  1563. r = -1;
  1564. }
  1565. } else if (r == -1) {
  1566. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1567. }
  1568. if (r < 0) {
  1569. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1570. escaped_safe_str(resolve->address));
  1571. }
  1572. return r;
  1573. }
  1574. /** How many requests for bogus addresses have we launched so far? */
  1575. static int n_wildcard_requests = 0;
  1576. /** Map from dotted-quad IP address in response to an int holding how many
  1577. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1578. * would be easier to use definitely-invalid addresses (as specified by
  1579. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1580. static strmap_t *dns_wildcard_response_count = NULL;
  1581. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1582. * nameserver wants to return in response to requests for nonexistent domains.
  1583. */
  1584. static smartlist_t *dns_wildcard_list = NULL;
  1585. /** True iff we've logged about a single address getting wildcarded.
  1586. * Subsequent warnings will be less severe. */
  1587. static int dns_wildcard_one_notice_given = 0;
  1588. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1589. */
  1590. static int dns_wildcard_notice_given = 0;
  1591. /** List of supposedly good addresses that are getting wildcarded to the
  1592. * same addresses as nonexistent addresses. */
  1593. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1594. /** True iff we've warned about a test address getting wildcarded */
  1595. static int dns_wildcarded_test_address_notice_given = 0;
  1596. /** True iff all addresses seem to be getting wildcarded. */
  1597. static int dns_is_completely_invalid = 0;
  1598. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1599. * to a request for a hopefully bogus address. */
  1600. static void
  1601. wildcard_increment_answer(const char *id)
  1602. {
  1603. int *ip;
  1604. if (!dns_wildcard_response_count)
  1605. dns_wildcard_response_count = strmap_new();
  1606. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1607. if (!ip) {
  1608. ip = tor_malloc_zero(sizeof(int));
  1609. strmap_set(dns_wildcard_response_count, id, ip);
  1610. }
  1611. ++*ip;
  1612. if (*ip > 5 && n_wildcard_requests > 10) {
  1613. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1614. if (!smartlist_contains_string(dns_wildcard_list, id)) {
  1615. tor_log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1616. "Your DNS provider has given \"%s\" as an answer for %d different "
  1617. "invalid addresses. Apparently they are hijacking DNS failures. "
  1618. "I'll try to correct for this by treating future occurrences of "
  1619. "\"%s\" as 'not found'.", id, *ip, id);
  1620. smartlist_add_strdup(dns_wildcard_list, id);
  1621. }
  1622. if (!dns_wildcard_notice_given)
  1623. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1624. dns_wildcard_notice_given = 1;
  1625. }
  1626. }
  1627. /** Note that a single test address (one believed to be good) seems to be
  1628. * getting redirected to the same IP as failures are. */
  1629. static void
  1630. add_wildcarded_test_address(const char *address)
  1631. {
  1632. int n, n_test_addrs;
  1633. if (!dns_wildcarded_test_address_list)
  1634. dns_wildcarded_test_address_list = smartlist_new();
  1635. if (smartlist_contains_string_case(dns_wildcarded_test_address_list,
  1636. address))
  1637. return;
  1638. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1639. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1640. smartlist_add_strdup(dns_wildcarded_test_address_list, address);
  1641. n = smartlist_len(dns_wildcarded_test_address_list);
  1642. if (n > n_test_addrs/2) {
  1643. tor_log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1644. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1645. "address. It has done this with %d test addresses so far. I'm "
  1646. "going to stop being an exit node for now, since our DNS seems so "
  1647. "broken.", address, n);
  1648. if (!dns_is_completely_invalid) {
  1649. dns_is_completely_invalid = 1;
  1650. mark_my_descriptor_dirty("dns hijacking confirmed");
  1651. }
  1652. if (!dns_wildcarded_test_address_notice_given)
  1653. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1654. dns_wildcarded_test_address_notice_given = 1;
  1655. }
  1656. }
  1657. /** Callback function when we get an answer (possibly failing) for a request
  1658. * for a (hopefully) nonexistent domain. */
  1659. static void
  1660. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1661. void *addresses, void *arg)
  1662. {
  1663. (void)ttl;
  1664. ++n_wildcard_requests;
  1665. if (result == DNS_ERR_NONE && count) {
  1666. char *string_address = arg;
  1667. int i;
  1668. if (type == DNS_IPv4_A) {
  1669. const uint32_t *addrs = addresses;
  1670. for (i = 0; i < count; ++i) {
  1671. char answer_buf[INET_NTOA_BUF_LEN+1];
  1672. struct in_addr in;
  1673. in.s_addr = addrs[i];
  1674. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1675. wildcard_increment_answer(answer_buf);
  1676. }
  1677. } else if (type == DNS_IPv6_AAAA) {
  1678. const struct in6_addr *addrs = addresses;
  1679. for (i = 0; i < count; ++i) {
  1680. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1681. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1682. wildcard_increment_answer(answer_buf);
  1683. }
  1684. }
  1685. tor_log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1686. "Your DNS provider gave an answer for \"%s\", which "
  1687. "is not supposed to exist. Apparently they are hijacking "
  1688. "DNS failures. Trying to correct for this. We've noticed %d "
  1689. "possibly bad address%s so far.",
  1690. string_address, strmap_size(dns_wildcard_response_count),
  1691. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1692. dns_wildcard_one_notice_given = 1;
  1693. }
  1694. tor_free(arg);
  1695. }
  1696. /** Launch a single request for a nonexistent hostname consisting of between
  1697. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1698. * <b>suffix</b> */
  1699. static void
  1700. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1701. const char *suffix)
  1702. {
  1703. char *addr;
  1704. struct evdns_request *req;
  1705. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1706. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1707. "domains with request for bogus hostname \"%s\"", addr);
  1708. tor_assert(the_evdns_base);
  1709. if (is_ipv6)
  1710. req = evdns_base_resolve_ipv6(
  1711. the_evdns_base,
  1712. /* This "addr" tells us which address to resolve */
  1713. addr,
  1714. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1715. /* This "addr" is an argument to the callback*/ addr);
  1716. else
  1717. req = evdns_base_resolve_ipv4(
  1718. the_evdns_base,
  1719. /* This "addr" tells us which address to resolve */
  1720. addr,
  1721. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1722. /* This "addr" is an argument to the callback*/ addr);
  1723. if (!req) {
  1724. /* There is no evdns request in progress; stop addr from getting leaked */
  1725. tor_free(addr);
  1726. }
  1727. }
  1728. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1729. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1730. static void
  1731. launch_test_addresses(evutil_socket_t fd, short event, void *args)
  1732. {
  1733. const or_options_t *options = get_options();
  1734. (void)fd;
  1735. (void)event;
  1736. (void)args;
  1737. if (net_is_disabled())
  1738. return;
  1739. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1740. "hijack *everything*.");
  1741. /* This situation is worse than the failure-hijacking situation. When this
  1742. * happens, we're no good for DNS requests at all, and we shouldn't really
  1743. * be an exit server.*/
  1744. if (options->ServerDNSTestAddresses) {
  1745. tor_assert(the_evdns_base);
  1746. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1747. const char *, address) {
  1748. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1749. log_info(LD_EXIT, "eventdns rejected test address %s",
  1750. escaped_safe_str(address));
  1751. }
  1752. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1753. log_info(LD_EXIT, "eventdns rejected test address %s",
  1754. escaped_safe_str(address));
  1755. }
  1756. } SMARTLIST_FOREACH_END(address);
  1757. }
  1758. }
  1759. #define N_WILDCARD_CHECKS 2
  1760. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1761. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1762. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1763. * buy these lovely encyclopedias" page. */
  1764. static void
  1765. dns_launch_wildcard_checks(void)
  1766. {
  1767. int i, ipv6;
  1768. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1769. "to hijack DNS failures.");
  1770. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1771. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1772. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1773. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1774. * these. This is the standards-compliance equivalent of making sure
  1775. * that your crackhouse's elevator inspection certificate is up to date.
  1776. */
  1777. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1778. launch_wildcard_check(2, 16, ipv6, ".test");
  1779. /* These will break specs if there are ever any number of
  1780. * 8+-character top-level domains. */
  1781. launch_wildcard_check(8, 16, ipv6, "");
  1782. /* Try some random .com/org/net domains. This will work fine so long as
  1783. * not too many resolve to the same place. */
  1784. launch_wildcard_check(8, 16, ipv6, ".com");
  1785. launch_wildcard_check(8, 16, ipv6, ".org");
  1786. launch_wildcard_check(8, 16, ipv6, ".net");
  1787. }
  1788. }
  1789. }
  1790. /** If appropriate, start testing whether our DNS servers tend to lie to
  1791. * us. */
  1792. void
  1793. dns_launch_correctness_checks(void)
  1794. {
  1795. static struct event *launch_event = NULL;
  1796. struct timeval timeout;
  1797. if (!get_options()->ServerDNSDetectHijacking)
  1798. return;
  1799. dns_launch_wildcard_checks();
  1800. /* Wait a while before launching requests for test addresses, so we can
  1801. * get the results from checking for wildcarding. */
  1802. if (! launch_event)
  1803. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1804. launch_test_addresses, NULL);
  1805. timeout.tv_sec = 30;
  1806. timeout.tv_usec = 0;
  1807. if (evtimer_add(launch_event, &timeout)<0) {
  1808. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1809. }
  1810. }
  1811. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1812. int
  1813. dns_seems_to_be_broken(void)
  1814. {
  1815. return dns_is_completely_invalid;
  1816. }
  1817. /** Return true iff we think that IPv6 hostname lookup is broken */
  1818. int
  1819. dns_seems_to_be_broken_for_ipv6(void)
  1820. {
  1821. return dns_is_broken_for_ipv6;
  1822. }
  1823. /** Forget what we've previously learned about our DNS servers' correctness. */
  1824. void
  1825. dns_reset_correctness_checks(void)
  1826. {
  1827. strmap_free(dns_wildcard_response_count, tor_free_);
  1828. dns_wildcard_response_count = NULL;
  1829. n_wildcard_requests = 0;
  1830. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1831. if (dns_wildcard_list) {
  1832. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1833. smartlist_clear(dns_wildcard_list);
  1834. }
  1835. if (dns_wildcarded_test_address_list) {
  1836. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1837. tor_free(cp));
  1838. smartlist_clear(dns_wildcarded_test_address_list);
  1839. }
  1840. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1841. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1842. dns_is_broken_for_ipv6 = 0;
  1843. }
  1844. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1845. * returned in response to requests for nonexistent hostnames. */
  1846. static int
  1847. answer_is_wildcarded(const char *ip)
  1848. {
  1849. return dns_wildcard_list && smartlist_contains_string(dns_wildcard_list, ip);
  1850. }
  1851. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1852. static void
  1853. assert_resolve_ok(cached_resolve_t *resolve)
  1854. {
  1855. tor_assert(resolve);
  1856. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1857. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1858. tor_assert(tor_strisnonupper(resolve->address));
  1859. if (resolve->state != CACHE_STATE_PENDING) {
  1860. tor_assert(!resolve->pending_connections);
  1861. }
  1862. if (resolve->state == CACHE_STATE_PENDING ||
  1863. resolve->state == CACHE_STATE_DONE) {
  1864. #if 0
  1865. tor_assert(!resolve->ttl);
  1866. if (resolve->is_reverse)
  1867. tor_assert(!resolve->hostname);
  1868. else
  1869. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1870. #endif /* 0 */
  1871. /*XXXXX ADD MORE */
  1872. }
  1873. }
  1874. /** Return the number of DNS cache entries as an int */
  1875. static int
  1876. dns_cache_entry_count(void)
  1877. {
  1878. return HT_SIZE(&cache_root);
  1879. }
  1880. /** Log memory information about our internal DNS cache at level 'severity'. */
  1881. void
  1882. dump_dns_mem_usage(int severity)
  1883. {
  1884. /* This should never be larger than INT_MAX. */
  1885. int hash_count = dns_cache_entry_count();
  1886. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1887. hash_mem += HT_MEM_USAGE(&cache_root);
  1888. /* Print out the count and estimated size of our &cache_root. It undercounts
  1889. hostnames in cached reverse resolves.
  1890. */
  1891. tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1892. tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1893. (unsigned)hash_mem);
  1894. }
  1895. #ifdef DEBUG_DNS_CACHE
  1896. /** Exit with an assertion if the DNS cache is corrupt. */
  1897. static void
  1898. assert_cache_ok_(void)
  1899. {
  1900. cached_resolve_t **resolve;
  1901. int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
  1902. if (bad_rep) {
  1903. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1904. tor_assert(!bad_rep);
  1905. }
  1906. HT_FOREACH(resolve, cache_map, &cache_root) {
  1907. assert_resolve_ok(*resolve);
  1908. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1909. }
  1910. if (!cached_resolve_pqueue)
  1911. return;
  1912. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1913. compare_cached_resolves_by_expiry_,
  1914. offsetof(cached_resolve_t, minheap_idx));
  1915. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1916. {
  1917. if (res->state == CACHE_STATE_DONE) {
  1918. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1919. tor_assert(!found || found != res);
  1920. } else {
  1921. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1922. tor_assert(found);
  1923. }
  1924. });
  1925. }
  1926. #endif /* defined(DEBUG_DNS_CACHE) */
  1927. cached_resolve_t *
  1928. dns_get_cache_entry(cached_resolve_t *query)
  1929. {
  1930. return HT_FIND(cache_map, &cache_root, query);
  1931. }
  1932. void
  1933. dns_insert_cache_entry(cached_resolve_t *new_entry)
  1934. {
  1935. HT_INSERT(cache_map, &cache_root, new_entry);
  1936. }