addressmap.c 37 KB

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