addressmap.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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. switch (ent->source) {
  350. case ADDRMAPSRC_DNS:
  351. {
  352. sa_family_t f;
  353. tor_addr_t tmp;
  354. f = tor_addr_parse(&tmp, ent->new_address);
  355. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  356. goto done;
  357. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  358. goto done;
  359. }
  360. break;
  361. case ADDRMAPSRC_CONTROLLER:
  362. case ADDRMAPSRC_TORRC:
  363. if (!(flags & AMR_FLAG_USE_MAPADDRESS))
  364. goto done;
  365. break;
  366. case ADDRMAPSRC_AUTOMAP:
  367. if (!(flags & AMR_FLAG_USE_AUTOMAP))
  368. goto done;
  369. break;
  370. case ADDRMAPSRC_TRACKEXIT:
  371. if (!(flags & AMR_FLAG_USE_TRACKEXIT))
  372. goto done;
  373. break;
  374. case ADDRMAPSRC_NONE:
  375. default:
  376. log_warn(LD_BUG, "Unknown addrmap source value %d. Ignoring it.",
  377. (int) ent->source);
  378. goto done;
  379. }
  380. if (ent->dst_wildcard && !exact_match) {
  381. strlcat(address, ".", maxlen);
  382. strlcat(address, ent->new_address, maxlen);
  383. } else {
  384. strlcpy(address, ent->new_address, maxlen);
  385. }
  386. if (!strcmpend(address, ".exit") &&
  387. strcmpend(addr_orig, ".exit") &&
  388. exit_source == ADDRMAPSRC_NONE) {
  389. exit_source = ent->source;
  390. }
  391. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  392. log_addr_orig, escaped_safe_str_client(address));
  393. if (ent->expires > 1 && ent->expires < expires)
  394. expires = ent->expires;
  395. tor_free(log_addr_orig);
  396. }
  397. log_warn(LD_CONFIG,
  398. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  399. escaped_safe_str_client(address));
  400. /* it's fine to rewrite a rewrite, but don't loop forever */
  401. done:
  402. tor_free(addr_orig);
  403. tor_free(log_addr_orig);
  404. if (exit_source_out)
  405. *exit_source_out = exit_source;
  406. if (expires_out)
  407. *expires_out = expires;
  408. return (rewrites > 0);
  409. }
  410. /** If we have a cached reverse DNS entry for the address stored in the
  411. * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
  412. * rewrite to the cached value and return 1. Otherwise return 0. Set
  413. * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
  414. * if the result does not expire. */
  415. int
  416. addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags,
  417. time_t *expires_out)
  418. {
  419. char *s, *cp;
  420. addressmap_entry_t *ent;
  421. int r = 0;
  422. {
  423. sa_family_t f;
  424. tor_addr_t tmp;
  425. f = tor_addr_parse(&tmp, address);
  426. if (f == AF_INET && !(flags & AMR_FLAG_USE_IPV4_DNS))
  427. return 0;
  428. else if (f == AF_INET6 && !(flags & AMR_FLAG_USE_IPV6_DNS))
  429. return 0;
  430. /* FFFF we should reverse-map virtual addresses even if we haven't
  431. * enabled DNS cacheing. */
  432. }
  433. tor_asprintf(&s, "REVERSE[%s]", address);
  434. ent = strmap_get(addressmap, s);
  435. if (ent) {
  436. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  437. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  438. escaped_safe_str_client(s), cp);
  439. tor_free(cp);
  440. strlcpy(address, ent->new_address, maxlen);
  441. r = 1;
  442. }
  443. if (expires_out)
  444. *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
  445. tor_free(s);
  446. return r;
  447. }
  448. /** Return 1 if <b>address</b> is already registered, else return 0. If address
  449. * is already registered, and <b>update_expires</b> is non-zero, then update
  450. * the expiry time on the mapping with update_expires if it is a
  451. * mapping created by TrackHostExits. */
  452. int
  453. addressmap_have_mapping(const char *address, int update_expiry)
  454. {
  455. addressmap_entry_t *ent;
  456. if (!(ent=strmap_get_lc(addressmap, address)))
  457. return 0;
  458. if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
  459. ent->expires=time(NULL) + update_expiry;
  460. return 1;
  461. }
  462. /** Register a request to map <b>address</b> to <b>new_address</b>,
  463. * which will expire on <b>expires</b> (or 0 if never expires from
  464. * config file, 1 if never expires from controller, 2 if never expires
  465. * (virtual address mapping) from the controller.)
  466. *
  467. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  468. * free as appropriate. We will leave address alone.
  469. *
  470. * If <b>wildcard_addr</b> is true, then the mapping will match any address
  471. * equal to <b>address</b>, or any address ending with a period followed by
  472. * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
  473. * both true, the mapping will rewrite addresses that end with
  474. * ".<b>address</b>" into ones that end with ".<b>new_address</b>".
  475. *
  476. * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
  477. * <b>address</b> and <b>wildcard_addr</b> is equal to
  478. * <b>wildcard_new_addr</b>, remove any mappings that exist from
  479. * <b>address</b>.
  480. *
  481. *
  482. * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
  483. * not set. */
  484. void
  485. addressmap_register(const char *address, char *new_address, time_t expires,
  486. addressmap_entry_source_t source,
  487. const int wildcard_addr,
  488. const int wildcard_new_addr)
  489. {
  490. addressmap_entry_t *ent;
  491. if (wildcard_new_addr)
  492. tor_assert(wildcard_addr);
  493. ent = strmap_get(addressmap, address);
  494. if (!new_address || (!strcasecmp(address,new_address) &&
  495. wildcard_addr == wildcard_new_addr)) {
  496. /* Remove the mapping, if any. */
  497. tor_free(new_address);
  498. if (ent) {
  499. addressmap_ent_remove(address,ent);
  500. strmap_remove(addressmap, address);
  501. }
  502. return;
  503. }
  504. if (!ent) { /* make a new one and register it */
  505. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  506. strmap_set(addressmap, address, ent);
  507. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  508. if (expires > 1) {
  509. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  510. "since it's already mapped to '%s'",
  511. safe_str_client(address),
  512. safe_str_client(new_address),
  513. safe_str_client(ent->new_address));
  514. tor_free(new_address);
  515. return;
  516. }
  517. if (address_is_in_virtual_range(ent->new_address) &&
  518. expires != 2) {
  519. /* XXX This isn't the perfect test; we want to avoid removing
  520. * mappings set from the control interface _as virtual mapping */
  521. addressmap_virtaddress_remove(address, ent);
  522. }
  523. tor_free(ent->new_address);
  524. } /* else { we have an in-progress resolve with no mapping. } */
  525. ent->new_address = new_address;
  526. ent->expires = expires==2 ? 1 : expires;
  527. ent->num_resolve_failures = 0;
  528. ent->source = source;
  529. ent->src_wildcard = wildcard_addr ? 1 : 0;
  530. ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
  531. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  532. safe_str_client(address),
  533. safe_str_client(ent->new_address));
  534. control_event_address_mapped(address, ent->new_address, expires, NULL, 1);
  535. }
  536. /** An attempt to resolve <b>address</b> failed at some OR.
  537. * Increment the number of resolve failures we have on record
  538. * for it, and then return that number.
  539. */
  540. int
  541. client_dns_incr_failures(const char *address)
  542. {
  543. addressmap_entry_t *ent = strmap_get(addressmap, address);
  544. if (!ent) {
  545. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  546. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  547. strmap_set(addressmap,address,ent);
  548. }
  549. if (ent->num_resolve_failures < SHORT_MAX)
  550. ++ent->num_resolve_failures; /* don't overflow */
  551. log_info(LD_APP, "Address %s now has %d resolve failures.",
  552. safe_str_client(address),
  553. ent->num_resolve_failures);
  554. return ent->num_resolve_failures;
  555. }
  556. /** If <b>address</b> is in the client DNS addressmap, reset
  557. * the number of resolve failures we have on record for it.
  558. * This is used when we fail a stream because it won't resolve:
  559. * otherwise future attempts on that address will only try once.
  560. */
  561. void
  562. client_dns_clear_failures(const char *address)
  563. {
  564. addressmap_entry_t *ent = strmap_get(addressmap, address);
  565. if (ent)
  566. ent->num_resolve_failures = 0;
  567. }
  568. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  569. * We can now use this in subsequent streams via addressmap_rewrite()
  570. * so we can more correctly choose an exit that will allow <b>address</b>.
  571. *
  572. * If <b>exitname</b> is defined, then append the addresses with
  573. * ".exitname.exit" before registering the mapping.
  574. *
  575. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  576. * <b>ttl</b>seconds; otherwise, we use the default.
  577. */
  578. static void
  579. client_dns_set_addressmap_impl(entry_connection_t *for_conn,
  580. const char *address, const char *name,
  581. const char *exitname,
  582. int ttl)
  583. {
  584. char *extendedaddress=NULL, *extendedval=NULL;
  585. (void)for_conn;
  586. tor_assert(address);
  587. tor_assert(name);
  588. if (ttl<0)
  589. ttl = DEFAULT_DNS_TTL;
  590. else
  591. ttl = dns_clip_ttl(ttl);
  592. if (exitname) {
  593. /* XXXX fails to ever get attempts to get an exit address of
  594. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  595. * won't make strict RFC952-compliant applications (like us) barf. */
  596. tor_asprintf(&extendedaddress,
  597. "%s.%s.exit", address, exitname);
  598. tor_asprintf(&extendedval,
  599. "%s.%s.exit", name, exitname);
  600. } else {
  601. tor_asprintf(&extendedaddress,
  602. "%s", address);
  603. tor_asprintf(&extendedval,
  604. "%s", name);
  605. }
  606. addressmap_register(extendedaddress, extendedval,
  607. time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
  608. tor_free(extendedaddress);
  609. }
  610. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  611. * We can now use this in subsequent streams via addressmap_rewrite()
  612. * so we can more correctly choose an exit that will allow <b>address</b>.
  613. *
  614. * If <b>exitname</b> is defined, then append the addresses with
  615. * ".exitname.exit" before registering the mapping.
  616. *
  617. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  618. * <b>ttl</b>seconds; otherwise, we use the default.
  619. */
  620. void
  621. client_dns_set_addressmap(entry_connection_t *for_conn,
  622. const char *address,
  623. const tor_addr_t *val,
  624. const char *exitname,
  625. int ttl)
  626. {
  627. tor_addr_t addr_tmp;
  628. char valbuf[TOR_ADDR_BUF_LEN];
  629. tor_assert(address);
  630. tor_assert(val);
  631. if (tor_addr_parse(&addr_tmp, address) >= 0)
  632. return; /* If address was an IP address already, don't add a mapping. */
  633. if (tor_addr_family(val) == AF_INET) {
  634. if (! for_conn->cache_ipv4_answers)
  635. return;
  636. } else if (tor_addr_family(val) == AF_INET6) {
  637. if (! for_conn->cache_ipv6_answers)
  638. return;
  639. }
  640. if (! tor_addr_to_str(valbuf, val, sizeof(valbuf), 1))
  641. return;
  642. client_dns_set_addressmap_impl(for_conn, address, valbuf, exitname, ttl);
  643. }
  644. /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
  645. * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
  646. *
  647. * If <b>exitname</b> is defined, then append the addresses with
  648. * ".exitname.exit" before registering the mapping.
  649. *
  650. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  651. * <b>ttl</b>seconds; otherwise, we use the default.
  652. */
  653. void
  654. client_dns_set_reverse_addressmap(entry_connection_t *for_conn,
  655. const char *address, const char *v,
  656. const char *exitname,
  657. int ttl)
  658. {
  659. char *s = NULL;
  660. {
  661. tor_addr_t tmp_addr;
  662. sa_family_t f = tor_addr_parse(&tmp_addr, address);
  663. if ((f == AF_INET && ! for_conn->cache_ipv4_answers) ||
  664. (f == AF_INET6 && ! for_conn->cache_ipv6_answers))
  665. return;
  666. }
  667. tor_asprintf(&s, "REVERSE[%s]", address);
  668. client_dns_set_addressmap_impl(for_conn, s, v, exitname, ttl);
  669. tor_free(s);
  670. }
  671. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  672. * These addresses should map to localhost, so even if the
  673. * application accidentally tried to connect to them directly (not
  674. * via Tor), it wouldn't get too far astray.
  675. *
  676. * These options are configured by parse_virtual_addr_network().
  677. */
  678. static virtual_addr_conf_t virtaddr_conf_ipv4;
  679. static virtual_addr_conf_t virtaddr_conf_ipv6;
  680. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  681. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  682. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  683. * string and return -1 on failure. If validate_only is false, sets the
  684. * actual virtual address range to the parsed value. */
  685. int
  686. parse_virtual_addr_network(const char *val, sa_family_t family,
  687. int validate_only,
  688. char **msg)
  689. {
  690. const int ipv6 = (family == AF_INET6);
  691. tor_addr_t addr;
  692. maskbits_t bits;
  693. const int max_bits = ipv6 ? 40 : 16;
  694. virtual_addr_conf_t *conf = ipv6 ? &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  695. if (tor_addr_parse_mask_ports(val, 0, &addr, &bits, NULL, NULL) < 0) {
  696. if (msg)
  697. tor_asprintf(msg, "Error parsing VirtualAddressNetwork%s %s",
  698. ipv6?"IPv6":"", val);
  699. return -1;
  700. }
  701. if (tor_addr_family(&addr) != family) {
  702. if (msg)
  703. tor_asprintf(msg, "Incorrect address type for VirtualAddressNetwork%s",
  704. ipv6?"IPv6":"");
  705. return -1;
  706. }
  707. #if 0
  708. if (port_min != 1 || port_max != 65535) {
  709. if (msg)
  710. tor_asprintf(msg, "Can't specify ports on VirtualAddressNetwork%s",
  711. ipv6?"IPv6":"");
  712. return -1;
  713. }
  714. #endif
  715. if (bits > max_bits) {
  716. if (msg)
  717. tor_asprintf(msg, "VirtualAddressNetwork%s expects a /%d "
  718. "network or larger",ipv6?"IPv6":"", max_bits);
  719. return -1;
  720. }
  721. if (validate_only)
  722. return 0;
  723. tor_addr_copy(&conf->addr, &addr);
  724. conf->bits = bits;
  725. return 0;
  726. }
  727. /**
  728. * Return true iff <b>addr</b> is likely to have been returned by
  729. * client_dns_get_unused_address.
  730. **/
  731. int
  732. address_is_in_virtual_range(const char *address)
  733. {
  734. tor_addr_t addr;
  735. tor_assert(address);
  736. if (!strcasecmpend(address, ".virtual")) {
  737. return 1;
  738. } else if (tor_addr_parse(&addr, address) >= 0) {
  739. const virtual_addr_conf_t *conf = (tor_addr_family(&addr) == AF_INET6) ?
  740. &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  741. if (tor_addr_compare_masked(&addr, &conf->addr, conf->bits, CMP_EXACT)==0)
  742. return 1;
  743. }
  744. return 0;
  745. }
  746. /** Return a random address conforming to the virtual address configuration
  747. * in <b>conf</b>.
  748. */
  749. STATIC void
  750. get_random_virtual_addr(const virtual_addr_conf_t *conf, tor_addr_t *addr_out)
  751. {
  752. uint8_t tmp[4];
  753. const uint8_t *addr_bytes;
  754. uint8_t bytes[16];
  755. const int ipv6 = tor_addr_family(&conf->addr) == AF_INET6;
  756. const int total_bytes = ipv6 ? 16 : 4;
  757. tor_assert(conf->bits <= total_bytes * 8);
  758. /* Set addr_bytes to the bytes of the virtual network, in host order */
  759. if (ipv6) {
  760. addr_bytes = tor_addr_to_in6_addr8(&conf->addr);
  761. } else {
  762. set_uint32(tmp, tor_addr_to_ipv4n(&conf->addr));
  763. addr_bytes = tmp;
  764. }
  765. /* Get an appropriate number of random bytes. */
  766. crypto_rand((char*)bytes, total_bytes);
  767. /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
  768. if (conf->bits >= 8)
  769. memcpy(bytes, addr_bytes, conf->bits / 8);
  770. if (conf->bits & 7) {
  771. uint8_t mask = 0xff >> (conf->bits & 7);
  772. bytes[conf->bits/8] &= mask;
  773. bytes[conf->bits/8] |= addr_bytes[conf->bits/8] & ~mask;
  774. }
  775. if (ipv6)
  776. tor_addr_from_ipv6_bytes(addr_out, (char*) bytes);
  777. else
  778. tor_addr_from_ipv4n(addr_out, get_uint32(bytes));
  779. tor_assert(tor_addr_compare_masked(addr_out, &conf->addr,
  780. conf->bits, CMP_EXACT)==0);
  781. }
  782. /** Return a newly allocated string holding an address of <b>type</b>
  783. * (one of RESOLVED_TYPE_{IPV4|IPV6|HOSTNAME}) that has not yet been
  784. * mapped, and that is very unlikely to be the address of any real host.
  785. *
  786. * May return NULL if we have run out of virtual addresses.
  787. */
  788. static char *
  789. addressmap_get_virtual_address(int type)
  790. {
  791. char buf[64];
  792. tor_assert(addressmap);
  793. if (type == RESOLVED_TYPE_HOSTNAME) {
  794. char rand[10];
  795. do {
  796. crypto_rand(rand, sizeof(rand));
  797. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  798. strlcat(buf, ".virtual", sizeof(buf));
  799. } while (strmap_get(addressmap, buf));
  800. return tor_strdup(buf);
  801. } else if (type == RESOLVED_TYPE_IPV4 || type == RESOLVED_TYPE_IPV6) {
  802. const int ipv6 = (type == RESOLVED_TYPE_IPV6);
  803. const virtual_addr_conf_t *conf = ipv6 ?
  804. &virtaddr_conf_ipv6 : &virtaddr_conf_ipv4;
  805. /* Don't try more than 1000 times. This gives us P < 1e-9 for
  806. * failing to get a good address so long as the address space is
  807. * less than ~97.95% full. That's always going to be true under
  808. * sensible circumstances for an IPv6 /10, and it's going to be
  809. * true for an IPv4 /10 as long as we've handed out less than
  810. * 4.08 million addresses. */
  811. uint32_t attempts = 1000;
  812. tor_addr_t addr;
  813. while (attempts--) {
  814. get_random_virtual_addr(conf, &addr);
  815. if (!ipv6) {
  816. /* Don't hand out any .0 or .255 address. */
  817. const uint32_t a = tor_addr_to_ipv4h(&addr);
  818. if ((a & 0xff) == 0 || (a & 0xff) == 0xff)
  819. continue;
  820. }
  821. tor_addr_to_str(buf, &addr, sizeof(buf), 1);
  822. if (!strmap_get(addressmap, buf)) {
  823. /* XXXX This code is to make sure I didn't add an undecorated version
  824. * by mistake. I hope it's needless. */
  825. char tmp[TOR_ADDR_BUF_LEN];
  826. tor_addr_to_str(tmp, &addr, sizeof(tmp), 0);
  827. if (strmap_get(addressmap, tmp)) {
  828. log_warn(LD_BUG, "%s wasn't in the addressmap, but %s was.",
  829. buf, tmp);
  830. continue;
  831. }
  832. return tor_strdup(buf);
  833. }
  834. }
  835. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  836. return NULL;
  837. } else {
  838. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  839. return NULL;
  840. }
  841. }
  842. /** A controller has requested that we map some address of type
  843. * <b>type</b> to the address <b>new_address</b>. Choose an address
  844. * that is unlikely to be used, and map it, and return it in a newly
  845. * allocated string. If another address of the same type is already
  846. * mapped to <b>new_address</b>, try to return a copy of that address.
  847. *
  848. * The string in <b>new_address</b> may be freed or inserted into a map
  849. * as appropriate. May return NULL if are out of virtual addresses.
  850. **/
  851. const char *
  852. addressmap_register_virtual_address(int type, char *new_address)
  853. {
  854. char **addrp;
  855. virtaddress_entry_t *vent;
  856. int vent_needs_to_be_added = 0;
  857. tor_assert(new_address);
  858. tor_assert(addressmap);
  859. tor_assert(virtaddress_reversemap);
  860. vent = strmap_get(virtaddress_reversemap, new_address);
  861. if (!vent) {
  862. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  863. vent_needs_to_be_added = 1;
  864. }
  865. if (type == RESOLVED_TYPE_IPV4)
  866. addrp = &vent->ipv4_address;
  867. else if (type == RESOLVED_TYPE_IPV6)
  868. addrp = &vent->ipv6_address;
  869. else
  870. addrp = &vent->hostname_address;
  871. if (*addrp) {
  872. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  873. if (ent && ent->new_address &&
  874. !strcasecmp(new_address, ent->new_address)) {
  875. tor_free(new_address);
  876. tor_assert(!vent_needs_to_be_added);
  877. return tor_strdup(*addrp);
  878. } else {
  879. log_warn(LD_BUG,
  880. "Internal confusion: I thought that '%s' was mapped to by "
  881. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  882. safe_str_client(new_address),
  883. safe_str_client(*addrp),
  884. safe_str_client(*addrp),
  885. ent?safe_str_client(ent->new_address):"(nothing)");
  886. }
  887. }
  888. tor_free(*addrp);
  889. *addrp = addressmap_get_virtual_address(type);
  890. if (!*addrp) {
  891. tor_free(vent);
  892. tor_free(new_address);
  893. return NULL;
  894. }
  895. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  896. if (vent_needs_to_be_added)
  897. strmap_set(virtaddress_reversemap, new_address, vent);
  898. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
  899. /* FFFF register corresponding reverse mapping. */
  900. #if 0
  901. {
  902. /* Try to catch possible bugs */
  903. addressmap_entry_t *ent;
  904. ent = strmap_get(addressmap, *addrp);
  905. tor_assert(ent);
  906. tor_assert(!strcasecmp(ent->new_address,new_address));
  907. vent = strmap_get(virtaddress_reversemap, new_address);
  908. tor_assert(vent);
  909. tor_assert(!strcasecmp(*addrp,
  910. (type == RESOLVED_TYPE_IPV4) ?
  911. vent->ipv4_address : vent->hostname_address));
  912. log_info(LD_APP, "Map from %s to %s okay.",
  913. safe_str_client(*addrp),
  914. safe_str_client(new_address));
  915. }
  916. #endif
  917. return *addrp;
  918. }
  919. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  920. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  921. * should be true if we're using this address as a client; false if we're
  922. * using it as a server.
  923. */
  924. int
  925. address_is_invalid_destination(const char *address, int client)
  926. {
  927. if (client) {
  928. if (get_options()->AllowNonRFC953Hostnames)
  929. return 0;
  930. } else {
  931. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  932. return 0;
  933. }
  934. /* It might be an IPv6 address! */
  935. {
  936. tor_addr_t a;
  937. if (tor_addr_parse(&a, address) >= 0)
  938. return 0;
  939. }
  940. while (*address) {
  941. if (TOR_ISALNUM(*address) ||
  942. *address == '-' ||
  943. *address == '.' ||
  944. *address == '_') /* Underscore is not allowed, but Windows does it
  945. * sometimes, just to thumb its nose at the IETF. */
  946. ++address;
  947. else
  948. return 1;
  949. }
  950. return 0;
  951. }
  952. /** Iterate over all address mappings which have expiry times between
  953. * min_expires and max_expires, inclusive. If sl is provided, add an
  954. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  955. * the expiry time if want_expiry is false. If sl is NULL, remove the
  956. * mappings.
  957. */
  958. void
  959. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  960. time_t max_expires, int want_expiry)
  961. {
  962. strmap_iter_t *iter;
  963. const char *key;
  964. void *val_;
  965. addressmap_entry_t *val;
  966. if (!addressmap)
  967. addressmap_init();
  968. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  969. strmap_iter_get(iter, &key, &val_);
  970. val = val_;
  971. if (val->expires >= min_expires && val->expires <= max_expires) {
  972. if (!sl) {
  973. iter = strmap_iter_next_rmv(addressmap,iter);
  974. addressmap_ent_remove(key, val);
  975. continue;
  976. } else if (val->new_address) {
  977. const char *src_wc = val->src_wildcard ? "*." : "";
  978. const char *dst_wc = val->dst_wildcard ? "*." : "";
  979. if (want_expiry) {
  980. if (val->expires < 3 || val->expires == TIME_MAX)
  981. smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
  982. src_wc, key, dst_wc, val->new_address);
  983. else {
  984. char time[ISO_TIME_LEN+1];
  985. format_iso_time(time, val->expires);
  986. smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
  987. src_wc, key, dst_wc, val->new_address,
  988. time);
  989. }
  990. } else {
  991. smartlist_add_asprintf(sl, "%s%s %s%s",
  992. src_wc, key, dst_wc, val->new_address);
  993. }
  994. }
  995. }
  996. iter = strmap_iter_next(addressmap,iter);
  997. }
  998. }