dns.c 71 KB

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