dns.c 71 KB

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