addressmap.c 34 KB

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