dns.c 54 KB

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