addressmap.c 31 KB

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