addressmap.c 34 KB

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