dns.c 55 KB

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