dns.c 55 KB

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