dns.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file dns.c
  7. * \brief Implements a local cache for DNS results for Tor servers.
  8. * This is implemented as a wrapper around Adam Langley's eventdns.c code.
  9. * (We can't just use gethostbyname() and friends because we really need to
  10. * be nonblocking.)
  11. *
  12. * There are three main cases when a Tor relay uses dns.c to launch a DNS
  13. * request:
  14. * <ol>
  15. * <li>To check whether the DNS server is working more or less correctly.
  16. * This happens via dns_launch_correctness_checks(). The answer is
  17. * reported in the return value from later calls to
  18. * dns_seems_to_be_broken().
  19. * <li>When a client has asked the relay, in a RELAY_BEGIN cell, to connect
  20. * to a given server by hostname. This happens via dns_resolve().
  21. * <li>When a client has asked the relay, in a RELAY_RESOLVE cell, to look
  22. * up a given server's IP address(es) by hostname. This also happens via
  23. * dns_resolve().
  24. * </ol>
  25. *
  26. * Each of these gets handled a little differently.
  27. *
  28. * To check for correctness, we look up some hostname we expect to exist and
  29. * have real entries, some hostnames which we expect to definitely not exist,
  30. * and some hostnames that we expect to probably not exist. If too many of
  31. * the hostnames that shouldn't exist do exist, that's a DNS hijacking
  32. * attempt. If too many of the hostnames that should exist have the same
  33. * addresses as the ones that shouldn't exist, that's a very bad DNS hijacking
  34. * attempt, or a very naughty captive portal. And if the hostnames that
  35. * should exist simply don't exist, we probably have a broken nameserver.
  36. *
  37. * To handle client requests, we first check our cache for answers. If there
  38. * isn't something up-to-date, we've got to launch A or AAAA requests as
  39. * appropriate. How we handle responses to those in particular is a bit
  40. * complex; see dns_lookup() and set_exitconn_info_from_resolve().
  41. *
  42. * When a lookup is finally complete, the inform_pending_connections()
  43. * function will tell all of the streams that have been waiting for the
  44. * resolve, by calling connection_exit_connect() if the client sent a
  45. * RELAY_BEGIN cell, and by calling send_resolved_cell() or
  46. * send_hostname_cell() if the client sent a RELAY_RESOLVE cell.
  47. **/
  48. #define DNS_PRIVATE
  49. #include "or/or.h"
  50. #include "or/circuitlist.h"
  51. #include "or/circuituse.h"
  52. #include "or/config.h"
  53. #include "or/connection.h"
  54. #include "or/connection_edge.h"
  55. #include "or/control.h"
  56. #include "lib/crypt_ops/crypto_rand.h"
  57. #include "or/dns.h"
  58. #include "or/main.h"
  59. #include "or/policies.h"
  60. #include "or/relay.h"
  61. #include "or/router.h"
  62. #include "ht.h"
  63. #include "lib/sandbox/sandbox.h"
  64. #include "or/edge_connection_st.h"
  65. #include "or/or_circuit_st.h"
  66. #include <event2/event.h>
  67. #include <event2/dns.h>
  68. /** How long will we wait for an answer from the resolver before we decide
  69. * that the resolver is wedged? */
  70. #define RESOLVE_MAX_TIMEOUT 300
  71. /** Our evdns_base; this structure handles all our name lookups. */
  72. static struct evdns_base *the_evdns_base = NULL;
  73. /** Have we currently configured nameservers with eventdns? */
  74. static int nameservers_configured = 0;
  75. /** Did our most recent attempt to configure nameservers with eventdns fail? */
  76. static int nameserver_config_failed = 0;
  77. /** What was the resolv_conf fname we last used when configuring the
  78. * nameservers? Used to check whether we need to reconfigure. */
  79. static char *resolv_conf_fname = NULL;
  80. /** What was the mtime on the resolv.conf file we last used when configuring
  81. * the nameservers? Used to check whether we need to reconfigure. */
  82. static time_t resolv_conf_mtime = 0;
  83. static void purge_expired_resolves(time_t now);
  84. static void dns_found_answer(const char *address, uint8_t query_type,
  85. int dns_answer,
  86. const tor_addr_t *addr,
  87. const char *hostname,
  88. uint32_t ttl);
  89. static void add_wildcarded_test_address(const char *address);
  90. static int configure_nameservers(int force);
  91. static int answer_is_wildcarded(const char *ip);
  92. static int evdns_err_is_transient(int err);
  93. static void inform_pending_connections(cached_resolve_t *resolve);
  94. static void make_pending_resolve_cached(cached_resolve_t *cached);
  95. #ifdef DEBUG_DNS_CACHE
  96. static void assert_cache_ok_(void);
  97. #define assert_cache_ok() assert_cache_ok_()
  98. #else
  99. #define assert_cache_ok() STMT_NIL
  100. #endif /* defined(DEBUG_DNS_CACHE) */
  101. static void assert_resolve_ok(cached_resolve_t *resolve);
  102. /** Hash table of cached_resolve objects. */
  103. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  104. /** Global: how many IPv6 requests have we made in all? */
  105. static uint64_t n_ipv6_requests_made = 0;
  106. /** Global: how many IPv6 requests have timed out? */
  107. static uint64_t n_ipv6_timeouts = 0;
  108. /** Global: Do we think that IPv6 DNS is broken? */
  109. static int dns_is_broken_for_ipv6 = 0;
  110. /** Function to compare hashed resolves on their addresses; used to
  111. * implement hash tables. */
  112. static inline int
  113. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  114. {
  115. /* make this smarter one day? */
  116. assert_resolve_ok(a); // Not b; b may be just a search.
  117. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  118. }
  119. /** Hash function for cached_resolve objects */
  120. static inline unsigned int
  121. cached_resolve_hash(cached_resolve_t *a)
  122. {
  123. return (unsigned) siphash24g((const uint8_t*)a->address, strlen(a->address));
  124. }
  125. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  126. cached_resolves_eq)
  127. HT_GENERATE2(cache_map, cached_resolve_t, node, cached_resolve_hash,
  128. cached_resolves_eq, 0.6, tor_reallocarray_, tor_free_)
  129. /** Initialize the DNS cache. */
  130. static void
  131. init_cache_map(void)
  132. {
  133. HT_INIT(cache_map, &cache_root);
  134. }
  135. /** Helper: called by eventdns when eventdns wants to log something. */
  136. static void
  137. evdns_log_cb(int warn, const char *msg)
  138. {
  139. const char *cp;
  140. static int all_down = 0;
  141. int severity = warn ? LOG_WARN : LOG_INFO;
  142. if (!strcmpstart(msg, "Resolve requested for") &&
  143. get_options()->SafeLogging) {
  144. log_info(LD_EXIT, "eventdns: Resolve requested.");
  145. return;
  146. } else if (!strcmpstart(msg, "Search: ")) {
  147. return;
  148. }
  149. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  150. char *ns = tor_strndup(msg+11, cp-(msg+11));
  151. const char *colon = strchr(cp, ':');
  152. tor_assert(colon);
  153. const char *err = colon+2;
  154. /* Don't warn about a single failed nameserver; we'll warn with 'all
  155. * nameservers have failed' if we're completely out of nameservers;
  156. * otherwise, the situation is tolerable. */
  157. severity = LOG_INFO;
  158. control_event_server_status(LOG_NOTICE,
  159. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  160. ns, escaped(err));
  161. tor_free(ns);
  162. } else if (!strcmpstart(msg, "Nameserver ") &&
  163. (cp=strstr(msg, " is back up"))) {
  164. char *ns = tor_strndup(msg+11, cp-(msg+11));
  165. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  166. all_down = 0;
  167. control_event_server_status(LOG_NOTICE,
  168. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  169. tor_free(ns);
  170. } else if (!strcmp(msg, "All nameservers have failed")) {
  171. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  172. all_down = 1;
  173. } else if (!strcmpstart(msg, "Address mismatch on received DNS")) {
  174. static ratelim_t mismatch_limit = RATELIM_INIT(3600);
  175. const char *src = strstr(msg, " Apparent source");
  176. if (!src || get_options()->SafeLogging) {
  177. src = "";
  178. }
  179. log_fn_ratelim(&mismatch_limit, severity, LD_EXIT,
  180. "eventdns: Received a DNS packet from "
  181. "an IP address to which we did not send a request. This "
  182. "could be a DNS spoofing attempt, or some kind of "
  183. "misconfiguration.%s", src);
  184. return;
  185. }
  186. tor_log(severity, LD_EXIT, "eventdns: %s", msg);
  187. }
  188. /** Helper: passed to eventdns.c as a callback so it can generate random
  189. * numbers for transaction IDs and 0x20-hack coding. */
  190. static void
  191. dns_randfn_(char *b, size_t n)
  192. {
  193. crypto_rand(b,n);
  194. }
  195. /** Initialize the DNS subsystem; called by the OR process. */
  196. int
  197. dns_init(void)
  198. {
  199. init_cache_map();
  200. evdns_set_random_bytes_fn(dns_randfn_);
  201. if (server_mode(get_options())) {
  202. int r = configure_nameservers(1);
  203. return r;
  204. }
  205. return 0;
  206. }
  207. /** Called when DNS-related options change (or may have changed). Returns -1
  208. * on failure, 0 on success. */
  209. int
  210. dns_reset(void)
  211. {
  212. const or_options_t *options = get_options();
  213. if (! server_mode(options)) {
  214. if (!the_evdns_base) {
  215. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  216. log_err(LD_BUG, "Couldn't create an evdns_base");
  217. return -1;
  218. }
  219. }
  220. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  221. evdns_base_search_clear(the_evdns_base);
  222. nameservers_configured = 0;
  223. tor_free(resolv_conf_fname);
  224. resolv_conf_mtime = 0;
  225. } else {
  226. if (configure_nameservers(0) < 0) {
  227. return -1;
  228. }
  229. }
  230. return 0;
  231. }
  232. /** Return true iff the most recent attempt to initialize the DNS subsystem
  233. * failed. */
  234. int
  235. has_dns_init_failed(void)
  236. {
  237. return nameserver_config_failed;
  238. }
  239. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  240. * OP that asked us to resolve it, and how long to cache that record
  241. * ourselves. */
  242. uint32_t
  243. dns_clip_ttl(uint32_t ttl)
  244. {
  245. /* This logic is a defense against "DefectTor" DNS-based traffic
  246. * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
  247. * We only give two values: a "low" value and a "high" value.
  248. */
  249. if (ttl < MIN_DNS_TTL_AT_EXIT)
  250. return MIN_DNS_TTL_AT_EXIT;
  251. else
  252. return MAX_DNS_TTL_AT_EXIT;
  253. }
  254. /** Helper: free storage held by an entry in the DNS cache. */
  255. static void
  256. free_cached_resolve_(cached_resolve_t *r)
  257. {
  258. if (!r)
  259. return;
  260. while (r->pending_connections) {
  261. pending_connection_t *victim = r->pending_connections;
  262. r->pending_connections = victim->next;
  263. tor_free(victim);
  264. }
  265. if (r->res_status_hostname == RES_STATUS_DONE_OK)
  266. tor_free(r->result_ptr.hostname);
  267. r->magic = 0xFF00FF00;
  268. tor_free(r);
  269. }
  270. /** Compare two cached_resolve_t pointers by expiry time, and return
  271. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  272. * the priority queue implementation. */
  273. static int
  274. compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
  275. {
  276. const cached_resolve_t *a = _a, *b = _b;
  277. if (a->expire < b->expire)
  278. return -1;
  279. else if (a->expire == b->expire)
  280. return 0;
  281. else
  282. return 1;
  283. }
  284. /** Priority queue of cached_resolve_t objects to let us know when they
  285. * will expire. */
  286. static smartlist_t *cached_resolve_pqueue = NULL;
  287. static void
  288. cached_resolve_add_answer(cached_resolve_t *resolve,
  289. int query_type,
  290. int dns_result,
  291. const tor_addr_t *answer_addr,
  292. const char *answer_hostname,
  293. uint32_t ttl)
  294. {
  295. if (query_type == DNS_PTR) {
  296. if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
  297. return;
  298. if (dns_result == DNS_ERR_NONE && answer_hostname) {
  299. resolve->result_ptr.hostname = tor_strdup(answer_hostname);
  300. resolve->res_status_hostname = RES_STATUS_DONE_OK;
  301. } else {
  302. resolve->result_ptr.err_hostname = dns_result;
  303. resolve->res_status_hostname = RES_STATUS_DONE_ERR;
  304. }
  305. resolve->ttl_hostname = ttl;
  306. } else if (query_type == DNS_IPv4_A) {
  307. if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
  308. return;
  309. if (dns_result == DNS_ERR_NONE && answer_addr &&
  310. tor_addr_family(answer_addr) == AF_INET) {
  311. resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
  312. resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
  313. } else {
  314. resolve->result_ipv4.err_ipv4 = dns_result;
  315. resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
  316. }
  317. resolve->ttl_ipv4 = ttl;
  318. } else if (query_type == DNS_IPv6_AAAA) {
  319. if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
  320. return;
  321. if (dns_result == DNS_ERR_NONE && answer_addr &&
  322. tor_addr_family(answer_addr) == AF_INET6) {
  323. memcpy(&resolve->result_ipv6.addr_ipv6,
  324. tor_addr_to_in6(answer_addr),
  325. sizeof(struct in6_addr));
  326. resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
  327. } else {
  328. resolve->result_ipv6.err_ipv6 = dns_result;
  329. resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
  330. }
  331. resolve->ttl_ipv6 = ttl;
  332. }
  333. }
  334. /** Return true iff there are no in-flight requests for <b>resolve</b>. */
  335. static int
  336. cached_resolve_have_all_answers(const cached_resolve_t *resolve)
  337. {
  338. return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
  339. resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
  340. resolve->res_status_hostname != RES_STATUS_INFLIGHT);
  341. }
  342. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  343. * priority queue */
  344. static void
  345. set_expiry(cached_resolve_t *resolve, time_t expires)
  346. {
  347. tor_assert(resolve && resolve->expire == 0);
  348. if (!cached_resolve_pqueue)
  349. cached_resolve_pqueue = smartlist_new();
  350. resolve->expire = expires;
  351. smartlist_pqueue_add(cached_resolve_pqueue,
  352. compare_cached_resolves_by_expiry_,
  353. offsetof(cached_resolve_t, minheap_idx),
  354. resolve);
  355. }
  356. /** Free all storage held in the DNS cache and related structures. */
  357. void
  358. dns_free_all(void)
  359. {
  360. cached_resolve_t **ptr, **next, *item;
  361. assert_cache_ok();
  362. if (cached_resolve_pqueue) {
  363. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  364. {
  365. if (res->state == CACHE_STATE_DONE)
  366. free_cached_resolve_(res);
  367. });
  368. }
  369. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  370. item = *ptr;
  371. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  372. free_cached_resolve_(item);
  373. }
  374. HT_CLEAR(cache_map, &cache_root);
  375. smartlist_free(cached_resolve_pqueue);
  376. cached_resolve_pqueue = NULL;
  377. tor_free(resolv_conf_fname);
  378. }
  379. /** Remove every cached_resolve whose <b>expire</b> time is before or
  380. * equal to <b>now</b> from the cache. */
  381. static void
  382. purge_expired_resolves(time_t now)
  383. {
  384. cached_resolve_t *resolve, *removed;
  385. pending_connection_t *pend;
  386. edge_connection_t *pendconn;
  387. assert_cache_ok();
  388. if (!cached_resolve_pqueue)
  389. return;
  390. while (smartlist_len(cached_resolve_pqueue)) {
  391. resolve = smartlist_get(cached_resolve_pqueue, 0);
  392. if (resolve->expire > now)
  393. break;
  394. smartlist_pqueue_pop(cached_resolve_pqueue,
  395. compare_cached_resolves_by_expiry_,
  396. offsetof(cached_resolve_t, minheap_idx));
  397. if (resolve->state == CACHE_STATE_PENDING) {
  398. log_debug(LD_EXIT,
  399. "Expiring a dns resolve %s that's still pending. Forgot to "
  400. "cull it? DNS resolve didn't tell us about the timeout?",
  401. escaped_safe_str(resolve->address));
  402. } else if (resolve->state == CACHE_STATE_CACHED) {
  403. log_debug(LD_EXIT,
  404. "Forgetting old cached resolve (address %s, expires %lu)",
  405. escaped_safe_str(resolve->address),
  406. (unsigned long)resolve->expire);
  407. tor_assert(!resolve->pending_connections);
  408. } else {
  409. tor_assert(resolve->state == CACHE_STATE_DONE);
  410. tor_assert(!resolve->pending_connections);
  411. }
  412. if (resolve->pending_connections) {
  413. log_debug(LD_EXIT,
  414. "Closing pending connections on timed-out DNS resolve!");
  415. while (resolve->pending_connections) {
  416. pend = resolve->pending_connections;
  417. resolve->pending_connections = pend->next;
  418. /* Connections should only be pending if they have no socket. */
  419. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  420. pendconn = pend->conn;
  421. /* Prevent double-remove */
  422. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  423. if (!pendconn->base_.marked_for_close) {
  424. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  425. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  426. connection_free_(TO_CONN(pendconn));
  427. }
  428. tor_free(pend);
  429. }
  430. }
  431. if (resolve->state == CACHE_STATE_CACHED ||
  432. resolve->state == CACHE_STATE_PENDING) {
  433. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  434. if (removed != resolve) {
  435. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  436. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  437. resolve->address, (void*)resolve,
  438. removed ? removed->address : "NULL", (void*)removed);
  439. }
  440. tor_assert(removed == resolve);
  441. } else {
  442. /* This should be in state DONE. Make sure it's not in the cache. */
  443. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  444. tor_assert(tmp != resolve);
  445. }
  446. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  447. tor_free(resolve->result_ptr.hostname);
  448. resolve->magic = 0xF0BBF0BB;
  449. tor_free(resolve);
  450. }
  451. assert_cache_ok();
  452. }
  453. /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
  454. * or ipv6 depending on the connection's address". */
  455. #define RESOLVED_TYPE_AUTO 0xff
  456. /** Send a response to the RESOLVE request of a connection.
  457. * <b>answer_type</b> must be one of
  458. * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
  459. *
  460. * If <b>circ</b> is provided, and we have a cached answer, send the
  461. * answer back along circ; otherwise, send the answer back along
  462. * <b>conn</b>'s attached circuit.
  463. */
  464. MOCK_IMPL(STATIC void,
  465. send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type,
  466. const cached_resolve_t *resolved))
  467. {
  468. char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
  469. size_t buflen = 0;
  470. uint32_t ttl;
  471. buf[0] = answer_type;
  472. ttl = dns_clip_ttl(conn->address_ttl);
  473. switch (answer_type)
  474. {
  475. case RESOLVED_TYPE_AUTO:
  476. if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
  477. cp[0] = RESOLVED_TYPE_IPV4;
  478. cp[1] = 4;
  479. set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
  480. set_uint32(cp+6, htonl(ttl));
  481. cp += 10;
  482. }
  483. if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
  484. const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
  485. cp[0] = RESOLVED_TYPE_IPV6;
  486. cp[1] = 16;
  487. memcpy(cp+2, bytes, 16);
  488. set_uint32(cp+18, htonl(ttl));
  489. cp += 22;
  490. }
  491. if (cp != buf) {
  492. buflen = cp - buf;
  493. break;
  494. } else {
  495. answer_type = RESOLVED_TYPE_ERROR;
  496. /* fall through. */
  497. }
  498. /* Falls through. */
  499. case RESOLVED_TYPE_ERROR_TRANSIENT:
  500. case RESOLVED_TYPE_ERROR:
  501. {
  502. const char *errmsg = "Error resolving hostname";
  503. size_t msglen = strlen(errmsg);
  504. buf[0] = answer_type;
  505. buf[1] = msglen;
  506. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  507. set_uint32(buf+2+msglen, htonl(ttl));
  508. buflen = 6+msglen;
  509. break;
  510. }
  511. default:
  512. tor_assert(0);
  513. return;
  514. }
  515. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  516. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  517. }
  518. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  519. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  520. * The answer type will be RESOLVED_HOSTNAME.
  521. *
  522. * If <b>circ</b> is provided, and we have a cached answer, send the
  523. * answer back along circ; otherwise, send the answer back along
  524. * <b>conn</b>'s attached circuit.
  525. */
  526. MOCK_IMPL(STATIC void,
  527. send_resolved_hostname_cell,(edge_connection_t *conn,
  528. const char *hostname))
  529. {
  530. char buf[RELAY_PAYLOAD_SIZE];
  531. size_t buflen;
  532. uint32_t ttl;
  533. size_t namelen = strlen(hostname);
  534. tor_assert(hostname);
  535. tor_assert(namelen < 256);
  536. ttl = dns_clip_ttl(conn->address_ttl);
  537. buf[0] = RESOLVED_TYPE_HOSTNAME;
  538. buf[1] = (uint8_t)namelen;
  539. memcpy(buf+2, hostname, namelen);
  540. set_uint32(buf+2+namelen, htonl(ttl));
  541. buflen = 2+namelen+4;
  542. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  543. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  544. // log_notice(LD_EXIT, "Sent");
  545. }
  546. /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
  547. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  548. * If resolve failed, free exitconn and return -1.
  549. *
  550. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  551. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  552. * need to send back an END cell, since connection_exit_begin_conn will
  553. * do that for us.)
  554. *
  555. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  556. * circuit.
  557. *
  558. * Else, if seen before and pending, add conn to the pending list,
  559. * and return 0.
  560. *
  561. * Else, if not seen before, add conn to pending list, hand to
  562. * dns farm, and return 0.
  563. *
  564. * Exitconn's on_circuit field must be set, but exitconn should not
  565. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  566. * On success, link the connection to n_streams if it's an exit connection.
  567. * On "pending", link the connection to resolving streams. Otherwise,
  568. * clear its on_circuit field.
  569. */
  570. int
  571. dns_resolve(edge_connection_t *exitconn)
  572. {
  573. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  574. int is_resolve, r;
  575. int made_connection_pending = 0;
  576. char *hostname = NULL;
  577. cached_resolve_t *resolve = NULL;
  578. is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  579. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
  580. &made_connection_pending, &resolve);
  581. switch (r) {
  582. case 1:
  583. /* We got an answer without a lookup -- either the answer was
  584. * cached, or it was obvious (like an IP address). */
  585. if (is_resolve) {
  586. /* Send the answer back right now, and detach. */
  587. if (hostname)
  588. send_resolved_hostname_cell(exitconn, hostname);
  589. else
  590. send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
  591. exitconn->on_circuit = NULL;
  592. } else {
  593. /* Add to the n_streams list; the calling function will send back a
  594. * connected cell. */
  595. exitconn->next_stream = oncirc->n_streams;
  596. oncirc->n_streams = exitconn;
  597. }
  598. break;
  599. case 0:
  600. /* The request is pending: add the connection into the linked list of
  601. * resolving_streams on this circuit. */
  602. exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
  603. exitconn->next_stream = oncirc->resolving_streams;
  604. oncirc->resolving_streams = exitconn;
  605. break;
  606. case -2:
  607. case -1:
  608. /* The request failed before it could start: cancel this connection,
  609. * and stop everybody waiting for the same connection. */
  610. if (is_resolve) {
  611. send_resolved_cell(exitconn,
  612. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  613. NULL);
  614. }
  615. exitconn->on_circuit = NULL;
  616. dns_cancel_pending_resolve(exitconn->base_.address);
  617. if (!made_connection_pending && !exitconn->base_.marked_for_close) {
  618. /* If we made the connection pending, then we freed it already in
  619. * dns_cancel_pending_resolve(). If we marked it for close, it'll
  620. * get freed from the main loop. Otherwise, can free it now. */
  621. connection_free_(TO_CONN(exitconn));
  622. }
  623. break;
  624. default:
  625. tor_assert(0);
  626. }
  627. tor_free(hostname);
  628. return r;
  629. }
  630. /** Helper function for dns_resolve: same functionality, but does not handle:
  631. * - marking connections on error and clearing their on_circuit
  632. * - linking connections to n_streams/resolving_streams,
  633. * - sending resolved cells if we have an answer/error right away,
  634. *
  635. * Return -2 on a transient error. If it's a reverse resolve and it's
  636. * successful, sets *<b>hostname_out</b> to a newly allocated string
  637. * holding the cached reverse DNS value.
  638. *
  639. * Set *<b>made_connection_pending_out</b> to true if we have placed
  640. * <b>exitconn</b> on the list of pending connections for some resolve; set it
  641. * to false otherwise.
  642. *
  643. * Set *<b>resolve_out</b> to a cached resolve, if we found one.
  644. */
  645. MOCK_IMPL(STATIC int,
  646. dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
  647. or_circuit_t *oncirc, char **hostname_out,
  648. int *made_connection_pending_out,
  649. cached_resolve_t **resolve_out))
  650. {
  651. cached_resolve_t *resolve;
  652. cached_resolve_t search;
  653. pending_connection_t *pending_connection;
  654. int is_reverse = 0;
  655. tor_addr_t addr;
  656. time_t now = time(NULL);
  657. int r;
  658. assert_connection_ok(TO_CONN(exitconn), 0);
  659. tor_assert(!SOCKET_OK(exitconn->base_.s));
  660. assert_cache_ok();
  661. tor_assert(oncirc);
  662. *made_connection_pending_out = 0;
  663. /* first check if exitconn->base_.address is an IP. If so, we already
  664. * know the answer. */
  665. if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
  666. if (tor_addr_family(&addr) == AF_INET ||
  667. tor_addr_family(&addr) == AF_INET6) {
  668. tor_addr_copy(&exitconn->base_.addr, &addr);
  669. exitconn->address_ttl = DEFAULT_DNS_TTL;
  670. return 1;
  671. } else {
  672. /* XXXX unspec? Bogus? */
  673. return -1;
  674. }
  675. }
  676. /* If we're a non-exit, don't even do DNS lookups. */
  677. if (router_my_exit_policy_is_reject_star())
  678. return -1;
  679. if (address_is_invalid_destination(exitconn->base_.address, 0)) {
  680. tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
  681. "Rejecting invalid destination address %s",
  682. escaped_safe_str(exitconn->base_.address));
  683. return -1;
  684. }
  685. /* then take this opportunity to see if there are any expired
  686. * resolves in the hash table. */
  687. purge_expired_resolves(now);
  688. /* lower-case exitconn->base_.address, so it's in canonical form */
  689. tor_strlower(exitconn->base_.address);
  690. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  691. * .in-addr.arpa address but this isn't a resolve request, kill the
  692. * connection.
  693. */
  694. if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
  695. AF_UNSPEC, 0)) != 0) {
  696. if (r == 1) {
  697. is_reverse = 1;
  698. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  699. return -1;
  700. }
  701. if (!is_reverse || !is_resolve) {
  702. if (!is_reverse)
  703. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  704. escaped_safe_str(exitconn->base_.address));
  705. else if (!is_resolve)
  706. log_info(LD_EXIT,
  707. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  708. "sending error.",
  709. escaped_safe_str(exitconn->base_.address));
  710. return -1;
  711. }
  712. //log_notice(LD_EXIT, "Looks like an address %s",
  713. //exitconn->base_.address);
  714. }
  715. exitconn->is_reverse_dns_lookup = is_reverse;
  716. /* now check the hash table to see if 'address' is already there. */
  717. strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
  718. resolve = HT_FIND(cache_map, &cache_root, &search);
  719. if (resolve && resolve->expire > now) { /* already there */
  720. switch (resolve->state) {
  721. case CACHE_STATE_PENDING:
  722. /* add us to the pending list */
  723. pending_connection = tor_malloc_zero(
  724. sizeof(pending_connection_t));
  725. pending_connection->conn = exitconn;
  726. pending_connection->next = resolve->pending_connections;
  727. resolve->pending_connections = pending_connection;
  728. *made_connection_pending_out = 1;
  729. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
  730. "for pending DNS resolve of %s", exitconn->base_.s,
  731. escaped_safe_str(exitconn->base_.address));
  732. return 0;
  733. case CACHE_STATE_CACHED:
  734. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
  735. "cached answer for %s",
  736. exitconn->base_.s,
  737. escaped_safe_str(resolve->address));
  738. *resolve_out = resolve;
  739. return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
  740. case CACHE_STATE_DONE:
  741. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  742. tor_fragile_assert();
  743. }
  744. tor_assert(0);
  745. }
  746. tor_assert(!resolve);
  747. /* not there, need to add it */
  748. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  749. resolve->magic = CACHED_RESOLVE_MAGIC;
  750. resolve->state = CACHE_STATE_PENDING;
  751. resolve->minheap_idx = -1;
  752. strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
  753. /* add this connection to the pending list */
  754. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  755. pending_connection->conn = exitconn;
  756. resolve->pending_connections = pending_connection;
  757. *made_connection_pending_out = 1;
  758. /* Add this resolve to the cache and priority queue. */
  759. HT_INSERT(cache_map, &cache_root, resolve);
  760. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  761. log_debug(LD_EXIT,"Launching %s.",
  762. escaped_safe_str(exitconn->base_.address));
  763. assert_cache_ok();
  764. return launch_resolve(resolve);
  765. }
  766. /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
  767. * <b>resolve</b> whose DNS lookups have all either succeeded or failed,
  768. * update the appropriate fields (address_ttl and addr) of <b>exitconn</b>.
  769. *
  770. * The logic can be complicated here, since we might have launched both
  771. * an A lookup and an AAAA lookup, and since either of those might have
  772. * succeeded or failed, and since we want to answer a RESOLVE cell with
  773. * a full answer but answer a BEGIN cell with whatever answer the client
  774. * would accept <i>and</i> we could still connect to.
  775. *
  776. * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
  777. * copy of the name resulting hostname.
  778. *
  779. * Return -2 on a transient error, -1 on a permenent error, and 1 on
  780. * a successful lookup.
  781. */
  782. MOCK_IMPL(STATIC int,
  783. set_exitconn_info_from_resolve,(edge_connection_t *exitconn,
  784. const cached_resolve_t *resolve,
  785. char **hostname_out))
  786. {
  787. int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
  788. uint32_t begincell_flags;
  789. const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  790. tor_assert(exitconn);
  791. tor_assert(resolve);
  792. if (exitconn->is_reverse_dns_lookup) {
  793. exitconn->address_ttl = resolve->ttl_hostname;
  794. if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
  795. *hostname_out = tor_strdup(resolve->result_ptr.hostname);
  796. return 1;
  797. } else {
  798. return -1;
  799. }
  800. }
  801. /* If we're here then the connection wants one or either of ipv4, ipv6, and
  802. * we can give it one or both. */
  803. if (is_resolve) {
  804. begincell_flags = BEGIN_FLAG_IPV6_OK;
  805. } else {
  806. begincell_flags = exitconn->begincell_flags;
  807. }
  808. ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
  809. ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
  810. ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
  811. (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
  812. get_options()->IPv6Exit;
  813. /* Now decide which one to actually give. */
  814. if (ipv4_ok && ipv6_ok && is_resolve) {
  815. answer_with_ipv4 = 1;
  816. } else if (ipv4_ok && ipv6_ok) {
  817. /* If we have both, see if our exit policy has an opinion. */
  818. const uint16_t port = exitconn->base_.port;
  819. int ipv4_allowed, ipv6_allowed;
  820. tor_addr_t a4, a6;
  821. tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
  822. tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
  823. ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
  824. ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
  825. if (ipv4_allowed && !ipv6_allowed) {
  826. answer_with_ipv4 = 1;
  827. } else if (ipv6_allowed && !ipv4_allowed) {
  828. answer_with_ipv4 = 0;
  829. } else {
  830. /* Our exit policy would permit both. Answer with whichever the user
  831. * prefers */
  832. answer_with_ipv4 = !(begincell_flags &
  833. BEGIN_FLAG_IPV6_PREFERRED);
  834. }
  835. } else {
  836. /* Otherwise if one is okay, send it back. */
  837. if (ipv4_ok) {
  838. answer_with_ipv4 = 1;
  839. } else if (ipv6_ok) {
  840. answer_with_ipv4 = 0;
  841. } else {
  842. /* Neither one was okay. Choose based on user preference. */
  843. answer_with_ipv4 = !(begincell_flags &
  844. BEGIN_FLAG_IPV6_PREFERRED);
  845. }
  846. }
  847. /* Finally, we write the answer back. */
  848. r = 1;
  849. if (answer_with_ipv4) {
  850. if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
  851. tor_addr_from_ipv4h(&exitconn->base_.addr,
  852. resolve->result_ipv4.addr_ipv4);
  853. } else {
  854. r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
  855. }
  856. exitconn->address_ttl = resolve->ttl_ipv4;
  857. } else {
  858. if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
  859. tor_addr_from_in6(&exitconn->base_.addr,
  860. &resolve->result_ipv6.addr_ipv6);
  861. } else {
  862. r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
  863. }
  864. exitconn->address_ttl = resolve->ttl_ipv6;
  865. }
  866. return r;
  867. }
  868. /** Log an error and abort if conn is waiting for a DNS resolve.
  869. */
  870. void
  871. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  872. {
  873. pending_connection_t *pend;
  874. cached_resolve_t search;
  875. #if 1
  876. cached_resolve_t *resolve;
  877. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  878. resolve = HT_FIND(cache_map, &cache_root, &search);
  879. if (!resolve)
  880. return;
  881. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  882. tor_assert(pend->conn != conn);
  883. }
  884. #else /* !(1) */
  885. cached_resolve_t **resolve;
  886. HT_FOREACH(resolve, cache_map, &cache_root) {
  887. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  888. tor_assert(pend->conn != conn);
  889. }
  890. }
  891. #endif /* 1 */
  892. }
  893. /** Log an error and abort if any connection waiting for a DNS resolve is
  894. * corrupted. */
  895. void
  896. assert_all_pending_dns_resolves_ok(void)
  897. {
  898. pending_connection_t *pend;
  899. cached_resolve_t **resolve;
  900. HT_FOREACH(resolve, cache_map, &cache_root) {
  901. for (pend = (*resolve)->pending_connections;
  902. pend;
  903. pend = pend->next) {
  904. assert_connection_ok(TO_CONN(pend->conn), 0);
  905. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  906. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  907. }
  908. }
  909. }
  910. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  911. */
  912. void
  913. connection_dns_remove(edge_connection_t *conn)
  914. {
  915. pending_connection_t *pend, *victim;
  916. cached_resolve_t search;
  917. cached_resolve_t *resolve;
  918. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  919. tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
  920. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  921. resolve = HT_FIND(cache_map, &cache_root, &search);
  922. if (!resolve) {
  923. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  924. escaped_safe_str(conn->base_.address));
  925. return;
  926. }
  927. tor_assert(resolve->pending_connections);
  928. assert_connection_ok(TO_CONN(conn),0);
  929. pend = resolve->pending_connections;
  930. if (pend->conn == conn) {
  931. resolve->pending_connections = pend->next;
  932. tor_free(pend);
  933. log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
  934. "longer waiting for resolve of %s",
  935. conn->base_.s,
  936. escaped_safe_str(conn->base_.address));
  937. return;
  938. } else {
  939. for ( ; pend->next; pend = pend->next) {
  940. if (pend->next->conn == conn) {
  941. victim = pend->next;
  942. pend->next = victim->next;
  943. tor_free(victim);
  944. log_debug(LD_EXIT,
  945. "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
  946. "for resolve of %s",
  947. conn->base_.s, escaped_safe_str(conn->base_.address));
  948. return; /* more are pending */
  949. }
  950. }
  951. log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
  952. "for a resolve of %s, but we tried to remove it.",
  953. conn->base_.s, escaped_safe_str(conn->base_.address));
  954. }
  955. }
  956. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  957. * the resolve for <b>address</b> itself, and remove any cached results for
  958. * <b>address</b> from the cache.
  959. */
  960. MOCK_IMPL(void,
  961. dns_cancel_pending_resolve,(const char *address))
  962. {
  963. pending_connection_t *pend;
  964. cached_resolve_t search;
  965. cached_resolve_t *resolve, *tmp;
  966. edge_connection_t *pendconn;
  967. circuit_t *circ;
  968. strlcpy(search.address, address, sizeof(search.address));
  969. resolve = HT_FIND(cache_map, &cache_root, &search);
  970. if (!resolve)
  971. return;
  972. if (resolve->state != CACHE_STATE_PENDING) {
  973. /* We can get into this state if we never actually created the pending
  974. * resolve, due to finding an earlier cached error or something. Just
  975. * ignore it. */
  976. if (resolve->pending_connections) {
  977. log_warn(LD_BUG,
  978. "Address %s is not pending but has pending connections!",
  979. escaped_safe_str(address));
  980. tor_fragile_assert();
  981. }
  982. return;
  983. }
  984. if (!resolve->pending_connections) {
  985. log_warn(LD_BUG,
  986. "Address %s is pending but has no pending connections!",
  987. escaped_safe_str(address));
  988. tor_fragile_assert();
  989. return;
  990. }
  991. tor_assert(resolve->pending_connections);
  992. /* mark all pending connections to fail */
  993. log_debug(LD_EXIT,
  994. "Failing all connections waiting on DNS resolve of %s",
  995. escaped_safe_str(address));
  996. while (resolve->pending_connections) {
  997. pend = resolve->pending_connections;
  998. pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  999. pendconn = pend->conn;
  1000. assert_connection_ok(TO_CONN(pendconn), 0);
  1001. tor_assert(!SOCKET_OK(pendconn->base_.s));
  1002. if (!pendconn->base_.marked_for_close) {
  1003. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1004. }
  1005. circ = circuit_get_by_edge_conn(pendconn);
  1006. if (circ)
  1007. circuit_detach_stream(circ, pendconn);
  1008. if (!pendconn->base_.marked_for_close)
  1009. connection_free_(TO_CONN(pendconn));
  1010. resolve->pending_connections = pend->next;
  1011. tor_free(pend);
  1012. }
  1013. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  1014. if (tmp != resolve) {
  1015. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  1016. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1017. resolve->address, (void*)resolve,
  1018. tmp ? tmp->address : "NULL", (void*)tmp);
  1019. }
  1020. tor_assert(tmp == resolve);
  1021. resolve->state = CACHE_STATE_DONE;
  1022. }
  1023. /** Return true iff <b>address</b> is one of the addresses we use to verify
  1024. * that well-known sites aren't being hijacked by our DNS servers. */
  1025. static inline int
  1026. is_test_address(const char *address)
  1027. {
  1028. const or_options_t *options = get_options();
  1029. return options->ServerDNSTestAddresses &&
  1030. smartlist_contains_string_case(options->ServerDNSTestAddresses, address);
  1031. }
  1032. /** Called on the OR side when the eventdns library tells us the outcome of a
  1033. * single DNS resolve: remember the answer, and tell all pending connections
  1034. * about the result of the lookup if the lookup is now done. (<b>address</b>
  1035. * is a NUL-terminated string containing the address to look up;
  1036. * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
  1037. * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
  1038. * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
  1039. * <b>ttl</b> is the time-to-live of this answer, in seconds.)
  1040. */
  1041. static void
  1042. dns_found_answer(const char *address, uint8_t query_type,
  1043. int dns_answer,
  1044. const tor_addr_t *addr,
  1045. const char *hostname, uint32_t ttl)
  1046. {
  1047. cached_resolve_t search;
  1048. cached_resolve_t *resolve;
  1049. assert_cache_ok();
  1050. strlcpy(search.address, address, sizeof(search.address));
  1051. resolve = HT_FIND(cache_map, &cache_root, &search);
  1052. if (!resolve) {
  1053. int is_test_addr = is_test_address(address);
  1054. if (!is_test_addr)
  1055. log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
  1056. escaped_safe_str(address));
  1057. return;
  1058. }
  1059. assert_resolve_ok(resolve);
  1060. if (resolve->state != CACHE_STATE_PENDING) {
  1061. /* XXXX Maybe update addr? or check addr for consistency? Or let
  1062. * VALID replace FAILED? */
  1063. int is_test_addr = is_test_address(address);
  1064. if (!is_test_addr)
  1065. log_notice(LD_EXIT,
  1066. "Resolved %s which was already resolved; ignoring",
  1067. escaped_safe_str(address));
  1068. tor_assert(resolve->pending_connections == NULL);
  1069. return;
  1070. }
  1071. cached_resolve_add_answer(resolve, query_type, dns_answer,
  1072. addr, hostname, ttl);
  1073. if (cached_resolve_have_all_answers(resolve)) {
  1074. inform_pending_connections(resolve);
  1075. make_pending_resolve_cached(resolve);
  1076. }
  1077. }
  1078. /** Given a pending cached_resolve_t that we just finished resolving,
  1079. * inform every connection that was waiting for the outcome of that
  1080. * resolution.
  1081. *
  1082. * Do this by sending a RELAY_RESOLVED cell (if the pending stream had sent us
  1083. * RELAY_RESOLVE cell), or by launching an exit connection (if the pending
  1084. * stream had send us a RELAY_BEGIN cell).
  1085. */
  1086. static void
  1087. inform_pending_connections(cached_resolve_t *resolve)
  1088. {
  1089. pending_connection_t *pend;
  1090. edge_connection_t *pendconn;
  1091. int r;
  1092. while (resolve->pending_connections) {
  1093. char *hostname = NULL;
  1094. pend = resolve->pending_connections;
  1095. pendconn = pend->conn; /* don't pass complex things to the
  1096. connection_mark_for_close macro */
  1097. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  1098. if (pendconn->base_.marked_for_close) {
  1099. /* prevent double-remove. */
  1100. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1101. resolve->pending_connections = pend->next;
  1102. tor_free(pend);
  1103. continue;
  1104. }
  1105. r = set_exitconn_info_from_resolve(pendconn,
  1106. resolve,
  1107. &hostname);
  1108. if (r < 0) {
  1109. /* prevent double-remove. */
  1110. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1111. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1112. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1113. /* This detach must happen after we send the end cell. */
  1114. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1115. } else {
  1116. send_resolved_cell(pendconn, r == -1 ?
  1117. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  1118. NULL);
  1119. /* This detach must happen after we send the resolved cell. */
  1120. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1121. }
  1122. connection_free_(TO_CONN(pendconn));
  1123. } else {
  1124. circuit_t *circ;
  1125. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1126. /* prevent double-remove. */
  1127. pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  1128. circ = circuit_get_by_edge_conn(pend->conn);
  1129. tor_assert(circ);
  1130. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1131. /* unlink pend->conn from resolving_streams, */
  1132. circuit_detach_stream(circ, pend->conn);
  1133. /* and link it to n_streams */
  1134. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1135. pend->conn->on_circuit = circ;
  1136. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1137. connection_exit_connect(pend->conn);
  1138. } else {
  1139. /* prevent double-remove. This isn't really an accurate state,
  1140. * but it does the right thing. */
  1141. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1142. if (pendconn->is_reverse_dns_lookup)
  1143. send_resolved_hostname_cell(pendconn, hostname);
  1144. else
  1145. send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
  1146. circ = circuit_get_by_edge_conn(pendconn);
  1147. tor_assert(circ);
  1148. circuit_detach_stream(circ, pendconn);
  1149. connection_free_(TO_CONN(pendconn));
  1150. }
  1151. }
  1152. resolve->pending_connections = pend->next;
  1153. tor_free(pend);
  1154. tor_free(hostname);
  1155. }
  1156. }
  1157. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1158. * corresponding cached cached_resolve_t.
  1159. *
  1160. * This function is only necessary because of the perversity of our
  1161. * cache timeout code; see inline comment for ideas on eliminating it.
  1162. **/
  1163. static void
  1164. make_pending_resolve_cached(cached_resolve_t *resolve)
  1165. {
  1166. cached_resolve_t *removed;
  1167. resolve->state = CACHE_STATE_DONE;
  1168. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1169. if (removed != resolve) {
  1170. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1171. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1172. resolve->address, (void*)resolve,
  1173. removed ? removed->address : "NULL", (void*)removed);
  1174. }
  1175. assert_resolve_ok(resolve);
  1176. assert_cache_ok();
  1177. /* The resolve will eventually just hit the time-out in the expiry queue and
  1178. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1179. * way. XXXXX we could do better!*/
  1180. {
  1181. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1182. sizeof(cached_resolve_t));
  1183. uint32_t ttl = UINT32_MAX;
  1184. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1185. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1186. new_resolve->result_ptr.hostname =
  1187. tor_strdup(resolve->result_ptr.hostname);
  1188. new_resolve->state = CACHE_STATE_CACHED;
  1189. assert_resolve_ok(new_resolve);
  1190. HT_INSERT(cache_map, &cache_root, new_resolve);
  1191. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1192. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1193. resolve->ttl_ipv4 < ttl)
  1194. ttl = resolve->ttl_ipv4;
  1195. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1196. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1197. resolve->ttl_ipv6 < ttl)
  1198. ttl = resolve->ttl_ipv6;
  1199. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1200. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1201. resolve->ttl_hostname < ttl)
  1202. ttl = resolve->ttl_hostname;
  1203. set_expiry(new_resolve, time(NULL) + dns_clip_ttl(ttl));
  1204. }
  1205. assert_cache_ok();
  1206. }
  1207. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1208. * a transient failure. */
  1209. static int
  1210. evdns_err_is_transient(int err)
  1211. {
  1212. switch (err)
  1213. {
  1214. case DNS_ERR_SERVERFAILED:
  1215. case DNS_ERR_TRUNCATED:
  1216. case DNS_ERR_TIMEOUT:
  1217. return 1;
  1218. default:
  1219. return 0;
  1220. }
  1221. }
  1222. /** Configure eventdns nameservers if force is true, or if the configuration
  1223. * has changed since the last time we called this function, or if we failed on
  1224. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1225. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1226. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1227. * -1 on failure. */
  1228. static int
  1229. configure_nameservers(int force)
  1230. {
  1231. const or_options_t *options;
  1232. const char *conf_fname;
  1233. struct stat st;
  1234. int r, flags;
  1235. options = get_options();
  1236. conf_fname = options->ServerDNSResolvConfFile;
  1237. #ifndef _WIN32
  1238. if (!conf_fname)
  1239. conf_fname = "/etc/resolv.conf";
  1240. #endif
  1241. flags = DNS_OPTIONS_ALL;
  1242. if (!the_evdns_base) {
  1243. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1244. log_err(LD_BUG, "Couldn't create an evdns_base");
  1245. return -1;
  1246. }
  1247. }
  1248. evdns_set_log_fn(evdns_log_cb);
  1249. if (conf_fname) {
  1250. log_debug(LD_FS, "stat()ing %s", conf_fname);
  1251. if (stat(sandbox_intern_string(conf_fname), &st)) {
  1252. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1253. conf_fname, strerror(errno));
  1254. goto err;
  1255. }
  1256. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1257. && st.st_mtime == resolv_conf_mtime) {
  1258. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1259. return 0;
  1260. }
  1261. if (nameservers_configured) {
  1262. evdns_base_search_clear(the_evdns_base);
  1263. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1264. }
  1265. #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
  1266. if (flags & DNS_OPTION_HOSTSFILE) {
  1267. flags ^= DNS_OPTION_HOSTSFILE;
  1268. log_debug(LD_FS, "Loading /etc/hosts");
  1269. evdns_base_load_hosts(the_evdns_base,
  1270. sandbox_intern_string("/etc/hosts"));
  1271. }
  1272. #endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
  1273. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1274. if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
  1275. sandbox_intern_string(conf_fname)))) {
  1276. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1277. conf_fname, conf_fname, r);
  1278. goto err;
  1279. }
  1280. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1281. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1282. goto err;
  1283. }
  1284. tor_free(resolv_conf_fname);
  1285. resolv_conf_fname = tor_strdup(conf_fname);
  1286. resolv_conf_mtime = st.st_mtime;
  1287. if (nameservers_configured)
  1288. evdns_base_resume(the_evdns_base);
  1289. }
  1290. #ifdef _WIN32
  1291. else {
  1292. if (nameservers_configured) {
  1293. evdns_base_search_clear(the_evdns_base);
  1294. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1295. }
  1296. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1297. log_warn(LD_EXIT,"Could not config nameservers.");
  1298. goto err;
  1299. }
  1300. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1301. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1302. "your Windows configuration.");
  1303. goto err;
  1304. }
  1305. if (nameservers_configured)
  1306. evdns_base_resume(the_evdns_base);
  1307. tor_free(resolv_conf_fname);
  1308. resolv_conf_mtime = 0;
  1309. }
  1310. #endif /* defined(_WIN32) */
  1311. #define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
  1312. // If we only have one nameserver, it does not make sense to back off
  1313. // from it for a timeout. Unfortunately, the value for max-timeouts is
  1314. // currently clamped by libevent to 255, but it does not hurt to set
  1315. // it higher in case libevent gets a patch for this. Higher-than-
  1316. // default maximum of 3 with multiple nameservers to avoid spuriously
  1317. // marking one down on bursts of timeouts resulting from scans/attacks
  1318. // against non-responding authoritative DNS servers.
  1319. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1320. SET("max-timeouts:", "1000000");
  1321. } else {
  1322. SET("max-timeouts:", "10");
  1323. }
  1324. // Elongate the queue of maximum inflight dns requests, so if a bunch
  1325. // remain pending at the resolver (happens commonly with Unbound) we won't
  1326. // stall every other DNS request. This potentially means some wasted
  1327. // CPU as there's a walk over a linear queue involved, but this is a
  1328. // much better tradeoff compared to just failing DNS requests because
  1329. // of a full queue.
  1330. SET("max-inflight:", "8192");
  1331. // Two retries at 5 and 10 seconds for bind9/named which relies on
  1332. // clients to handle retries. Second retry for retried circuits with
  1333. // extended 15 second timeout. Superfluous with local-system Unbound
  1334. // instance--has its own elaborate retry scheme.
  1335. SET("timeout:", "5");
  1336. SET("attempts:","3");
  1337. if (options->ServerDNSRandomizeCase)
  1338. SET("randomize-case:", "1");
  1339. else
  1340. SET("randomize-case:", "0");
  1341. #undef SET
  1342. dns_servers_relaunch_checks();
  1343. nameservers_configured = 1;
  1344. if (nameserver_config_failed) {
  1345. nameserver_config_failed = 0;
  1346. /* XXX the three calls to republish the descriptor might be producing
  1347. * descriptors that are only cosmetically different, especially on
  1348. * non-exit relays! -RD */
  1349. mark_my_descriptor_dirty("dns resolvers back");
  1350. }
  1351. return 0;
  1352. err:
  1353. nameservers_configured = 0;
  1354. if (! nameserver_config_failed) {
  1355. nameserver_config_failed = 1;
  1356. mark_my_descriptor_dirty("dns resolvers failed");
  1357. }
  1358. return -1;
  1359. }
  1360. /** For eventdns: Called when we get an answer for a request we launched.
  1361. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1362. */
  1363. static void
  1364. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1365. void *arg)
  1366. {
  1367. char *arg_ = arg;
  1368. uint8_t orig_query_type = arg_[0];
  1369. char *string_address = arg_ + 1;
  1370. tor_addr_t addr;
  1371. const char *hostname = NULL;
  1372. int was_wildcarded = 0;
  1373. tor_addr_make_unspec(&addr);
  1374. /* Keep track of whether IPv6 is working */
  1375. if (type == DNS_IPv6_AAAA) {
  1376. if (result == DNS_ERR_TIMEOUT) {
  1377. ++n_ipv6_timeouts;
  1378. }
  1379. if (n_ipv6_timeouts > 10 &&
  1380. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1381. if (! dns_is_broken_for_ipv6) {
  1382. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1383. "have timed out. I'm going to assume I can't get AAAA "
  1384. "responses.");
  1385. dns_is_broken_for_ipv6 = 1;
  1386. }
  1387. }
  1388. }
  1389. if (result == DNS_ERR_NONE) {
  1390. if (type == DNS_IPv4_A && count) {
  1391. char answer_buf[INET_NTOA_BUF_LEN+1];
  1392. char *escaped_address;
  1393. uint32_t *addrs = addresses;
  1394. tor_addr_from_ipv4n(&addr, addrs[0]);
  1395. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1396. escaped_address = esc_for_log(string_address);
  1397. if (answer_is_wildcarded(answer_buf)) {
  1398. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1399. "address %s; treating as a failure.",
  1400. safe_str(escaped_address),
  1401. escaped_safe_str(answer_buf));
  1402. was_wildcarded = 1;
  1403. tor_addr_make_unspec(&addr);
  1404. result = DNS_ERR_NOTEXIST;
  1405. } else {
  1406. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1407. safe_str(escaped_address),
  1408. escaped_safe_str(answer_buf));
  1409. }
  1410. tor_free(escaped_address);
  1411. } else if (type == DNS_IPv6_AAAA && count) {
  1412. char answer_buf[TOR_ADDR_BUF_LEN];
  1413. char *escaped_address;
  1414. struct in6_addr *addrs = addresses;
  1415. tor_addr_from_in6(&addr, &addrs[0]);
  1416. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1417. escaped_address = esc_for_log(string_address);
  1418. if (answer_is_wildcarded(answer_buf)) {
  1419. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1420. "address %s; treating as a failure.",
  1421. safe_str(escaped_address),
  1422. escaped_safe_str(answer_buf));
  1423. was_wildcarded = 1;
  1424. tor_addr_make_unspec(&addr);
  1425. result = DNS_ERR_NOTEXIST;
  1426. } else {
  1427. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1428. safe_str(escaped_address),
  1429. escaped_safe_str(answer_buf));
  1430. }
  1431. tor_free(escaped_address);
  1432. } else if (type == DNS_PTR && count) {
  1433. char *escaped_address;
  1434. hostname = ((char**)addresses)[0];
  1435. escaped_address = esc_for_log(string_address);
  1436. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1437. safe_str(escaped_address),
  1438. escaped_safe_str(hostname));
  1439. tor_free(escaped_address);
  1440. } else if (count) {
  1441. log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
  1442. " for %s.",
  1443. escaped_safe_str(string_address));
  1444. } else {
  1445. log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
  1446. escaped_safe_str(string_address));
  1447. }
  1448. }
  1449. if (was_wildcarded) {
  1450. if (is_test_address(string_address)) {
  1451. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1452. * server must really hate us. */
  1453. add_wildcarded_test_address(string_address);
  1454. }
  1455. }
  1456. if (orig_query_type && type && orig_query_type != type) {
  1457. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1458. (int)orig_query_type, (int)type);
  1459. }
  1460. if (result != DNS_ERR_SHUTDOWN)
  1461. dns_found_answer(string_address, orig_query_type,
  1462. result, &addr, hostname, ttl);
  1463. tor_free(arg_);
  1464. }
  1465. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1466. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1467. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1468. static int
  1469. launch_one_resolve(const char *address, uint8_t query_type,
  1470. const tor_addr_t *ptr_address)
  1471. {
  1472. const int options = get_options()->ServerDNSSearchDomains ? 0
  1473. : DNS_QUERY_NO_SEARCH;
  1474. const size_t addr_len = strlen(address);
  1475. struct evdns_request *req = 0;
  1476. char *addr = tor_malloc(addr_len + 2);
  1477. addr[0] = (char) query_type;
  1478. memcpy(addr+1, address, addr_len + 1);
  1479. switch (query_type) {
  1480. case DNS_IPv4_A:
  1481. req = evdns_base_resolve_ipv4(the_evdns_base,
  1482. address, options, evdns_callback, addr);
  1483. break;
  1484. case DNS_IPv6_AAAA:
  1485. req = evdns_base_resolve_ipv6(the_evdns_base,
  1486. address, options, evdns_callback, addr);
  1487. ++n_ipv6_requests_made;
  1488. break;
  1489. case DNS_PTR:
  1490. if (tor_addr_family(ptr_address) == AF_INET)
  1491. req = evdns_base_resolve_reverse(the_evdns_base,
  1492. tor_addr_to_in(ptr_address),
  1493. DNS_QUERY_NO_SEARCH,
  1494. evdns_callback, addr);
  1495. else if (tor_addr_family(ptr_address) == AF_INET6)
  1496. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1497. tor_addr_to_in6(ptr_address),
  1498. DNS_QUERY_NO_SEARCH,
  1499. evdns_callback, addr);
  1500. else
  1501. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1502. break;
  1503. default:
  1504. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1505. break;
  1506. }
  1507. if (req) {
  1508. return 0;
  1509. } else {
  1510. tor_free(addr);
  1511. return -1;
  1512. }
  1513. }
  1514. /** For eventdns: start resolving as necessary to find the target for
  1515. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1516. * 0 on "resolve launched." */
  1517. MOCK_IMPL(STATIC int,
  1518. launch_resolve,(cached_resolve_t *resolve))
  1519. {
  1520. tor_addr_t a;
  1521. int r;
  1522. if (net_is_disabled())
  1523. return -1;
  1524. /* What? Nameservers not configured? Sounds like a bug. */
  1525. if (!nameservers_configured) {
  1526. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1527. "launched. Configuring.");
  1528. if (configure_nameservers(1) < 0) {
  1529. return -1;
  1530. }
  1531. }
  1532. r = tor_addr_parse_PTR_name(
  1533. &a, resolve->address, AF_UNSPEC, 0);
  1534. tor_assert(the_evdns_base);
  1535. if (r == 0) {
  1536. log_info(LD_EXIT, "Launching eventdns request for %s",
  1537. escaped_safe_str(resolve->address));
  1538. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1539. if (get_options()->IPv6Exit)
  1540. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1541. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1542. resolve->res_status_ipv4 = 0;
  1543. r = -1;
  1544. }
  1545. if (r==0 && get_options()->IPv6Exit) {
  1546. /* We ask for an IPv6 address for *everything*. */
  1547. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1548. resolve->res_status_ipv6 = 0;
  1549. r = -1;
  1550. }
  1551. }
  1552. } else if (r == 1) {
  1553. r = 0;
  1554. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1555. escaped_safe_str(resolve->address));
  1556. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1557. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1558. resolve->res_status_hostname = 0;
  1559. r = -1;
  1560. }
  1561. } else if (r == -1) {
  1562. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1563. }
  1564. if (r < 0) {
  1565. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1566. escaped_safe_str(resolve->address));
  1567. }
  1568. return r;
  1569. }
  1570. /** How many requests for bogus addresses have we launched so far? */
  1571. static int n_wildcard_requests = 0;
  1572. /** Map from dotted-quad IP address in response to an int holding how many
  1573. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1574. * would be easier to use definitely-invalid addresses (as specified by
  1575. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1576. static strmap_t *dns_wildcard_response_count = NULL;
  1577. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1578. * nameserver wants to return in response to requests for nonexistent domains.
  1579. */
  1580. static smartlist_t *dns_wildcard_list = NULL;
  1581. /** True iff we've logged about a single address getting wildcarded.
  1582. * Subsequent warnings will be less severe. */
  1583. static int dns_wildcard_one_notice_given = 0;
  1584. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1585. */
  1586. static int dns_wildcard_notice_given = 0;
  1587. /** List of supposedly good addresses that are getting wildcarded to the
  1588. * same addresses as nonexistent addresses. */
  1589. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1590. /** True iff we've warned about a test address getting wildcarded */
  1591. static int dns_wildcarded_test_address_notice_given = 0;
  1592. /** True iff all addresses seem to be getting wildcarded. */
  1593. static int dns_is_completely_invalid = 0;
  1594. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1595. * to a request for a hopefully bogus address. */
  1596. static void
  1597. wildcard_increment_answer(const char *id)
  1598. {
  1599. int *ip;
  1600. if (!dns_wildcard_response_count)
  1601. dns_wildcard_response_count = strmap_new();
  1602. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1603. if (!ip) {
  1604. ip = tor_malloc_zero(sizeof(int));
  1605. strmap_set(dns_wildcard_response_count, id, ip);
  1606. }
  1607. ++*ip;
  1608. if (*ip > 5 && n_wildcard_requests > 10) {
  1609. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1610. if (!smartlist_contains_string(dns_wildcard_list, id)) {
  1611. tor_log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1612. "Your DNS provider has given \"%s\" as an answer for %d different "
  1613. "invalid addresses. Apparently they are hijacking DNS failures. "
  1614. "I'll try to correct for this by treating future occurrences of "
  1615. "\"%s\" as 'not found'.", id, *ip, id);
  1616. smartlist_add_strdup(dns_wildcard_list, id);
  1617. }
  1618. if (!dns_wildcard_notice_given)
  1619. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1620. dns_wildcard_notice_given = 1;
  1621. }
  1622. }
  1623. /** Note that a single test address (one believed to be good) seems to be
  1624. * getting redirected to the same IP as failures are. */
  1625. static void
  1626. add_wildcarded_test_address(const char *address)
  1627. {
  1628. int n, n_test_addrs;
  1629. if (!dns_wildcarded_test_address_list)
  1630. dns_wildcarded_test_address_list = smartlist_new();
  1631. if (smartlist_contains_string_case(dns_wildcarded_test_address_list,
  1632. address))
  1633. return;
  1634. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1635. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1636. smartlist_add_strdup(dns_wildcarded_test_address_list, address);
  1637. n = smartlist_len(dns_wildcarded_test_address_list);
  1638. if (n > n_test_addrs/2) {
  1639. tor_log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1640. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1641. "address. It has done this with %d test addresses so far. I'm "
  1642. "going to stop being an exit node for now, since our DNS seems so "
  1643. "broken.", address, n);
  1644. if (!dns_is_completely_invalid) {
  1645. dns_is_completely_invalid = 1;
  1646. mark_my_descriptor_dirty("dns hijacking confirmed");
  1647. }
  1648. if (!dns_wildcarded_test_address_notice_given)
  1649. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1650. dns_wildcarded_test_address_notice_given = 1;
  1651. }
  1652. }
  1653. /** Callback function when we get an answer (possibly failing) for a request
  1654. * for a (hopefully) nonexistent domain. */
  1655. static void
  1656. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1657. void *addresses, void *arg)
  1658. {
  1659. (void)ttl;
  1660. ++n_wildcard_requests;
  1661. if (result == DNS_ERR_NONE && count) {
  1662. char *string_address = arg;
  1663. int i;
  1664. if (type == DNS_IPv4_A) {
  1665. const uint32_t *addrs = addresses;
  1666. for (i = 0; i < count; ++i) {
  1667. char answer_buf[INET_NTOA_BUF_LEN+1];
  1668. struct in_addr in;
  1669. in.s_addr = addrs[i];
  1670. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1671. wildcard_increment_answer(answer_buf);
  1672. }
  1673. } else if (type == DNS_IPv6_AAAA) {
  1674. const struct in6_addr *addrs = addresses;
  1675. for (i = 0; i < count; ++i) {
  1676. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1677. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1678. wildcard_increment_answer(answer_buf);
  1679. }
  1680. }
  1681. tor_log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1682. "Your DNS provider gave an answer for \"%s\", which "
  1683. "is not supposed to exist. Apparently they are hijacking "
  1684. "DNS failures. Trying to correct for this. We've noticed %d "
  1685. "possibly bad address%s so far.",
  1686. string_address, strmap_size(dns_wildcard_response_count),
  1687. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1688. dns_wildcard_one_notice_given = 1;
  1689. }
  1690. tor_free(arg);
  1691. }
  1692. /** Launch a single request for a nonexistent hostname consisting of between
  1693. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1694. * <b>suffix</b> */
  1695. static void
  1696. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1697. const char *suffix)
  1698. {
  1699. char *addr;
  1700. struct evdns_request *req;
  1701. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1702. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1703. "domains with request for bogus hostname \"%s\"", addr);
  1704. tor_assert(the_evdns_base);
  1705. if (is_ipv6)
  1706. req = evdns_base_resolve_ipv6(
  1707. the_evdns_base,
  1708. /* This "addr" tells us which address to resolve */
  1709. addr,
  1710. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1711. /* This "addr" is an argument to the callback*/ addr);
  1712. else
  1713. req = evdns_base_resolve_ipv4(
  1714. the_evdns_base,
  1715. /* This "addr" tells us which address to resolve */
  1716. addr,
  1717. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1718. /* This "addr" is an argument to the callback*/ addr);
  1719. if (!req) {
  1720. /* There is no evdns request in progress; stop addr from getting leaked */
  1721. tor_free(addr);
  1722. }
  1723. }
  1724. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1725. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1726. static void
  1727. launch_test_addresses(evutil_socket_t fd, short event, void *args)
  1728. {
  1729. const or_options_t *options = get_options();
  1730. (void)fd;
  1731. (void)event;
  1732. (void)args;
  1733. if (net_is_disabled())
  1734. return;
  1735. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1736. "hijack *everything*.");
  1737. /* This situation is worse than the failure-hijacking situation. When this
  1738. * happens, we're no good for DNS requests at all, and we shouldn't really
  1739. * be an exit server.*/
  1740. if (options->ServerDNSTestAddresses) {
  1741. tor_assert(the_evdns_base);
  1742. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1743. const char *, address) {
  1744. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1745. log_info(LD_EXIT, "eventdns rejected test address %s",
  1746. escaped_safe_str(address));
  1747. }
  1748. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1749. log_info(LD_EXIT, "eventdns rejected test address %s",
  1750. escaped_safe_str(address));
  1751. }
  1752. } SMARTLIST_FOREACH_END(address);
  1753. }
  1754. }
  1755. #define N_WILDCARD_CHECKS 2
  1756. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1757. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1758. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1759. * buy these lovely encyclopedias" page. */
  1760. static void
  1761. dns_launch_wildcard_checks(void)
  1762. {
  1763. int i, ipv6;
  1764. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1765. "to hijack DNS failures.");
  1766. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1767. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1768. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1769. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1770. * these. This is the standards-compliance equivalent of making sure
  1771. * that your crackhouse's elevator inspection certificate is up to date.
  1772. */
  1773. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1774. launch_wildcard_check(2, 16, ipv6, ".test");
  1775. /* These will break specs if there are ever any number of
  1776. * 8+-character top-level domains. */
  1777. launch_wildcard_check(8, 16, ipv6, "");
  1778. /* Try some random .com/org/net domains. This will work fine so long as
  1779. * not too many resolve to the same place. */
  1780. launch_wildcard_check(8, 16, ipv6, ".com");
  1781. launch_wildcard_check(8, 16, ipv6, ".org");
  1782. launch_wildcard_check(8, 16, ipv6, ".net");
  1783. }
  1784. }
  1785. }
  1786. /** If appropriate, start testing whether our DNS servers tend to lie to
  1787. * us. */
  1788. void
  1789. dns_launch_correctness_checks(void)
  1790. {
  1791. static struct event *launch_event = NULL;
  1792. struct timeval timeout;
  1793. if (!get_options()->ServerDNSDetectHijacking)
  1794. return;
  1795. dns_launch_wildcard_checks();
  1796. /* Wait a while before launching requests for test addresses, so we can
  1797. * get the results from checking for wildcarding. */
  1798. if (! launch_event)
  1799. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1800. launch_test_addresses, NULL);
  1801. timeout.tv_sec = 30;
  1802. timeout.tv_usec = 0;
  1803. if (evtimer_add(launch_event, &timeout)<0) {
  1804. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1805. }
  1806. }
  1807. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1808. int
  1809. dns_seems_to_be_broken(void)
  1810. {
  1811. return dns_is_completely_invalid;
  1812. }
  1813. /** Return true iff we think that IPv6 hostname lookup is broken */
  1814. int
  1815. dns_seems_to_be_broken_for_ipv6(void)
  1816. {
  1817. return dns_is_broken_for_ipv6;
  1818. }
  1819. /** Forget what we've previously learned about our DNS servers' correctness. */
  1820. void
  1821. dns_reset_correctness_checks(void)
  1822. {
  1823. strmap_free(dns_wildcard_response_count, tor_free_);
  1824. dns_wildcard_response_count = NULL;
  1825. n_wildcard_requests = 0;
  1826. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1827. if (dns_wildcard_list) {
  1828. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1829. smartlist_clear(dns_wildcard_list);
  1830. }
  1831. if (dns_wildcarded_test_address_list) {
  1832. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1833. tor_free(cp));
  1834. smartlist_clear(dns_wildcarded_test_address_list);
  1835. }
  1836. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1837. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1838. dns_is_broken_for_ipv6 = 0;
  1839. }
  1840. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1841. * returned in response to requests for nonexistent hostnames. */
  1842. static int
  1843. answer_is_wildcarded(const char *ip)
  1844. {
  1845. return dns_wildcard_list && smartlist_contains_string(dns_wildcard_list, ip);
  1846. }
  1847. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1848. static void
  1849. assert_resolve_ok(cached_resolve_t *resolve)
  1850. {
  1851. tor_assert(resolve);
  1852. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1853. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1854. tor_assert(tor_strisnonupper(resolve->address));
  1855. if (resolve->state != CACHE_STATE_PENDING) {
  1856. tor_assert(!resolve->pending_connections);
  1857. }
  1858. if (resolve->state == CACHE_STATE_PENDING ||
  1859. resolve->state == CACHE_STATE_DONE) {
  1860. #if 0
  1861. tor_assert(!resolve->ttl);
  1862. if (resolve->is_reverse)
  1863. tor_assert(!resolve->hostname);
  1864. else
  1865. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1866. #endif /* 0 */
  1867. /*XXXXX ADD MORE */
  1868. }
  1869. }
  1870. /** Return the number of DNS cache entries as an int */
  1871. static int
  1872. dns_cache_entry_count(void)
  1873. {
  1874. return HT_SIZE(&cache_root);
  1875. }
  1876. /** Log memory information about our internal DNS cache at level 'severity'. */
  1877. void
  1878. dump_dns_mem_usage(int severity)
  1879. {
  1880. /* This should never be larger than INT_MAX. */
  1881. int hash_count = dns_cache_entry_count();
  1882. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1883. hash_mem += HT_MEM_USAGE(&cache_root);
  1884. /* Print out the count and estimated size of our &cache_root. It undercounts
  1885. hostnames in cached reverse resolves.
  1886. */
  1887. tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1888. tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1889. (unsigned)hash_mem);
  1890. }
  1891. #ifdef DEBUG_DNS_CACHE
  1892. /** Exit with an assertion if the DNS cache is corrupt. */
  1893. static void
  1894. assert_cache_ok_(void)
  1895. {
  1896. cached_resolve_t **resolve;
  1897. int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
  1898. if (bad_rep) {
  1899. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1900. tor_assert(!bad_rep);
  1901. }
  1902. HT_FOREACH(resolve, cache_map, &cache_root) {
  1903. assert_resolve_ok(*resolve);
  1904. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1905. }
  1906. if (!cached_resolve_pqueue)
  1907. return;
  1908. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1909. compare_cached_resolves_by_expiry_,
  1910. offsetof(cached_resolve_t, minheap_idx));
  1911. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1912. {
  1913. if (res->state == CACHE_STATE_DONE) {
  1914. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1915. tor_assert(!found || found != res);
  1916. } else {
  1917. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1918. tor_assert(found);
  1919. }
  1920. });
  1921. }
  1922. #endif /* defined(DEBUG_DNS_CACHE) */
  1923. cached_resolve_t *
  1924. dns_get_cache_entry(cached_resolve_t *query)
  1925. {
  1926. return HT_FIND(cache_map, &cache_root, query);
  1927. }
  1928. void
  1929. dns_insert_cache_entry(cached_resolve_t *new_entry)
  1930. {
  1931. HT_INSERT(cache_map, &cache_root, new_entry);
  1932. }