dns.c 72 KB

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