addressmap.c 35 KB

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