addressmap.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #include "or.h"
  7. #include "addressmap.h"
  8. #include "circuituse.h"
  9. #include "config.h"
  10. #include "connection_edge.h"
  11. #include "control.h"
  12. #include "dns.h"
  13. #include "routerset.h"
  14. #include "nodelist.h"
  15. /** A client-side struct to remember requests to rewrite addresses
  16. * to new addresses. These structs are stored in the hash table
  17. * "addressmap" below.
  18. *
  19. * There are 5 ways to set an address mapping:
  20. * - A MapAddress command from the controller [permanent]
  21. * - An AddressMap directive in the torrc [permanent]
  22. * - When a TrackHostExits torrc directive is triggered [temporary]
  23. * - When a DNS resolve succeeds [temporary]
  24. * - When a DNS resolve fails [temporary]
  25. *
  26. * When an addressmap request is made but one is already registered,
  27. * the new one is replaced only if the currently registered one has
  28. * no "new_address" (that is, it's in the process of DNS resolve),
  29. * or if the new one is permanent (expires==0 or 1).
  30. *
  31. * (We overload the 'expires' field, using "0" for mappings set via
  32. * the configuration file, "1" for mappings set from the control
  33. * interface, and other values for DNS and TrackHostExit mappings that can
  34. * expire.)
  35. *
  36. * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
  37. * any address that ends with a . followed by the key for this entry will
  38. * get remapped by it. If "dst_wildcard" is also true, then only the
  39. * matching suffix of such addresses will get replaced by new_address.
  40. */
  41. typedef struct {
  42. char *new_address;
  43. time_t expires;
  44. addressmap_entry_source_t source:3;
  45. unsigned src_wildcard:1;
  46. unsigned dst_wildcard:1;
  47. short num_resolve_failures;
  48. } addressmap_entry_t;
  49. /** Entry for mapping addresses to which virtual address we mapped them to. */
  50. typedef struct {
  51. char *ipv4_address;
  52. char *hostname_address;
  53. } virtaddress_entry_t;
  54. /** A hash table to store client-side address rewrite instructions. */
  55. static strmap_t *addressmap=NULL;
  56. /**
  57. * Table mapping addresses to which virtual address, if any, we
  58. * assigned them to.
  59. *
  60. * We maintain the following invariant: if [A,B] is in
  61. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  62. * must be in addressmap. We do not require that the converse hold:
  63. * if it fails, then we could end up mapping two virtual addresses to
  64. * the same address, which is no disaster.
  65. **/
  66. static strmap_t *virtaddress_reversemap=NULL;
  67. /** Initialize addressmap. */
  68. void
  69. addressmap_init(void)
  70. {
  71. addressmap = strmap_new();
  72. virtaddress_reversemap = strmap_new();
  73. }
  74. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  75. static void
  76. addressmap_ent_free(void *_ent)
  77. {
  78. addressmap_entry_t *ent;
  79. if (!_ent)
  80. return;
  81. ent = _ent;
  82. tor_free(ent->new_address);
  83. tor_free(ent);
  84. }
  85. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
  86. static void
  87. addressmap_virtaddress_ent_free(void *_ent)
  88. {
  89. virtaddress_entry_t *ent;
  90. if (!_ent)
  91. return;
  92. ent = _ent;
  93. tor_free(ent->ipv4_address);
  94. tor_free(ent->hostname_address);
  95. tor_free(ent);
  96. }
  97. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
  98. static void
  99. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  100. {
  101. if (ent && ent->new_address &&
  102. address_is_in_virtual_range(ent->new_address)) {
  103. virtaddress_entry_t *ve =
  104. strmap_get(virtaddress_reversemap, ent->new_address);
  105. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  106. if (ve) {
  107. if (!strcmp(address, ve->ipv4_address))
  108. tor_free(ve->ipv4_address);
  109. if (!strcmp(address, ve->hostname_address))
  110. tor_free(ve->hostname_address);
  111. if (!ve->ipv4_address && !ve->hostname_address) {
  112. tor_free(ve);
  113. strmap_remove(virtaddress_reversemap, ent->new_address);
  114. }
  115. }
  116. }
  117. }
  118. /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
  119. * client address maps. */
  120. static void
  121. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  122. {
  123. addressmap_virtaddress_remove(address, ent);
  124. addressmap_ent_free(ent);
  125. }
  126. /** Unregister all TrackHostExits mappings from any address to
  127. * *.exitname.exit. */
  128. void
  129. clear_trackexithost_mappings(const char *exitname)
  130. {
  131. char *suffix = NULL;
  132. if (!addressmap || !exitname)
  133. return;
  134. tor_asprintf(&suffix, ".%s.exit", exitname);
  135. tor_strlower(suffix);
  136. STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
  137. if (ent->source == ADDRMAPSRC_TRACKEXIT &&
  138. !strcmpend(ent->new_address, suffix)) {
  139. addressmap_ent_remove(address, ent);
  140. MAP_DEL_CURRENT(address);
  141. }
  142. } STRMAP_FOREACH_END;
  143. tor_free(suffix);
  144. }
  145. /** Remove all TRACKEXIT mappings from the addressmap for which the target
  146. * host is unknown or no longer allowed, or for which the source address
  147. * is no longer in trackexithosts. */
  148. void
  149. addressmap_clear_excluded_trackexithosts(const or_options_t *options)
  150. {
  151. const routerset_t *allow_nodes = options->ExitNodes;
  152. const routerset_t *exclude_nodes = options->ExcludeExitNodesUnion_;
  153. if (!addressmap)
  154. return;
  155. if (routerset_is_empty(allow_nodes))
  156. allow_nodes = NULL;
  157. if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
  158. return;
  159. STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
  160. size_t len;
  161. const char *target = ent->new_address, *dot;
  162. char *nodename;
  163. const node_t *node;
  164. if (!target) {
  165. /* DNS resolving in progress */
  166. continue;
  167. } else if (strcmpend(target, ".exit")) {
  168. /* Not a .exit mapping */
  169. continue;
  170. } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
  171. /* Not a trackexit mapping. */
  172. continue;
  173. }
  174. len = strlen(target);
  175. if (len < 6)
  176. continue; /* malformed. */
  177. dot = target + len - 6; /* dot now points to just before .exit */
  178. while (dot > target && *dot != '.')
  179. dot--;
  180. if (*dot == '.') dot++;
  181. nodename = tor_strndup(dot, len-5-(dot-target));;
  182. node = node_get_by_nickname(nodename, 0);
  183. tor_free(nodename);
  184. if (!node ||
  185. (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
  186. routerset_contains_node(exclude_nodes, node) ||
  187. !hostname_in_track_host_exits(options, address)) {
  188. /* We don't know this one, or we want to be rid of it. */
  189. addressmap_ent_remove(address, ent);
  190. MAP_DEL_CURRENT(address);
  191. }
  192. } STRMAP_FOREACH_END;
  193. }
  194. /** Return true iff <b>address</b> is one that we are configured to
  195. * automap on resolve according to <b>options</b>. */
  196. int
  197. addressmap_address_should_automap(const char *address,
  198. const or_options_t *options)
  199. {
  200. const smartlist_t *suffix_list = options->AutomapHostsSuffixes;
  201. if (!suffix_list)
  202. return 0;
  203. SMARTLIST_FOREACH_BEGIN(suffix_list, const char *, suffix) {
  204. if (!strcasecmpend(address, suffix))
  205. return 1;
  206. } SMARTLIST_FOREACH_END(suffix);
  207. return 0;
  208. }
  209. /** Remove all AUTOMAP mappings from the addressmap for which the
  210. * source address no longer matches AutomapHostsSuffixes, which is
  211. * no longer allowed by AutomapHostsOnResolve, or for which the
  212. * target address is no longer in the virtual network. */
  213. void
  214. addressmap_clear_invalid_automaps(const or_options_t *options)
  215. {
  216. int clear_all = !options->AutomapHostsOnResolve;
  217. const smartlist_t *suffixes = options->AutomapHostsSuffixes;
  218. if (!addressmap)
  219. return;
  220. if (!suffixes)
  221. clear_all = 1; /* This should be impossible, but let's be sure. */
  222. STRMAP_FOREACH_MODIFY(addressmap, src_address, addressmap_entry_t *, ent) {
  223. int remove = clear_all;
  224. if (ent->source != ADDRMAPSRC_AUTOMAP)
  225. continue; /* not an automap mapping. */
  226. if (!remove) {
  227. remove = ! addressmap_address_should_automap(src_address, options);
  228. }
  229. if (!remove && ! address_is_in_virtual_range(ent->new_address))
  230. remove = 1;
  231. if (remove) {
  232. addressmap_ent_remove(src_address, ent);
  233. MAP_DEL_CURRENT(src_address);
  234. }
  235. } STRMAP_FOREACH_END;
  236. }
  237. /** Remove all entries from the addressmap that were set via the
  238. * configuration file or the command line. */
  239. void
  240. addressmap_clear_configured(void)
  241. {
  242. addressmap_get_mappings(NULL, 0, 0, 0);
  243. }
  244. /** Remove all entries from the addressmap that are set to expire, ever. */
  245. void
  246. addressmap_clear_transient(void)
  247. {
  248. addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
  249. }
  250. /** Clean out entries from the addressmap cache that were
  251. * added long enough ago that they are no longer valid.
  252. */
  253. void
  254. addressmap_clean(time_t now)
  255. {
  256. addressmap_get_mappings(NULL, 2, now, 0);
  257. }
  258. /** Free all the elements in the addressmap, and free the addressmap
  259. * itself. */
  260. void
  261. addressmap_free_all(void)
  262. {
  263. strmap_free(addressmap, addressmap_ent_free);
  264. addressmap = NULL;
  265. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  266. virtaddress_reversemap = NULL;
  267. }
  268. /** Try to find a match for AddressMap expressions that use
  269. * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
  270. * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
  271. * Return the matching entry in AddressMap or NULL if no match is found.
  272. * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
  273. * to 'a' before we return the matching AddressMap entry.
  274. *
  275. * This function does not handle the case where a pattern of the form "*.c.d"
  276. * matches the address c.d -- that's done by the main addressmap_rewrite
  277. * function.
  278. */
  279. static addressmap_entry_t *
  280. addressmap_match_superdomains(char *address)
  281. {
  282. addressmap_entry_t *val;
  283. char *cp;
  284. cp = address;
  285. while ((cp = strchr(cp, '.'))) {
  286. /* cp now points to a suffix of address that begins with a . */
  287. val = strmap_get_lc(addressmap, cp+1);
  288. if (val && val->src_wildcard) {
  289. if (val->dst_wildcard)
  290. *cp = '\0';
  291. return val;
  292. }
  293. ++cp;
  294. }
  295. return NULL;
  296. }
  297. /** Look at address, and rewrite it until it doesn't want any
  298. * more rewrites; but don't get into an infinite loop.
  299. * Don't write more than maxlen chars into address. Return true if the
  300. * address changed; false otherwise. Set *<b>expires_out</b> to the
  301. * expiry time of the result, or to <b>time_max</b> if the result does
  302. * not expire.
  303. *
  304. * If <b>exit_source_out</b> is non-null, we set it as follows. If we the
  305. * address starts out as a non-exit address, and we remap it to an .exit
  306. * address at any point, then set *<b>exit_source_out</b> to the
  307. * address_entry_source_t of the first such rule. Set *<b>exit_source_out</b>
  308. * to ADDRMAPSRC_NONE if there is no such rewrite, or if the original address
  309. * was a .exit.
  310. */
  311. int
  312. addressmap_rewrite(char *address, size_t maxlen,
  313. unsigned flags,
  314. time_t *expires_out,
  315. addressmap_entry_source_t *exit_source_out)
  316. {
  317. addressmap_entry_t *ent;
  318. int rewrites;
  319. time_t expires = TIME_MAX;
  320. addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
  321. char *addr_orig = tor_strdup(address);
  322. char *log_addr_orig = NULL;
  323. for (rewrites = 0; rewrites < 16; rewrites++) {
  324. int exact_match = 0;
  325. log_addr_orig = tor_strdup(escaped_safe_str_client(address));
  326. ent = strmap_get(addressmap, address);
  327. if (!ent || !ent->new_address) {
  328. ent = addressmap_match_superdomains(address);
  329. } else {
  330. if (ent->src_wildcard && !ent->dst_wildcard &&
  331. !strcasecmp(address, ent->new_address)) {
  332. /* This is a rule like *.example.com example.com, and we just got
  333. * "example.com" */
  334. goto done;
  335. }
  336. exact_match = 1;
  337. }
  338. if (!ent || !ent->new_address) {
  339. goto done;
  340. }
  341. if (ent && ent->source == ADDRMAPSRC_DNS) {
  342. sa_family_t f;
  343. tor_addr_t tmp;
  344. f = tor_addr_parse(&tmp, ent->new_address);
  345. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  346. goto done;
  347. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  348. goto done;
  349. }
  350. if (ent->dst_wildcard && !exact_match) {
  351. strlcat(address, ".", maxlen);
  352. strlcat(address, ent->new_address, maxlen);
  353. } else {
  354. strlcpy(address, ent->new_address, maxlen);
  355. }
  356. if (!strcmpend(address, ".exit") &&
  357. strcmpend(addr_orig, ".exit") &&
  358. exit_source == ADDRMAPSRC_NONE) {
  359. exit_source = ent->source;
  360. }
  361. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  362. log_addr_orig, escaped_safe_str_client(address));
  363. if (ent->expires > 1 && ent->expires < expires)
  364. expires = ent->expires;
  365. tor_free(log_addr_orig);
  366. }
  367. log_warn(LD_CONFIG,
  368. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  369. escaped_safe_str_client(address));
  370. /* it's fine to rewrite a rewrite, but don't loop forever */
  371. done:
  372. tor_free(addr_orig);
  373. tor_free(log_addr_orig);
  374. if (exit_source_out)
  375. *exit_source_out = exit_source;
  376. if (expires_out)
  377. *expires_out = TIME_MAX;
  378. return (rewrites > 0);
  379. }
  380. /** If we have a cached reverse DNS entry for the address stored in the
  381. * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
  382. * rewrite to the cached value and return 1. Otherwise return 0. Set
  383. * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
  384. * if the result does not expire. */
  385. int
  386. addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags,
  387. time_t *expires_out)
  388. {
  389. char *s, *cp;
  390. addressmap_entry_t *ent;
  391. int r = 0;
  392. {
  393. sa_family_t f;
  394. tor_addr_t tmp;
  395. f = tor_addr_parse(&tmp, address);
  396. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  397. return 0;
  398. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  399. return 0;
  400. }
  401. tor_asprintf(&s, "REVERSE[%s]", address);
  402. ent = strmap_get(addressmap, s);
  403. if (ent) {
  404. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  405. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  406. escaped_safe_str_client(s), cp);
  407. tor_free(cp);
  408. strlcpy(address, ent->new_address, maxlen);
  409. r = 1;
  410. }
  411. if (expires_out)
  412. *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
  413. tor_free(s);
  414. return r;
  415. }
  416. /** Return 1 if <b>address</b> is already registered, else return 0. If address
  417. * is already registered, and <b>update_expires</b> is non-zero, then update
  418. * the expiry time on the mapping with update_expires if it is a
  419. * mapping created by TrackHostExits. */
  420. int
  421. addressmap_have_mapping(const char *address, int update_expiry)
  422. {
  423. addressmap_entry_t *ent;
  424. if (!(ent=strmap_get_lc(addressmap, address)))
  425. return 0;
  426. if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
  427. ent->expires=time(NULL) + update_expiry;
  428. return 1;
  429. }
  430. /** Register a request to map <b>address</b> to <b>new_address</b>,
  431. * which will expire on <b>expires</b> (or 0 if never expires from
  432. * config file, 1 if never expires from controller, 2 if never expires
  433. * (virtual address mapping) from the controller.)
  434. *
  435. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  436. * free as appropriate. We will leave address alone.
  437. *
  438. * If <b>wildcard_addr</b> is true, then the mapping will match any address
  439. * equal to <b>address</b>, or any address ending with a period followed by
  440. * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
  441. * both true, the mapping will rewrite addresses that end with
  442. * ".<b>address</b>" into ones that end with ".<b>new_address</b>."
  443. *
  444. * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
  445. * <b>address</b> and <b>wildcard_addr</b> is equal to
  446. * <b>wildcard_new_addr</b>, remove any mappings that exist from
  447. * <b>address</b>.
  448. *
  449. *
  450. * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
  451. * not set. */
  452. void
  453. addressmap_register(const char *address, char *new_address, time_t expires,
  454. addressmap_entry_source_t source,
  455. const int wildcard_addr,
  456. const int wildcard_new_addr)
  457. {
  458. addressmap_entry_t *ent;
  459. if (wildcard_new_addr)
  460. tor_assert(wildcard_addr);
  461. ent = strmap_get(addressmap, address);
  462. if (!new_address || (!strcasecmp(address,new_address) &&
  463. wildcard_addr == wildcard_new_addr)) {
  464. /* Remove the mapping, if any. */
  465. tor_free(new_address);
  466. if (ent) {
  467. addressmap_ent_remove(address,ent);
  468. strmap_remove(addressmap, address);
  469. }
  470. return;
  471. }
  472. if (!ent) { /* make a new one and register it */
  473. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  474. strmap_set(addressmap, address, ent);
  475. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  476. if (expires > 1) {
  477. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  478. "since it's already mapped to '%s'",
  479. safe_str_client(address),
  480. safe_str_client(new_address),
  481. safe_str_client(ent->new_address));
  482. tor_free(new_address);
  483. return;
  484. }
  485. if (address_is_in_virtual_range(ent->new_address) &&
  486. expires != 2) {
  487. /* XXX This isn't the perfect test; we want to avoid removing
  488. * mappings set from the control interface _as virtual mapping */
  489. addressmap_virtaddress_remove(address, ent);
  490. }
  491. tor_free(ent->new_address);
  492. } /* else { we have an in-progress resolve with no mapping. } */
  493. ent->new_address = new_address;
  494. ent->expires = expires==2 ? 1 : expires;
  495. ent->num_resolve_failures = 0;
  496. ent->source = source;
  497. ent->src_wildcard = wildcard_addr ? 1 : 0;
  498. ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
  499. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  500. safe_str_client(address),
  501. safe_str_client(ent->new_address));
  502. control_event_address_mapped(address, ent->new_address, expires, NULL);
  503. }
  504. /** An attempt to resolve <b>address</b> failed at some OR.
  505. * Increment the number of resolve failures we have on record
  506. * for it, and then return that number.
  507. */
  508. int
  509. client_dns_incr_failures(const char *address)
  510. {
  511. addressmap_entry_t *ent = strmap_get(addressmap, address);
  512. if (!ent) {
  513. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  514. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  515. strmap_set(addressmap,address,ent);
  516. }
  517. if (ent->num_resolve_failures < SHORT_MAX)
  518. ++ent->num_resolve_failures; /* don't overflow */
  519. log_info(LD_APP, "Address %s now has %d resolve failures.",
  520. safe_str_client(address),
  521. ent->num_resolve_failures);
  522. return ent->num_resolve_failures;
  523. }
  524. /** If <b>address</b> is in the client DNS addressmap, reset
  525. * the number of resolve failures we have on record for it.
  526. * This is used when we fail a stream because it won't resolve:
  527. * otherwise future attempts on that address will only try once.
  528. */
  529. void
  530. client_dns_clear_failures(const char *address)
  531. {
  532. addressmap_entry_t *ent = strmap_get(addressmap, address);
  533. if (ent)
  534. ent->num_resolve_failures = 0;
  535. }
  536. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  537. * We can now use this in subsequent streams via addressmap_rewrite()
  538. * so we can more correctly choose an exit that will allow <b>address</b>.
  539. *
  540. * If <b>exitname</b> is defined, then append the addresses with
  541. * ".exitname.exit" before registering the mapping.
  542. *
  543. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  544. * <b>ttl</b>seconds; otherwise, we use the default.
  545. */
  546. static void
  547. client_dns_set_addressmap_impl(entry_connection_t *for_conn,
  548. const char *address, const char *name,
  549. const char *exitname,
  550. int ttl)
  551. {
  552. char *extendedaddress=NULL, *extendedval=NULL;
  553. (void)for_conn;
  554. tor_assert(address);
  555. tor_assert(name);
  556. if (ttl<0)
  557. ttl = DEFAULT_DNS_TTL;
  558. else
  559. ttl = dns_clip_ttl(ttl);
  560. if (exitname) {
  561. /* XXXX fails to ever get attempts to get an exit address of
  562. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  563. * won't make strict RFC952-compliant applications (like us) barf. */
  564. tor_asprintf(&extendedaddress,
  565. "%s.%s.exit", address, exitname);
  566. tor_asprintf(&extendedval,
  567. "%s.%s.exit", name, exitname);
  568. } else {
  569. tor_asprintf(&extendedaddress,
  570. "%s", address);
  571. tor_asprintf(&extendedval,
  572. "%s", name);
  573. }
  574. addressmap_register(extendedaddress, extendedval,
  575. time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
  576. tor_free(extendedaddress);
  577. }
  578. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  579. * We can now use this in subsequent streams via addressmap_rewrite()
  580. * so we can more correctly choose an exit that will allow <b>address</b>.
  581. *
  582. * If <b>exitname</b> is defined, then append the addresses with
  583. * ".exitname.exit" before registering the mapping.
  584. *
  585. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  586. * <b>ttl</b>seconds; otherwise, we use the default.
  587. */
  588. void
  589. client_dns_set_addressmap(entry_connection_t *for_conn,
  590. const char *address,
  591. const tor_addr_t *val,
  592. const char *exitname,
  593. int ttl)
  594. {
  595. tor_addr_t addr_tmp;
  596. char valbuf[TOR_ADDR_BUF_LEN];
  597. tor_assert(address);
  598. tor_assert(val);
  599. if (tor_addr_parse(&addr_tmp, address) >= 0)
  600. return; /* If address was an IP address already, don't add a mapping. */
  601. if (tor_addr_family(val) == AF_INET) {
  602. if (! for_conn->cache_ipv4_answers)
  603. return;
  604. } else if (tor_addr_family(val) == AF_INET6) {
  605. if (! for_conn->cache_ipv6_answers)
  606. return;
  607. }
  608. if (! tor_addr_to_str(valbuf, val, sizeof(valbuf), 1))
  609. return;
  610. client_dns_set_addressmap_impl(for_conn, address, valbuf, exitname, ttl);
  611. }
  612. /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
  613. * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
  614. *
  615. * If <b>exitname</b> is defined, then append the addresses with
  616. * ".exitname.exit" before registering the mapping.
  617. *
  618. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  619. * <b>ttl</b>seconds; otherwise, we use the default.
  620. */
  621. void
  622. client_dns_set_reverse_addressmap(entry_connection_t *for_conn,
  623. const char *address, const char *v,
  624. const char *exitname,
  625. int ttl)
  626. {
  627. char *s = NULL;
  628. {
  629. tor_addr_t tmp_addr;
  630. sa_family_t f = tor_addr_parse(&tmp_addr, address);
  631. if ((f == AF_INET && ! for_conn->cache_ipv4_answers) ||
  632. (f == AF_INET6 && ! for_conn->cache_ipv6_answers))
  633. return;
  634. }
  635. tor_asprintf(&s, "REVERSE[%s]", address);
  636. client_dns_set_addressmap_impl(for_conn, s, v, exitname, ttl);
  637. tor_free(s);
  638. }
  639. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  640. * These addresses should map to localhost, so even if the
  641. * application accidentally tried to connect to them directly (not
  642. * via Tor), it wouldn't get too far astray.
  643. *
  644. * These options are configured by parse_virtual_addr_network().
  645. */
  646. /** Which network should we use for virtual IPv4 addresses? Only the first
  647. * bits of this value are fixed. */
  648. static uint32_t virtual_addr_network = 0x7fc00000u;
  649. /** How many bits of <b>virtual_addr_network</b> are fixed? */
  650. static maskbits_t virtual_addr_netmask_bits = 10;
  651. /** What's the next virtual address we will hand out? */
  652. static uint32_t next_virtual_addr = 0x7fc00000u;
  653. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  654. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  655. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  656. * string and return -1 on failure. If validate_only is false, sets the
  657. * actual virtual address range to the parsed value. */
  658. int
  659. parse_virtual_addr_network(const char *val, int validate_only,
  660. char **msg)
  661. {
  662. uint32_t addr;
  663. uint16_t port_min, port_max;
  664. maskbits_t bits;
  665. if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
  666. if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
  667. return -1;
  668. }
  669. if (port_min != 1 || port_max != 65535) {
  670. if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
  671. return -1;
  672. }
  673. if (bits > 16) {
  674. if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
  675. "network or larger");
  676. return -1;
  677. }
  678. if (validate_only)
  679. return 0;
  680. virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
  681. virtual_addr_netmask_bits = bits;
  682. if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
  683. next_virtual_addr = addr;
  684. return 0;
  685. }
  686. /**
  687. * Return true iff <b>addr</b> is likely to have been returned by
  688. * client_dns_get_unused_address.
  689. **/
  690. int
  691. address_is_in_virtual_range(const char *address)
  692. {
  693. struct in_addr in;
  694. tor_assert(address);
  695. if (!strcasecmpend(address, ".virtual")) {
  696. return 1;
  697. } else if (tor_inet_aton(address, &in)) {
  698. uint32_t addr = ntohl(in.s_addr);
  699. if (!addr_mask_cmp_bits(addr, virtual_addr_network,
  700. virtual_addr_netmask_bits))
  701. return 1;
  702. }
  703. return 0;
  704. }
  705. /** Increment the value of next_virtual_addr; reset it to the start of the
  706. * virtual address range if it wraps around.
  707. */
  708. static INLINE void
  709. increment_virtual_addr(void)
  710. {
  711. ++next_virtual_addr;
  712. if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
  713. virtual_addr_netmask_bits))
  714. next_virtual_addr = virtual_addr_network;
  715. }
  716. /** Return a newly allocated string holding an address of <b>type</b>
  717. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  718. * and that is very unlikely to be the address of any real host.
  719. *
  720. * May return NULL if we have run out of virtual addresses.
  721. */
  722. static char *
  723. addressmap_get_virtual_address(int type)
  724. {
  725. char buf[64];
  726. tor_assert(addressmap);
  727. if (type == RESOLVED_TYPE_HOSTNAME) {
  728. char rand[10];
  729. do {
  730. crypto_rand(rand, sizeof(rand));
  731. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  732. strlcat(buf, ".virtual", sizeof(buf));
  733. } while (strmap_get(addressmap, buf));
  734. return tor_strdup(buf);
  735. } else if (type == RESOLVED_TYPE_IPV4) {
  736. // This is an imperfect estimate of how many addresses are available, but
  737. // that's ok.
  738. struct in_addr in;
  739. uint32_t available = 1u << (32-virtual_addr_netmask_bits);
  740. while (available) {
  741. /* Don't hand out any .0 or .255 address. */
  742. while ((next_virtual_addr & 0xff) == 0 ||
  743. (next_virtual_addr & 0xff) == 0xff) {
  744. increment_virtual_addr();
  745. if (! --available) {
  746. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  747. return NULL;
  748. }
  749. }
  750. in.s_addr = htonl(next_virtual_addr);
  751. tor_inet_ntoa(&in, buf, sizeof(buf));
  752. if (!strmap_get(addressmap, buf)) {
  753. increment_virtual_addr();
  754. break;
  755. }
  756. increment_virtual_addr();
  757. --available;
  758. // log_info(LD_CONFIG, "%d addrs available", (int)available);
  759. if (! available) {
  760. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  761. return NULL;
  762. }
  763. }
  764. return tor_strdup(buf);
  765. } else {
  766. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  767. return NULL;
  768. }
  769. }
  770. /** A controller has requested that we map some address of type
  771. * <b>type</b> to the address <b>new_address</b>. Choose an address
  772. * that is unlikely to be used, and map it, and return it in a newly
  773. * allocated string. If another address of the same type is already
  774. * mapped to <b>new_address</b>, try to return a copy of that address.
  775. *
  776. * The string in <b>new_address</b> may be freed or inserted into a map
  777. * as appropriate. May return NULL if are out of virtual addresses.
  778. **/
  779. const char *
  780. addressmap_register_virtual_address(int type, char *new_address)
  781. {
  782. char **addrp;
  783. virtaddress_entry_t *vent;
  784. int vent_needs_to_be_added = 0;
  785. tor_assert(new_address);
  786. tor_assert(addressmap);
  787. tor_assert(virtaddress_reversemap);
  788. vent = strmap_get(virtaddress_reversemap, new_address);
  789. if (!vent) {
  790. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  791. vent_needs_to_be_added = 1;
  792. }
  793. addrp = (type == RESOLVED_TYPE_IPV4) ?
  794. &vent->ipv4_address : &vent->hostname_address;
  795. if (*addrp) {
  796. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  797. if (ent && ent->new_address &&
  798. !strcasecmp(new_address, ent->new_address)) {
  799. tor_free(new_address);
  800. tor_assert(!vent_needs_to_be_added);
  801. return tor_strdup(*addrp);
  802. } else
  803. log_warn(LD_BUG,
  804. "Internal confusion: I thought that '%s' was mapped to by "
  805. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  806. safe_str_client(new_address),
  807. safe_str_client(*addrp),
  808. safe_str_client(*addrp),
  809. ent?safe_str_client(ent->new_address):"(nothing)");
  810. }
  811. tor_free(*addrp);
  812. *addrp = addressmap_get_virtual_address(type);
  813. if (!*addrp) {
  814. tor_free(vent);
  815. tor_free(new_address);
  816. return NULL;
  817. }
  818. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  819. if (vent_needs_to_be_added)
  820. strmap_set(virtaddress_reversemap, new_address, vent);
  821. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
  822. #if 0
  823. {
  824. /* Try to catch possible bugs */
  825. addressmap_entry_t *ent;
  826. ent = strmap_get(addressmap, *addrp);
  827. tor_assert(ent);
  828. tor_assert(!strcasecmp(ent->new_address,new_address));
  829. vent = strmap_get(virtaddress_reversemap, new_address);
  830. tor_assert(vent);
  831. tor_assert(!strcasecmp(*addrp,
  832. (type == RESOLVED_TYPE_IPV4) ?
  833. vent->ipv4_address : vent->hostname_address));
  834. log_info(LD_APP, "Map from %s to %s okay.",
  835. safe_str_client(*addrp),
  836. safe_str_client(new_address));
  837. }
  838. #endif
  839. return *addrp;
  840. }
  841. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  842. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  843. * should be true if we're using this address as a client; false if we're
  844. * using it as a server.
  845. */
  846. int
  847. address_is_invalid_destination(const char *address, int client)
  848. {
  849. if (client) {
  850. if (get_options()->AllowNonRFC953Hostnames)
  851. return 0;
  852. } else {
  853. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  854. return 0;
  855. }
  856. /* It might be an IPv6 address! */
  857. {
  858. tor_addr_t a;
  859. if (tor_addr_parse(&a, address) >= 0)
  860. return 0;
  861. }
  862. while (*address) {
  863. if (TOR_ISALNUM(*address) ||
  864. *address == '-' ||
  865. *address == '.' ||
  866. *address == '_') /* Underscore is not allowed, but Windows does it
  867. * sometimes, just to thumb its nose at the IETF. */
  868. ++address;
  869. else
  870. return 1;
  871. }
  872. return 0;
  873. }
  874. /** Iterate over all address mappings which have expiry times between
  875. * min_expires and max_expires, inclusive. If sl is provided, add an
  876. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  877. * the expiry time if want_expiry is false. If sl is NULL, remove the
  878. * mappings.
  879. */
  880. void
  881. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  882. time_t max_expires, int want_expiry)
  883. {
  884. strmap_iter_t *iter;
  885. const char *key;
  886. void *val_;
  887. addressmap_entry_t *val;
  888. if (!addressmap)
  889. addressmap_init();
  890. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  891. strmap_iter_get(iter, &key, &val_);
  892. val = val_;
  893. if (val->expires >= min_expires && val->expires <= max_expires) {
  894. if (!sl) {
  895. iter = strmap_iter_next_rmv(addressmap,iter);
  896. addressmap_ent_remove(key, val);
  897. continue;
  898. } else if (val->new_address) {
  899. const char *src_wc = val->src_wildcard ? "*." : "";
  900. const char *dst_wc = val->dst_wildcard ? "*." : "";
  901. if (want_expiry) {
  902. if (val->expires < 3 || val->expires == TIME_MAX)
  903. smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
  904. src_wc, key, dst_wc, val->new_address);
  905. else {
  906. char time[ISO_TIME_LEN+1];
  907. format_iso_time(time, val->expires);
  908. smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
  909. src_wc, key, dst_wc, val->new_address,
  910. time);
  911. }
  912. } else {
  913. smartlist_add_asprintf(sl, "%s%s %s%s",
  914. src_wc, key, dst_wc, val->new_address);
  915. }
  916. }
  917. }
  918. iter = strmap_iter_next(addressmap,iter);
  919. }
  920. }