addressmap.c 34 KB

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