addressmap.c 32 KB

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