dns.c 61 KB

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