addressmap.c 34 KB

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