addressmap.c 34 KB

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