dns.c 62 KB

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