dns.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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 "../common/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() do {} while (0)
  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 forthe 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 arond, 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 || resolve->state != CACHE_STATE_PENDING) {
  744. log_notice(LD_BUG,"Address %s is not pending. Dropping.",
  745. escaped_safe_str(address));
  746. return;
  747. }
  748. if (!resolve->pending_connections) {
  749. /* XXX this should never trigger, but sometimes it does */
  750. /* XXXX020 is the above still true? -NM */
  751. log_warn(LD_BUG,
  752. "Address %s is pending but has no pending connections!",
  753. escaped_safe_str(address));
  754. tor_fragile_assert();
  755. return;
  756. }
  757. tor_assert(resolve->pending_connections);
  758. /* mark all pending connections to fail */
  759. log_debug(LD_EXIT,
  760. "Failing all connections waiting on DNS resolve of %s",
  761. escaped_safe_str(address));
  762. while (resolve->pending_connections) {
  763. pend = resolve->pending_connections;
  764. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  765. pendconn = pend->conn;
  766. assert_connection_ok(TO_CONN(pendconn), 0);
  767. tor_assert(pendconn->_base.s == -1);
  768. if (!pendconn->_base.marked_for_close) {
  769. /* XXXX020 RESOURCELIMIT? Not RESOLVEFAILED??? */
  770. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT);
  771. }
  772. circ = circuit_get_by_edge_conn(pendconn);
  773. if (circ)
  774. circuit_detach_stream(circ, pendconn);
  775. if (!pendconn->_base.marked_for_close)
  776. connection_free(TO_CONN(pendconn));
  777. resolve->pending_connections = pend->next;
  778. tor_free(pend);
  779. }
  780. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  781. if (tmp != resolve) {
  782. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  783. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  784. resolve->address, (void*)resolve,
  785. tmp ? tmp->address : "NULL", (void*)tmp);
  786. }
  787. tor_assert(tmp == resolve);
  788. resolve->state = CACHE_STATE_DONE;
  789. }
  790. /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
  791. * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
  792. * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
  793. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  794. **/
  795. static void
  796. add_answer_to_cache(const char *address, int is_reverse, uint32_t addr,
  797. const char *hostname, char outcome, uint32_t ttl)
  798. {
  799. cached_resolve_t *resolve;
  800. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  801. return;
  802. //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
  803. // address, is_reverse?"(reverse)":"", (unsigned long)addr,
  804. // hostname?hostname:"NULL",(int)outcome);
  805. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  806. resolve->magic = CACHED_RESOLVE_MAGIC;
  807. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  808. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  809. strlcpy(resolve->address, address, sizeof(resolve->address));
  810. resolve->is_reverse = is_reverse;
  811. if (is_reverse) {
  812. if (outcome == DNS_RESOLVE_SUCCEEDED) {
  813. tor_assert(hostname);
  814. resolve->result.hostname = tor_strdup(hostname);
  815. } else {
  816. tor_assert(! hostname);
  817. resolve->result.hostname = NULL;
  818. }
  819. } else {
  820. tor_assert(!hostname);
  821. resolve->result.addr = addr;
  822. }
  823. resolve->ttl = ttl;
  824. assert_resolve_ok(resolve);
  825. HT_INSERT(cache_map, &cache_root, resolve);
  826. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  827. }
  828. /** Return true iff <b>address</b> is one of the addresses we use to verify
  829. * that well-known sites aren't being hijacked by our DNS servers. */
  830. static INLINE int
  831. is_test_address(const char *address)
  832. {
  833. or_options_t *options = get_options();
  834. return options->ServerDNSTestAddresses &&
  835. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  836. }
  837. /** Called on the OR side when a DNS worker or the eventdns library tells us
  838. * the outcome of a DNS resolve: tell all pending connections about the result
  839. * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
  840. * string containing the address to look up; <b>addr</b> is an IPv4 address in
  841. * host order; <b>outcome</b> is one of
  842. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  843. */
  844. static void
  845. dns_found_answer(const char *address, int is_reverse, uint32_t addr,
  846. const char *hostname, char outcome, uint32_t ttl)
  847. {
  848. pending_connection_t *pend;
  849. cached_resolve_t search;
  850. cached_resolve_t *resolve, *removed;
  851. edge_connection_t *pendconn;
  852. circuit_t *circ;
  853. assert_cache_ok();
  854. strlcpy(search.address, address, sizeof(search.address));
  855. resolve = HT_FIND(cache_map, &cache_root, &search);
  856. if (!resolve) {
  857. int is_test_addr = is_test_address(address);
  858. if (!is_test_addr)
  859. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  860. escaped_safe_str(address));
  861. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  862. return;
  863. }
  864. assert_resolve_ok(resolve);
  865. if (resolve->state != CACHE_STATE_PENDING) {
  866. /* XXXX020 Maybe update addr? or check addr for consistency? Or let
  867. * VALID replace FAILED? */
  868. int is_test_addr = is_test_address(address);
  869. if (!is_test_addr)
  870. log_notice(LD_EXIT,
  871. "Resolved %s which was already resolved; ignoring",
  872. escaped_safe_str(address));
  873. tor_assert(resolve->pending_connections == NULL);
  874. return;
  875. }
  876. /* Removed this assertion: in fact, we'll sometimes get a double answer
  877. * to the same question. This can happen when we ask one worker to resolve
  878. * X.Y.Z., then we cancel the request, and then we ask another worker to
  879. * resolve X.Y.Z. */
  880. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  881. while (resolve->pending_connections) {
  882. pend = resolve->pending_connections;
  883. pendconn = pend->conn; /* don't pass complex things to the
  884. connection_mark_for_close macro */
  885. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  886. pendconn->_base.addr = addr;
  887. pendconn->address_ttl = ttl;
  888. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  889. /* prevent double-remove. */
  890. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  891. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  892. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  893. /* This detach must happen after we send the end cell. */
  894. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  895. } else {
  896. send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
  897. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  898. /* This detach must happen after we send the resolved cell. */
  899. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  900. }
  901. connection_free(TO_CONN(pendconn));
  902. } else {
  903. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  904. tor_assert(!is_reverse);
  905. /* prevent double-remove. */
  906. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  907. circ = circuit_get_by_edge_conn(pend->conn);
  908. tor_assert(circ);
  909. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  910. /* unlink pend->conn from resolving_streams, */
  911. circuit_detach_stream(circ, pend->conn);
  912. /* and link it to n_streams */
  913. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  914. pend->conn->on_circuit = circ;
  915. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  916. connection_exit_connect(pend->conn);
  917. } else {
  918. /* prevent double-remove. This isn't really an accurate state,
  919. * but it does the right thing. */
  920. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  921. if (is_reverse)
  922. send_resolved_hostname_cell(pendconn, hostname);
  923. else
  924. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  925. circ = circuit_get_by_edge_conn(pendconn);
  926. tor_assert(circ);
  927. circuit_detach_stream(circ, pendconn);
  928. connection_free(TO_CONN(pendconn));
  929. }
  930. }
  931. resolve->pending_connections = pend->next;
  932. tor_free(pend);
  933. }
  934. resolve->state = CACHE_STATE_DONE;
  935. removed = HT_REMOVE(cache_map, &cache_root, &search);
  936. if (removed != resolve) {
  937. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  938. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  939. resolve->address, (void*)resolve,
  940. removed ? removed->address : "NULL", (void*)removed);
  941. }
  942. assert_resolve_ok(resolve);
  943. assert_cache_ok();
  944. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  945. assert_cache_ok();
  946. }
  947. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  948. * a transient failure. */
  949. static int
  950. evdns_err_is_transient(int err)
  951. {
  952. switch (err)
  953. {
  954. case DNS_ERR_SERVERFAILED:
  955. case DNS_ERR_TRUNCATED:
  956. case DNS_ERR_TIMEOUT:
  957. return 1;
  958. default:
  959. return 0;
  960. }
  961. }
  962. /** Configure eventdns nameservers if force is true, or if the configuration
  963. * has changed since the last time we called this function. On Unix, this
  964. * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
  965. * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
  966. * Return 0 on success or -1 on failure. */
  967. static int
  968. configure_nameservers(int force)
  969. {
  970. or_options_t *options;
  971. const char *conf_fname;
  972. struct stat st;
  973. int r;
  974. options = get_options();
  975. conf_fname = options->ServerDNSResolvConfFile;
  976. #ifndef MS_WINDOWS
  977. if (!conf_fname)
  978. conf_fname = "/etc/resolv.conf";
  979. #endif
  980. evdns_set_log_fn(evdns_log_cb);
  981. if (conf_fname) {
  982. if (stat(conf_fname, &st)) {
  983. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  984. conf_fname, strerror(errno));
  985. return -1;
  986. }
  987. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  988. && st.st_mtime == resolv_conf_mtime) {
  989. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  990. return 0;
  991. }
  992. if (nameservers_configured) {
  993. evdns_search_clear();
  994. evdns_clear_nameservers_and_suspend();
  995. }
  996. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  997. if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
  998. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  999. conf_fname, conf_fname, r);
  1000. return -1;
  1001. }
  1002. if (evdns_count_nameservers() == 0) {
  1003. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1004. return -1;
  1005. }
  1006. tor_free(resolv_conf_fname);
  1007. resolv_conf_fname = tor_strdup(conf_fname);
  1008. resolv_conf_mtime = st.st_mtime;
  1009. if (nameservers_configured)
  1010. evdns_resume();
  1011. }
  1012. #ifdef MS_WINDOWS
  1013. else {
  1014. if (nameservers_configured) {
  1015. evdns_search_clear();
  1016. evdns_clear_nameservers_and_suspend();
  1017. }
  1018. if (evdns_config_windows_nameservers()) {
  1019. log_warn(LD_EXIT,"Could not config nameservers.");
  1020. return -1;
  1021. }
  1022. if (evdns_count_nameservers() == 0) {
  1023. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1024. "your Windows configuration. Perhaps you should list a "
  1025. "ServerDNSResolvConfFile file in your torrc?");
  1026. return -1;
  1027. }
  1028. if (nameservers_configured)
  1029. evdns_resume();
  1030. tor_free(resolv_conf_fname);
  1031. resolv_conf_mtime = 0;
  1032. }
  1033. #endif
  1034. if (evdns_count_nameservers() == 1) {
  1035. evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
  1036. evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
  1037. } else {
  1038. evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
  1039. evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
  1040. }
  1041. dns_servers_relaunch_checks();
  1042. nameservers_configured = 1;
  1043. return 0;
  1044. }
  1045. /** For eventdns: Called when we get an answer for a request we launched.
  1046. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1047. */
  1048. static void
  1049. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1050. void *arg)
  1051. {
  1052. char *string_address = arg;
  1053. int is_reverse = 0;
  1054. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1055. uint32_t addr = 0;
  1056. const char *hostname = NULL;
  1057. int was_wildcarded = 0;
  1058. if (result == DNS_ERR_NONE) {
  1059. if (type == DNS_IPv4_A && count) {
  1060. char answer_buf[INET_NTOA_BUF_LEN+1];
  1061. struct in_addr in;
  1062. char *escaped_address;
  1063. uint32_t *addrs = addresses;
  1064. in.s_addr = addrs[0];
  1065. addr = ntohl(addrs[0]);
  1066. status = DNS_RESOLVE_SUCCEEDED;
  1067. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1068. escaped_address = esc_for_log(string_address);
  1069. if (answer_is_wildcarded(answer_buf)) {
  1070. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1071. "address %s; treating as a failure.",
  1072. safe_str(escaped_address),
  1073. escaped_safe_str(answer_buf));
  1074. was_wildcarded = 1;
  1075. addr = 0;
  1076. status = DNS_RESOLVE_FAILED_PERMANENT;
  1077. } else {
  1078. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1079. safe_str(escaped_address),
  1080. escaped_safe_str(answer_buf));
  1081. }
  1082. tor_free(escaped_address);
  1083. } else if (type == DNS_PTR && count) {
  1084. char *escaped_address;
  1085. is_reverse = 1;
  1086. hostname = ((char**)addresses)[0];
  1087. status = DNS_RESOLVE_SUCCEEDED;
  1088. escaped_address = esc_for_log(string_address);
  1089. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1090. safe_str(escaped_address),
  1091. escaped_safe_str(hostname));
  1092. tor_free(escaped_address);
  1093. } else if (count) {
  1094. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1095. escaped_safe_str(string_address));
  1096. } else {
  1097. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1098. escaped_safe_str(string_address));
  1099. }
  1100. } else {
  1101. if (evdns_err_is_transient(result))
  1102. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1103. }
  1104. if (was_wildcarded) {
  1105. if (is_test_address(string_address)) {
  1106. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1107. * server must really hate us. */
  1108. add_wildcarded_test_address(string_address);
  1109. }
  1110. }
  1111. if (result != DNS_ERR_SHUTDOWN)
  1112. dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
  1113. tor_free(string_address);
  1114. }
  1115. /** For eventdns: start resolving as necessary to find the target for
  1116. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1117. * 0 on "resolve launched." */
  1118. static int
  1119. launch_resolve(edge_connection_t *exitconn)
  1120. {
  1121. char *addr = tor_strdup(exitconn->_base.address);
  1122. struct in_addr in;
  1123. int r;
  1124. int options = get_options()->ServerDNSSearchDomains ? 0
  1125. : DNS_QUERY_NO_SEARCH;
  1126. /* What? Nameservers not configured? Sounds like a bug. */
  1127. if (!nameservers_configured) {
  1128. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1129. "launched. Configuring.");
  1130. if (configure_nameservers(1) < 0)
  1131. return -1;
  1132. }
  1133. r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
  1134. if (r == 0) {
  1135. log_info(LD_EXIT, "Launching eventdns request for %s",
  1136. escaped_safe_str(exitconn->_base.address));
  1137. r = evdns_resolve_ipv4(exitconn->_base.address, options,
  1138. evdns_callback, addr);
  1139. } else if (r == 1) {
  1140. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1141. escaped_safe_str(exitconn->_base.address));
  1142. r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
  1143. evdns_callback, addr);
  1144. } else if (r == -1) {
  1145. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1146. }
  1147. if (r) {
  1148. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1149. escaped_safe_str(addr), r);
  1150. r = evdns_err_is_transient(r) ? -2 : -1;
  1151. tor_free(addr); /* There is no evdns request in progress; stop
  1152. * addr from getting leaked. */
  1153. }
  1154. return r;
  1155. }
  1156. /** How many requests for bogus addresses have we launched so far? */
  1157. static int n_wildcard_requests = 0;
  1158. /** Map from dotted-quad IP address in response to an int holding how many
  1159. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1160. * would be easier to use definitely-invalid addresses (as specified by
  1161. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1162. static strmap_t *dns_wildcard_response_count = NULL;
  1163. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1164. * nameserver wants to return in response to requests for nonexistent domains.
  1165. */
  1166. static smartlist_t *dns_wildcard_list = NULL;
  1167. /** True iff we've logged about a single address getting wildcarded.
  1168. * Subsequent warnings will be less severe. */
  1169. static int dns_wildcard_one_notice_given = 0;
  1170. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1171. */
  1172. static int dns_wildcard_notice_given = 0;
  1173. /** List of supposedly good addresses that are getting wildcarded to the
  1174. * same addresses as nonexistent addresses. */
  1175. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1176. /** True iff we've warned about a test address getting wildcarded */
  1177. static int dns_wildcarded_test_address_notice_given = 0;
  1178. /** True iff all addresses seem to be getting wildcarded. */
  1179. static int dns_is_completely_invalid = 0;
  1180. /** Called when we see <b>id</b> (a dotted quad) in response to a request for
  1181. * a hopefully bogus address. */
  1182. static void
  1183. wildcard_increment_answer(const char *id)
  1184. {
  1185. int *ip;
  1186. if (!dns_wildcard_response_count)
  1187. dns_wildcard_response_count = strmap_new();
  1188. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1189. if (!ip) {
  1190. ip = tor_malloc_zero(sizeof(int));
  1191. strmap_set(dns_wildcard_response_count, id, ip);
  1192. }
  1193. ++*ip;
  1194. if (*ip > 5 && n_wildcard_requests > 10) {
  1195. if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
  1196. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1197. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1198. "Your DNS provider has given \"%s\" as an answer for %d different "
  1199. "invalid addresses. Apparently they are hijacking DNS failures. "
  1200. "I'll try to correct for this by treating future occurrences of "
  1201. "\"%s\" as 'not found'.", id, *ip, id);
  1202. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1203. }
  1204. if (!dns_wildcard_notice_given)
  1205. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1206. dns_wildcard_notice_given = 1;
  1207. }
  1208. }
  1209. /** Note that a single test address (one believed to be good) seems to be
  1210. * getting redirected to the same IP as failures are. */
  1211. static void
  1212. add_wildcarded_test_address(const char *address)
  1213. {
  1214. int n, n_test_addrs;
  1215. if (!dns_wildcarded_test_address_list)
  1216. dns_wildcarded_test_address_list = smartlist_create();
  1217. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1218. return;
  1219. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1220. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1221. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1222. n = smartlist_len(dns_wildcarded_test_address_list);
  1223. if (n > n_test_addrs/2) {
  1224. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1225. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1226. "address. It has done this with %d test addresses so far. I'm "
  1227. "going to stop being an exit node for now, since our DNS seems so "
  1228. "broken.", address, n);
  1229. if (!dns_is_completely_invalid) {
  1230. dns_is_completely_invalid = 1;
  1231. mark_my_descriptor_dirty();
  1232. }
  1233. if (!dns_wildcarded_test_address_notice_given)
  1234. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1235. dns_wildcarded_test_address_notice_given = 1;
  1236. }
  1237. }
  1238. /** Callback function when we get an answer (possibly failing) for a request
  1239. * for a (hopefully) nonexistent domain. */
  1240. static void
  1241. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1242. void *addresses, void *arg)
  1243. {
  1244. (void)ttl;
  1245. ++n_wildcard_requests;
  1246. if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
  1247. uint32_t *addrs = addresses;
  1248. int i;
  1249. char *string_address = arg;
  1250. for (i = 0; i < count; ++i) {
  1251. char answer_buf[INET_NTOA_BUF_LEN+1];
  1252. struct in_addr in;
  1253. in.s_addr = addrs[i];
  1254. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1255. wildcard_increment_answer(answer_buf);
  1256. }
  1257. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1258. "Your DNS provider gave an answer for \"%s\", which "
  1259. "is not supposed to exist. Apparently they are hijacking "
  1260. "DNS failures. Trying to correct for this. We've noticed %d possibly "
  1261. "bad addresses so far.",
  1262. string_address, strmap_size(dns_wildcard_response_count));
  1263. dns_wildcard_one_notice_given = 1;
  1264. }
  1265. tor_free(arg);
  1266. }
  1267. /** Launch a single request for a nonexistent hostname consisting of between
  1268. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1269. * <b>suffix</b> */
  1270. static void
  1271. launch_wildcard_check(int min_len, int max_len, const char *suffix)
  1272. {
  1273. char random_bytes[20], name[64], *addr;
  1274. size_t len;
  1275. int r;
  1276. len = min_len + crypto_rand_int(max_len-min_len+1);
  1277. if (crypto_rand(random_bytes, sizeof(random_bytes)) < 0)
  1278. return;
  1279. base32_encode(name, sizeof(name), random_bytes, sizeof(random_bytes));
  1280. name[len] = '\0';
  1281. strlcat(name, suffix, sizeof(name));
  1282. addr = tor_strdup(name);
  1283. r = evdns_resolve_ipv4(name, DNS_QUERY_NO_SEARCH,
  1284. evdns_wildcard_check_callback, addr);
  1285. if (r)
  1286. tor_free(addr);
  1287. }
  1288. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1289. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1290. static void
  1291. launch_test_addresses(int fd, short event, void *args)
  1292. {
  1293. or_options_t *options = get_options();
  1294. (void)fd;
  1295. (void)event;
  1296. (void)args;
  1297. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1298. "hijack *everything*.");
  1299. /* This situation is worse than the failure-hijacking situation. When this
  1300. * happens, we're no good for DNS requests at all, and we shouldn't really
  1301. * be an exit server.*/
  1302. if (!options->ServerDNSTestAddresses)
  1303. return;
  1304. SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
  1305. {
  1306. evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
  1307. tor_strdup(address));
  1308. });
  1309. }
  1310. #define N_WILDCARD_CHECKS 2
  1311. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1312. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1313. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1314. * buy these lovely encyclopedias" page. */
  1315. static void
  1316. dns_launch_wildcard_checks(void)
  1317. {
  1318. int i;
  1319. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1320. "to hijack DNS failures.");
  1321. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1322. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
  1323. * to 'comply' with rfc2606, refrain from giving A records for these.
  1324. * This is the standards-compliance equivalent of making sure that your
  1325. * crackhouse's elevator inspection certificate is up to date.
  1326. */
  1327. launch_wildcard_check(2, 16, ".invalid");
  1328. launch_wildcard_check(2, 16, ".test");
  1329. /* These will break specs if there are ever any number of
  1330. * 8+-character top-level domains. */
  1331. launch_wildcard_check(8, 16, "");
  1332. /* Try some random .com/org/net domains. This will work fine so long as
  1333. * not too many resolve to the same place. */
  1334. launch_wildcard_check(8, 16, ".com");
  1335. launch_wildcard_check(8, 16, ".org");
  1336. launch_wildcard_check(8, 16, ".net");
  1337. }
  1338. }
  1339. /** If appropriate, start testing whether our DNS servers tend to lie to
  1340. * us. */
  1341. void
  1342. dns_launch_correctness_checks(void)
  1343. {
  1344. static struct event launch_event;
  1345. struct timeval timeout;
  1346. if (!get_options()->ServerDNSDetectHijacking)
  1347. return;
  1348. dns_launch_wildcard_checks();
  1349. /* Wait a while before launching requests for test addresses, so we can
  1350. * get the results from checking for wildcarding. */
  1351. evtimer_set(&launch_event, launch_test_addresses, NULL);
  1352. timeout.tv_sec = 30;
  1353. timeout.tv_usec = 0;
  1354. evtimer_add(&launch_event, &timeout);
  1355. }
  1356. /** Return true iff our DNS servers lie to us too much to be trustd. */
  1357. int
  1358. dns_seems_to_be_broken(void)
  1359. {
  1360. return dns_is_completely_invalid;
  1361. }
  1362. /** Forget what we've previously learned about our DNS servers' correctness. */
  1363. void
  1364. dns_reset_correctness_checks(void)
  1365. {
  1366. if (dns_wildcard_response_count) {
  1367. strmap_free(dns_wildcard_response_count, _tor_free);
  1368. dns_wildcard_response_count = NULL;
  1369. }
  1370. n_wildcard_requests = 0;
  1371. if (dns_wildcard_list) {
  1372. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1373. smartlist_clear(dns_wildcard_list);
  1374. }
  1375. if (dns_wildcarded_test_address_list) {
  1376. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1377. tor_free(cp));
  1378. smartlist_clear(dns_wildcarded_test_address_list);
  1379. }
  1380. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1381. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
  1382. }
  1383. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1384. * returned in response to requests for nonexistent hostnames. */
  1385. static int
  1386. answer_is_wildcarded(const char *ip)
  1387. {
  1388. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1389. }
  1390. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1391. static void
  1392. assert_resolve_ok(cached_resolve_t *resolve)
  1393. {
  1394. tor_assert(resolve);
  1395. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1396. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1397. tor_assert(tor_strisnonupper(resolve->address));
  1398. if (resolve->state != CACHE_STATE_PENDING) {
  1399. tor_assert(!resolve->pending_connections);
  1400. }
  1401. if (resolve->state == CACHE_STATE_PENDING ||
  1402. resolve->state == CACHE_STATE_DONE) {
  1403. tor_assert(!resolve->ttl);
  1404. if (resolve->is_reverse)
  1405. tor_assert(!resolve->result.hostname);
  1406. else
  1407. tor_assert(!resolve->result.addr);
  1408. }
  1409. }
  1410. #ifdef DEBUG_DNS_CACHE
  1411. /** Exit with an assertion if the DNS cache is corrupt. */
  1412. static void
  1413. _assert_cache_ok(void)
  1414. {
  1415. cached_resolve_t **resolve;
  1416. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1417. if (bad_rep) {
  1418. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1419. tor_assert(!bad_rep);
  1420. }
  1421. HT_FOREACH(resolve, cache_map, &cache_root) {
  1422. assert_resolve_ok(*resolve);
  1423. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1424. }
  1425. if (!cached_resolve_pqueue)
  1426. return;
  1427. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1428. _compare_cached_resolves_by_expiry);
  1429. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1430. {
  1431. if (res->state == CACHE_STATE_DONE) {
  1432. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1433. tor_assert(!found || found != res);
  1434. } else {
  1435. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1436. tor_assert(found);
  1437. }
  1438. });
  1439. }
  1440. #endif