addressmap.c 36 KB

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