dns.c 71 KB

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