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