dns.c 73 KB

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