dns.c 68 KB

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