dns.c 56 KB

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