dns.c 60 KB

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