dns.c 71 KB

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