addressmap.c 36 KB

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