dns.c 71 KB

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