dns.c 55 KB

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