dns.c 62 KB

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