dns.c 54 KB

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