dns.c 73 KB

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