Tor  0.4.8.0-alpha-dev
policies.c
Go to the documentation of this file.
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3  * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
6 /**
7  * \file policies.c
8  * \brief Code to parse and use address policies and exit policies.
9  *
10  * We have two key kinds of address policy: full and compressed. A full
11  * policy is an array of accept/reject patterns, to be applied in order.
12  * A short policy is simply a list of ports. This module handles both
13  * kinds, including generic functions to apply them to addresses, and
14  * also including code to manage the global policies that we apply to
15  * incoming and outgoing connections.
16  **/
17 
18 #define POLICIES_PRIVATE
19 
20 #include "core/or/or.h"
21 #include "feature/client/bridges.h"
22 #include "app/config/config.h"
23 #include "core/or/policies.h"
28 #include "feature/relay/router.h"
30 #include "lib/geoip/geoip.h"
31 #include "ht.h"
33 #include "lib/encoding/confline.h"
34 #include "trunnel/ed25519_cert.h"
35 
36 #include "core/or/addr_policy_st.h"
40 #include "core/or/port_cfg_st.h"
43 
44 /** Maximum length of an exit policy summary. */
45 #define MAX_EXITPOLICY_SUMMARY_LEN 1000
46 
47 /** Policy that addresses for incoming SOCKS connections must match. */
48 static smartlist_t *socks_policy = NULL;
49 /** Policy that addresses for incoming directory connections must match. */
50 static smartlist_t *dir_policy = NULL;
51 /** Policy for incoming MetricsPort connections that must match. */
52 static smartlist_t *metrics_policy = NULL;
53 /** Policy that addresses for incoming router descriptors must match in order
54  * to be published by us. */
56 /** Policy that addresses for incoming router descriptors must match in order
57  * to be marked as valid in our networkstatus. */
59 /** Policy that addresses for incoming router descriptors must <b>not</b>
60  * match in order to not be marked as BadExit. */
62 /** Policy that addresses for incoming router descriptors must <b>not</b>
63  * match in order to not be marked as MiddleOnly. */
65 
66 /** Parsed addr_policy_t describing which addresses we believe we can start
67  * circuits at. */
69 /** Parsed addr_policy_t describing which addresses we believe we can connect
70  * to directories at. */
72 
73 /** Element of an exit policy summary */
74 typedef struct policy_summary_item_t {
75  uint16_t prt_min; /**< Lowest port number to accept/reject. */
76  uint16_t prt_max; /**< Highest port number to accept/reject. */
77  uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
78  this port range. */
79  unsigned int accepted:1; /** Has this port already been accepted */
81 
82 /** Private networks. This list is used in two places, once to expand the
83  * "private" keyword when parsing our own exit policy, secondly to ignore
84  * just such networks when building exit policy summaries. It is important
85  * that all authorities agree on that list when creating summaries, so don't
86  * just change this without a proper migration plan and a proposal and stuff.
87  */
88 static const char *private_nets[] = {
89  "0.0.0.0/8", "169.254.0.0/16",
90  "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
91  "[::]/8",
92  "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
93  NULL
94 };
95 
97  config_line_t *cfg,
98  smartlist_t **dest,
99  int ipv6_exit,
100  int rejectprivate,
101  const smartlist_t *configured_addresses,
102  int reject_interface_addresses,
103  int reject_configured_port_addresses,
104  int add_default_policy,
105  int add_reduced_policy);
106 
107 /** Replace all "private" entries in *<b>policy</b> with their expanded
108  * equivalents. */
109 void
111 {
112  uint16_t port_min, port_max;
113 
114  int i;
115  smartlist_t *tmp;
116 
117  if (!*policy) /*XXXX disallow NULL policies? */
118  return;
119 
120  tmp = smartlist_new();
121 
122  SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
123  if (! p->is_private) {
124  smartlist_add(tmp, p);
125  continue;
126  }
127  for (i = 0; private_nets[i]; ++i) {
128  addr_policy_t newpolicy;
129  memcpy(&newpolicy, p, sizeof(addr_policy_t));
130  newpolicy.is_private = 0;
131  newpolicy.is_canonical = 0;
133  &newpolicy.addr,
134  &newpolicy.maskbits, &port_min, &port_max)<0) {
135  tor_assert_unreached();
136  }
138  }
139  addr_policy_free(p);
140  } SMARTLIST_FOREACH_END(p);
141 
142  smartlist_free(*policy);
143  *policy = tmp;
144 }
145 
146 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
147  * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
148  * specific and one IPv6-specific. */
149 void
151 {
152  smartlist_t *tmp;
153  if (!*policy)
154  return;
155 
156  tmp = smartlist_new();
157  SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
158  sa_family_t family = tor_addr_family(&p->addr);
159  if (family == AF_INET6 || family == AF_INET || p->is_private) {
160  smartlist_add(tmp, p);
161  } else if (family == AF_UNSPEC) {
162  addr_policy_t newpolicy_ipv4;
163  addr_policy_t newpolicy_ipv6;
164  memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
165  memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
166  newpolicy_ipv4.is_canonical = 0;
167  newpolicy_ipv6.is_canonical = 0;
168  if (p->maskbits != 0) {
169  log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
170  newpolicy_ipv4.maskbits = 0;
171  newpolicy_ipv6.maskbits = 0;
172  }
173  tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
174  tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
175  (const uint8_t *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
176  smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
177  smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
178  addr_policy_free(p);
179  } else {
180  log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
181  smartlist_add(tmp, p);
182  }
183  } SMARTLIST_FOREACH_END(p);
184 
185  smartlist_free(*policy);
186  *policy = tmp;
187 }
188 
189 /**
190  * Given a linked list of config lines containing "accept[6]" and "reject[6]"
191  * tokens, parse them and append the result to <b>dest</b>. Return -1
192  * if any tokens are malformed (and don't append any), else return 0.
193  *
194  * If <b>assume_action</b> is nonnegative, then insert its action
195  * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
196  * action.
197  */
198 static int
200  int assume_action)
201 {
202  smartlist_t *result;
203  smartlist_t *entries;
204  addr_policy_t *item;
205  int malformed_list;
206  int r = 0;
207 
208  if (!cfg)
209  return 0;
210 
211  result = smartlist_new();
212  entries = smartlist_new();
213  for (; cfg; cfg = cfg->next) {
214  smartlist_split_string(entries, cfg->value, ",",
215  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
216  SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
217  log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
218  malformed_list = 0;
219  item = router_parse_addr_policy_item_from_string(ent, assume_action,
220  &malformed_list);
221  if (item) {
222  smartlist_add(result, item);
223  } else if (malformed_list) {
224  /* the error is so severe the entire list should be discarded */
225  log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
226  "list.", ent);
227  r = -1;
228  } else {
229  /* the error is minor: don't add the item, but keep processing the
230  * rest of the policies in the list */
231  log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
232  "The remainder of the policy list will be used.",
233  ent);
234  }
235  } SMARTLIST_FOREACH_END(ent);
236  SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
237  smartlist_clear(entries);
238  }
239  smartlist_free(entries);
240  if (r == -1) {
241  addr_policy_list_free(result);
242  } else {
243  policy_expand_private(&result);
244  policy_expand_unspec(&result);
245 
246  if (*dest) {
247  smartlist_add_all(*dest, result);
248  smartlist_free(result);
249  } else {
250  *dest = result;
251  }
252  }
253 
254  return r;
255 }
256 
257 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
258  * reachable_(or|dir)_addr_policy. The options should already have
259  * been validated by validate_addr_policies.
260  */
261 static int
263 {
264  const or_options_t *options = get_options();
265  int ret = 0;
266 
267  if (options->ReachableDirAddresses &&
268  options->ReachableORAddresses &&
269  options->ReachableAddresses) {
270  log_warn(LD_CONFIG,
271  "Both ReachableDirAddresses and ReachableORAddresses are set. "
272  "ReachableAddresses setting will be ignored.");
273  }
274  addr_policy_list_free(reachable_or_addr_policy);
276  if (!options->ReachableORAddresses && options->ReachableAddresses)
277  log_info(LD_CONFIG,
278  "Using ReachableAddresses as ReachableORAddresses.");
280  options->ReachableORAddresses :
281  options->ReachableAddresses,
282  &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
283  log_warn(LD_CONFIG,
284  "Error parsing Reachable%sAddresses entry; ignoring.",
285  options->ReachableORAddresses ? "OR" : "");
286  ret = -1;
287  }
288 
289  addr_policy_list_free(reachable_dir_addr_policy);
291  if (!options->ReachableDirAddresses && options->ReachableAddresses)
292  log_info(LD_CONFIG,
293  "Using ReachableAddresses as ReachableDirAddresses");
295  options->ReachableDirAddresses :
296  options->ReachableAddresses,
297  &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
298  if (options->ReachableDirAddresses)
299  log_warn(LD_CONFIG,
300  "Error parsing ReachableDirAddresses entry; ignoring.");
301  ret = -1;
302  }
303 
304  /* We ignore ReachableAddresses for relays */
305  if (!server_mode(options)) {
308  log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
309  "ReachableAddresses, ReachableORAddresses, or "
310  "ReachableDirAddresses reject all addresses. Please accept "
311  "some addresses in these options.");
312  } else if (options->ClientUseIPv4 == 1
315  log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
316  "ReachableAddresses, ReachableORAddresses, or "
317  "ReachableDirAddresses reject all IPv4 addresses. "
318  "Tor will not connect using IPv4.");
319  } else if (reachable_addr_use_ipv6(options)
322  log_warn(LD_CONFIG, "You have configured tor to use or prefer IPv6 "
323  "(or UseBridges 1), but "
324  "ReachableAddresses, ReachableORAddresses, or "
325  "ReachableDirAddresses reject all IPv6 addresses. "
326  "Tor will not connect using IPv6.");
327  }
328  }
329 
330  /* Append a reject *:* to reachable_(or|dir)_addr_policy */
331  if (!ret && (options->ReachableDirAddresses ||
332  options->ReachableORAddresses ||
333  options->ReachableAddresses)) {
336  }
337 
338  return ret;
339 }
340 
341 /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
342  * address:port combination. */
343 static int
344 firewall_is_fascist_impl(void)
345 {
346  const or_options_t *options = get_options();
347  /* Assume every non-bridge relay has an IPv4 address.
348  * Clients which use bridges may only know the IPv6 address of their
349  * bridge, but they will connect regardless of the ClientUseIPv6 setting. */
350  return options->ClientUseIPv4 == 0;
351 }
352 
353 /** Return true iff the firewall options, including ClientUseIPv4 0 and
354  * ClientUseIPv6 0, might block any OR address:port combination.
355  * Address preferences may still change which address is selected even if
356  * this function returns false.
357  */
358 int
360 {
361  return (reachable_or_addr_policy != NULL || firewall_is_fascist_impl());
362 }
363 
364 /** Return true iff the firewall options, including ClientUseIPv4 0 and
365  * ClientUseIPv6 0, might block any Dir address:port combination.
366  * Address preferences may still change which address is selected even if
367  * this function returns false.
368  */
369 int
371 {
372  return (reachable_dir_addr_policy != NULL || firewall_is_fascist_impl());
373 }
374 
375 /** Return true iff <b>policy</b> (possibly NULL) will allow a
376  * connection to <b>addr</b>:<b>port</b>.
377  */
378 static int
379 addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
380  smartlist_t *policy)
381 {
383  p = compare_tor_addr_to_addr_policy(addr, port, policy);
384  switch (p) {
387  return 1;
390  return 0;
391  default:
392  log_warn(LD_BUG, "Unexpected result: %d", (int)p);
393  return 0;
394  }
395 }
396 
397 /** Return true iff we think our firewall will let us make a connection to
398  * addr:port.
399  *
400  * If we are configured as a server, ignore any address family preference and
401  * just use IPv4.
402  * Otherwise:
403  * - return false for all IPv4 addresses:
404  * - if ClientUseIPv4 is 0, or
405  * if pref_only and pref_ipv6 are both true;
406  * - return false for all IPv6 addresses:
407  * - if reachable_addr_use_ipv6() is 0, or
408  * - if pref_only is true and pref_ipv6 is false.
409  *
410  * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
411 STATIC int
413  uint16_t port,
414  smartlist_t *firewall_policy,
415  int pref_only, int pref_ipv6)
416 {
417  const or_options_t *options = get_options();
418  const int client_mode = !server_mode(options);
419 
420  if (!addr || tor_addr_is_null(addr) || !port) {
421  return 0;
422  }
423 
424  /* Clients stop using IPv4 if it's disabled. In most cases, clients also
425  * stop using IPv4 if it's not preferred.
426  * Servers must have IPv4 enabled and preferred. */
427  if (tor_addr_family(addr) == AF_INET && client_mode &&
428  (!options->ClientUseIPv4 || (pref_only && pref_ipv6))) {
429  return 0;
430  }
431 
432  /* Clients and Servers won't use IPv6 unless it's enabled (and in most
433  * cases, IPv6 must also be preferred before it will be used). */
434  if (tor_addr_family(addr) == AF_INET6 &&
435  (!reachable_addr_use_ipv6(options) || (pref_only && !pref_ipv6))) {
436  return 0;
437  }
438 
439  return addr_policy_permits_tor_addr(addr, port,
440  firewall_policy);
441 }
442 
443 /** Is this client configured to use IPv6?
444  * Returns true if the client might use IPv6 for some of its connections
445  * (including dual-stack and IPv6-only clients), and false if it will never
446  * use IPv6 for any connections.
447  * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
448  * port: it supports bridge client per-node IPv6 preferences.
449  */
450 int
452 {
453  /* Clients use IPv6 if it's set, or they use bridges, or they don't use
454  * IPv4, or they prefer it.
455  * ClientPreferIPv6DirPort is deprecated, but check it anyway. */
456  return (options->ClientUseIPv6 == 1 || options->ClientUseIPv4 == 0 ||
457  options->ClientPreferIPv6ORPort == 1 ||
458  options->ClientPreferIPv6DirPort == 1 || options->UseBridges == 1);
459 }
460 
461 /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
462  * ClientPreferIPv6DirPort?
463  * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
464  */
465 static int
467 {
468  /*
469  Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
470  If we're a server or IPv6 is disabled, use IPv4.
471  If IPv4 is disabled, use IPv6.
472  */
473 
474  if (server_mode(options) || !reachable_addr_use_ipv6(options)) {
475  return 0;
476  }
477 
478  if (!options->ClientUseIPv4) {
479  return 1;
480  }
481 
482  return -1;
483 }
484 
485 /** Do we prefer to connect to IPv6 ORPorts?
486  * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
487  * per-node IPv6 preferences.
488  */
489 int
491 {
492  int pref_ipv6 = reachable_addr_prefer_ipv6_impl(options);
493 
494  if (pref_ipv6 >= 0) {
495  return pref_ipv6;
496  }
497 
498  /* We can use both IPv4 and IPv6 - which do we prefer? */
499  if (options->ClientPreferIPv6ORPort == 1) {
500  return 1;
501  }
502 
503  return 0;
504 }
505 
506 /** Do we prefer to connect to IPv6 DirPorts?
507  *
508  * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
509  * preferences. There's no reason to use it instead of this function.)
510  */
511 int
513 {
514  int pref_ipv6 = reachable_addr_prefer_ipv6_impl(options);
515 
516  if (pref_ipv6 >= 0) {
517  return pref_ipv6;
518  }
519 
520  /* We can use both IPv4 and IPv6 - which do we prefer? */
521  if (options->ClientPreferIPv6DirPort == 1) {
522  return 1;
523  }
524 
525  return 0;
526 }
527 
528 /** Return true iff we think our firewall will let us make a connection to
529  * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
530  * fw_connection.
531  * If pref_only is true, return true if addr is in the client's preferred
532  * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
533  * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
534  */
535 int
536 reachable_addr_allows_addr(const tor_addr_t *addr, uint16_t port,
537  firewall_connection_t fw_connection,
538  int pref_only, int pref_ipv6)
539 {
540  if (fw_connection == FIREWALL_OR_CONNECTION) {
541  return reachable_addr_allows(addr, port,
543  pref_only, pref_ipv6);
544  } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
545  return reachable_addr_allows(addr, port,
547  pref_only, pref_ipv6);
548  } else {
549  log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
550  fw_connection);
551  return 0;
552  }
553 }
554 
555 /** Return true iff we think our firewall will let us make a connection to
556  * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
557  * fw_connection.
558  * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
559  */
560 static int
562  firewall_connection_t fw_connection,
563  int pref_only, int pref_ipv6)
564 {
565  tor_assert(ap);
566  return reachable_addr_allows_addr(&ap->addr, ap->port,
567  fw_connection, pref_only,
568  pref_ipv6);
569 }
570 
571 /** Return true iff we think our firewall will let us make a connection to
572  * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
573  * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
574  * <b>fw_connection</b>.
575  * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
576  */
577 static int
578 reachable_addr_allows_base(const tor_addr_t *ipv4_addr, uint16_t ipv4_orport,
579  uint16_t ipv4_dirport,
580  const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
581  uint16_t ipv6_dirport,
582  firewall_connection_t fw_connection,
583  int pref_only, int pref_ipv6)
584 {
585  if (reachable_addr_allows_addr(ipv4_addr,
586  (fw_connection == FIREWALL_OR_CONNECTION
587  ? ipv4_orport
588  : ipv4_dirport),
589  fw_connection,
590  pref_only, pref_ipv6)) {
591  return 1;
592  }
593 
594  if (reachable_addr_allows_addr(ipv6_addr,
595  (fw_connection == FIREWALL_OR_CONNECTION
596  ? ipv6_orport
597  : ipv6_dirport),
598  fw_connection,
599  pref_only, pref_ipv6)) {
600  return 1;
601  }
602 
603  return 0;
604 }
605 
606 /** Like reachable_addr_allows_base(), but takes ri. */
607 static int
609  firewall_connection_t fw_connection,
610  int pref_only, int pref_ipv6)
611 {
612  if (!ri) {
613  return 0;
614  }
615 
616  /* Assume IPv4 and IPv6 DirPorts are the same */
617  return reachable_addr_allows_base(&ri->ipv4_addr, ri->ipv4_orport,
618  ri->ipv4_dirport, &ri->ipv6_addr,
619  ri->ipv6_orport, ri->ipv4_dirport,
620  fw_connection, pref_only, pref_ipv6);
621 }
622 
623 /** Like reachable_addr_allows_rs, but takes pref_ipv6. */
624 static int
626  firewall_connection_t fw_connection,
627  int pref_only, int pref_ipv6)
628 {
629  if (!rs) {
630  return 0;
631  }
632 
633  /* Assume IPv4 and IPv6 DirPorts are the same */
634  return reachable_addr_allows_base(&rs->ipv4_addr, rs->ipv4_orport,
635  rs->ipv4_dirport, &rs->ipv6_addr,
636  rs->ipv6_orport, rs->ipv4_dirport,
637  fw_connection, pref_only, pref_ipv6);
638 }
639 
640 /** Like reachable_addr_allows_base(), but takes rs.
641  * When rs is a fake_status from a dir_server_t, it can have a reachable
642  * address, even when the corresponding node does not.
643  * nodes can be missing addresses when there's no consensus (IPv4 and IPv6),
644  * or when there is a microdescriptor consensus, but no microdescriptors
645  * (microdescriptors have IPv6, the microdesc consensus does not). */
646 int
648  firewall_connection_t fw_connection, int pref_only)
649 {
650  if (!rs) {
651  return 0;
652  }
653 
654  /* We don't have access to the node-specific IPv6 preference, so use the
655  * generic IPv6 preference instead. */
656  const or_options_t *options = get_options();
657  int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
660 
661  return reachable_addr_allows_rs_impl(rs, fw_connection, pref_only,
662  pref_ipv6);
663 }
664 
665 /** Return true iff we think our firewall will let us make a connection to
666  * ipv6_addr:ipv6_orport based on ReachableORAddresses.
667  * If <b>fw_connection</b> is FIREWALL_DIR_CONNECTION, returns 0.
668  * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
669  */
670 static int
672  firewall_connection_t fw_connection,
673  int pref_only, int pref_ipv6)
674 {
675  if (!md) {
676  return 0;
677  }
678 
679  /* Can't check dirport, it doesn't have one */
680  if (fw_connection == FIREWALL_DIR_CONNECTION) {
681  return 0;
682  }
683 
684  /* Also can't check IPv4, doesn't have that either */
686  fw_connection, pref_only,
687  pref_ipv6);
688 }
689 
690 /** Like reachable_addr_allows_base(), but takes node, and looks up pref_ipv6
691  * from node_ipv6_or/dir_preferred(). */
692 int
694  firewall_connection_t fw_connection,
695  int pref_only)
696 {
697  if (!node) {
698  return 0;
699  }
700 
701  node_assert_ok(node);
702 
703  const int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
704  ? node_ipv6_or_preferred(node)
705  : node_ipv6_dir_preferred(node));
706 
707  /* Sometimes, the rs is missing the IPv6 address info, and we need to go
708  * all the way to the md */
709  if (node->ri && reachable_addr_allows_ri_impl(node->ri, fw_connection,
710  pref_only, pref_ipv6)) {
711  return 1;
712  } else if (node->rs && reachable_addr_allows_rs_impl(node->rs,
713  fw_connection,
714  pref_only,
715  pref_ipv6)) {
716  return 1;
717  } else if (node->md && reachable_addr_allows_md_impl(node->md,
718  fw_connection,
719  pref_only,
720  pref_ipv6)) {
721  return 1;
722  } else {
723  /* If we know nothing, assume it's unreachable, we'll never get an address
724  * to connect to. */
725  return 0;
726  }
727 }
728 
729 /** Like reachable_addr_allows_rs(), but takes ds. */
730 int
732  firewall_connection_t fw_connection,
733  int pref_only)
734 {
735  if (!ds) {
736  return 0;
737  }
738 
739  /* A dir_server_t always has a fake_status. As long as it has the same
740  * addresses/ports in both fake_status and dir_server_t, this works fine.
741  * (See #17867.)
742  * reachable_addr_allows_rs only checks the addresses in fake_status. */
743  return reachable_addr_allows_rs(&ds->fake_status, fw_connection,
744  pref_only);
745 }
746 
747 /** If a and b are both valid and allowed by fw_connection,
748  * choose one based on want_a and return it.
749  * Otherwise, return whichever is allowed.
750  * Otherwise, return NULL.
751  * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
752  */
753 static const tor_addr_port_t *
755  const tor_addr_port_t *b,
756  int want_a,
757  firewall_connection_t fw_connection,
758  int pref_only, int pref_ipv6)
759 {
760  const tor_addr_port_t *use_a = NULL;
761  const tor_addr_port_t *use_b = NULL;
762 
763  if (reachable_addr_allows_ap(a, fw_connection, pref_only,
764  pref_ipv6)) {
765  use_a = a;
766  }
767 
768  if (reachable_addr_allows_ap(b, fw_connection, pref_only,
769  pref_ipv6)) {
770  use_b = b;
771  }
772 
773  /* If both are allowed */
774  if (use_a && use_b) {
775  /* Choose a if we want it */
776  return (want_a ? use_a : use_b);
777  } else {
778  /* Choose a if we have it */
779  return (use_a ? use_a : use_b);
780  }
781 }
782 
783 /** If a and b are both valid and preferred by fw_connection,
784  * choose one based on want_a and return it.
785  * Otherwise, return whichever is preferred.
786  * If neither are preferred, and pref_only is false:
787  * - If a and b are both allowed by fw_connection,
788  * choose one based on want_a and return it.
789  * - Otherwise, return whichever is preferred.
790  * Otherwise, return NULL. */
791 STATIC const tor_addr_port_t *
793  const tor_addr_port_t *b,
794  int want_a,
795  firewall_connection_t fw_connection,
796  int pref_only, int pref_ipv6)
797 {
799  a, b, want_a,
800  fw_connection,
801  1, pref_ipv6);
802  if (pref_only || pref) {
803  /* If there is a preferred address, use it. If we can only use preferred
804  * addresses, and neither address is preferred, pref will be NULL, and we
805  * want to return NULL, so return it. */
806  return pref;
807  } else {
808  /* If there's no preferred address, and we can return addresses that are
809  * not preferred, use an address that's allowed */
810  return reachable_addr_choose_impl(a, b, want_a, fw_connection,
811  0, pref_ipv6);
812  }
813 }
814 
815 /** Copy an address and port into <b>ap</b> that we think our firewall will
816  * let us connect to. Uses ipv4_addr/ipv6_addr and
817  * ipv4_orport/ipv6_orport/ReachableORAddresses or
818  * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
819  * <b>fw_connection</b>.
820  * If pref_only, only choose preferred addresses. In either case, choose
821  * a preferred address before an address that's not preferred.
822  * If both addresses could be chosen (they are both preferred or both allowed)
823  * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4. */
824 static void
826  uint16_t ipv4_orport,
827  uint16_t ipv4_dirport,
828  const tor_addr_t *ipv6_addr,
829  uint16_t ipv6_orport,
830  uint16_t ipv6_dirport,
831  firewall_connection_t fw_connection,
832  int pref_only,
833  int pref_ipv6,
834  tor_addr_port_t* ap)
835 {
836  const tor_addr_port_t *result = NULL;
837  const int want_ipv4 = !pref_ipv6;
838 
839  tor_assert(ipv6_addr);
840  tor_assert(ap);
841 
842  tor_addr_make_null(&ap->addr, AF_UNSPEC);
843  ap->port = 0;
844 
845  tor_addr_port_t ipv4_ap;
846  tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
847  ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
848  ? ipv4_orport
849  : ipv4_dirport);
850 
851  tor_addr_port_t ipv6_ap;
852  tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
853  ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
854  ? ipv6_orport
855  : ipv6_dirport);
856 
857  result = reachable_addr_choose(&ipv4_ap, &ipv6_ap,
858  want_ipv4,
859  fw_connection, pref_only,
860  pref_ipv6);
861 
862  if (result) {
863  tor_addr_copy(&ap->addr, &result->addr);
864  ap->port = result->port;
865  }
866 }
867 
868 /** Like reachable_addr_choose_base(), but takes <b>rs</b>.
869  * Consults the corresponding node, then falls back to rs if node is NULL.
870  * This should only happen when there's no valid consensus, and rs doesn't
871  * correspond to a bridge client's bridge.
872  */
873 void
875  firewall_connection_t fw_connection,
876  int pref_only, tor_addr_port_t* ap)
877 {
878  tor_assert(ap);
879 
880  tor_addr_make_null(&ap->addr, AF_UNSPEC);
881  ap->port = 0;
882 
883  if (!rs) {
884  return;
885  }
886 
887  const or_options_t *options = get_options();
888  const node_t *node = node_get_by_id(rs->identity_digest);
889 
890  if (node) {
891  reachable_addr_choose_from_node(node, fw_connection, pref_only, ap);
892  } else {
893  /* There's no node-specific IPv6 preference, so use the generic IPv6
894  * preference instead. */
895  int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
898 
899  reachable_addr_choose_base(&rs->ipv4_addr, rs->ipv4_orport,
900  rs->ipv4_dirport, &rs->ipv6_addr,
901  rs->ipv6_orport, rs->ipv4_dirport,
902  fw_connection, pref_only, pref_ipv6,
903  ap);
904  }
905 }
906 
907 /** Like reachable_addr_choose_base(), but takes in a smartlist
908  * <b>lspecs</b> consisting of one or more link specifiers. We assume
909  * fw_connection is FIREWALL_OR_CONNECTION as link specifiers cannot
910  * contain DirPorts.
911  */
912 void
914  int pref_only, tor_addr_port_t* ap)
915 {
916  int have_v4 = 0, have_v6 = 0;
917  uint16_t port_v4 = 0, port_v6 = 0;
918  tor_addr_t addr_v4, addr_v6;
919 
920  tor_assert(ap);
921 
922  if (lspecs == NULL) {
923  log_warn(LD_BUG, "Unknown or missing link specifiers");
924  return;
925  }
926  if (smartlist_len(lspecs) == 0) {
927  log_warn(LD_PROTOCOL, "Link specifiers are empty");
928  return;
929  }
930 
931  tor_addr_make_null(&ap->addr, AF_UNSPEC);
932  ap->port = 0;
933 
934  tor_addr_make_null(&addr_v4, AF_INET);
935  tor_addr_make_null(&addr_v6, AF_INET6);
936 
937  SMARTLIST_FOREACH_BEGIN(lspecs, const link_specifier_t *, ls) {
938  switch (link_specifier_get_ls_type(ls)) {
939  case LS_IPV4:
940  /* Skip if we already seen a v4. */
941  if (have_v4) continue;
942  tor_addr_from_ipv4h(&addr_v4,
943  link_specifier_get_un_ipv4_addr(ls));
944  port_v4 = link_specifier_get_un_ipv4_port(ls);
945  have_v4 = 1;
946  break;
947  case LS_IPV6:
948  /* Skip if we already seen a v6, or deliberately skip it if we're not a
949  * direct connection. */
950  if (have_v6) continue;
951  tor_addr_from_ipv6_bytes(&addr_v6,
952  link_specifier_getconstarray_un_ipv6_addr(ls));
953  port_v6 = link_specifier_get_un_ipv6_port(ls);
954  have_v6 = 1;
955  break;
956  default:
957  /* Ignore unknown. */
958  break;
959  }
960  } SMARTLIST_FOREACH_END(ls);
961 
962  /* If we don't have IPv4 or IPv6 in link specifiers, log a bug and return. */
963  if (!have_v4 && !have_v6) {
964  if (!have_v6) {
965  log_warn(LD_PROTOCOL, "None of our link specifiers have IPv4 or IPv6");
966  } else {
967  log_warn(LD_PROTOCOL, "None of our link specifiers have IPv4");
968  }
969  return;
970  }
971 
972  /* Here, don't check for DirPorts as link specifiers are only used for
973  * ORPorts. */
974  const or_options_t *options = get_options();
975  int pref_ipv6 = reachable_addr_prefer_ipv6_orport(options);
976  /* Assume that the DirPorts are zero as link specifiers only use ORPorts. */
977  reachable_addr_choose_base(&addr_v4, port_v4, 0,
978  &addr_v6, port_v6, 0,
979  FIREWALL_OR_CONNECTION,
980  pref_only, pref_ipv6,
981  ap);
982 }
983 
984 /** Like reachable_addr_choose_base(), but takes <b>node</b>, and
985  * looks up the node's IPv6 preference rather than taking an argument
986  * for pref_ipv6. */
987 void
989  firewall_connection_t fw_connection,
990  int pref_only, tor_addr_port_t *ap)
991 {
992  tor_assert(ap);
993 
994  tor_addr_make_null(&ap->addr, AF_UNSPEC);
995  ap->port = 0;
996 
997  if (!node) {
998  return;
999  }
1000 
1001  node_assert_ok(node);
1002 
1003  const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
1004  ? node_ipv6_or_preferred(node)
1005  : node_ipv6_dir_preferred(node));
1006 
1007  tor_addr_port_t ipv4_or_ap;
1008  node_get_prim_orport(node, &ipv4_or_ap);
1009  tor_addr_port_t ipv4_dir_ap;
1010  node_get_prim_dirport(node, &ipv4_dir_ap);
1011 
1012  tor_addr_port_t ipv6_or_ap;
1013  node_get_pref_ipv6_orport(node, &ipv6_or_ap);
1014  tor_addr_port_t ipv6_dir_ap;
1015  node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
1016 
1017  /* Assume the IPv6 OR and Dir addresses are the same. */
1018  reachable_addr_choose_base(&ipv4_or_ap.addr, ipv4_or_ap.port,
1019  ipv4_dir_ap.port, &ipv6_or_ap.addr,
1020  ipv6_or_ap.port, ipv6_dir_ap.port,
1021  fw_connection, pref_only,
1022  pref_ipv6_node, ap);
1023 }
1024 
1025 /** Like reachable_addr_choose_from_rs(), but takes <b>ds</b>. */
1026 void
1028  firewall_connection_t fw_connection,
1029  int pref_only,
1030  tor_addr_port_t *ap)
1031 {
1032  tor_assert(ap);
1033 
1034  tor_addr_make_null(&ap->addr, AF_UNSPEC);
1035  ap->port = 0;
1036 
1037  if (!ds) {
1038  return;
1039  }
1040 
1041  /* A dir_server_t always has a fake_status. As long as it has the same
1042  * addresses/ports in both fake_status and dir_server_t, this works fine.
1043  * (See #17867.)
1044  * This function relies on reachable_addr_choose_from_rs looking up the
1045  * node if it can, because that will get the latest info for the relay. */
1046  reachable_addr_choose_from_rs(&ds->fake_status, fw_connection,
1047  pref_only, ap);
1048 }
1049 
1050 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
1051  * based on <b>dir_policy</b>. Else return 0.
1052  */
1053 int
1055 {
1056  return addr_policy_permits_tor_addr(addr, 1, dir_policy);
1057 }
1058 
1059 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1060  * based on <b>socks_policy</b>. Else return 0.
1061  */
1062 int
1064 {
1065  return addr_policy_permits_tor_addr(addr, 1, socks_policy);
1066 }
1067 
1068 /** Return 1 if <b>addr</b> is permitted to connect to our metrics port,
1069  * based on <b>socks_policy</b>. Else return 0.
1070  */
1071 int
1073 {
1075 }
1076 
1077 /** Return true iff the address <b>addr</b> is in a country listed in the
1078  * case-insensitive list of country codes <b>cc_list</b>. */
1079 static int
1080 addr_is_in_cc_list(const tor_addr_t *addr, const smartlist_t *cc_list)
1081 {
1082  country_t country;
1083  const char *name;
1084 
1085  if (!cc_list)
1086  return 0;
1087  country = geoip_get_country_by_addr(addr);
1088  name = geoip_get_country_name(country);
1089  return smartlist_contains_string_case(cc_list, name);
1090 }
1091 
1092 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
1093  * directory, based on <b>authdir_reject_policy</b>. Else return 0.
1094  */
1095 int
1096 authdir_policy_permits_address(const tor_addr_t *addr, uint16_t port)
1097 {
1099  return 0;
1100  return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
1101 }
1102 
1103 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
1104  * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
1105  */
1106 int
1107 authdir_policy_valid_address(const tor_addr_t *addr, uint16_t port)
1108 {
1110  return 0;
1111  return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
1112 }
1113 
1114 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
1115  * based on <b>authdir_badexit_policy</b>. Else return 0.
1116  */
1117 int
1118 authdir_policy_badexit_address(const tor_addr_t *addr, uint16_t port)
1119 {
1121  return 1;
1122  return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
1123 }
1124 
1125 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as MiddleOnly,
1126  * based on <b>authdir_middleonly_policy</b>. Else return 0.
1127  */
1128 int
1130 {
1132  return 1;
1133  return addr_is_in_cc_list(addr, get_options()->AuthDirMiddleOnlyCCs);
1134 }
1135 
1136 #define REJECT(arg) \
1137  STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
1138 
1139 /** Check <b>or_options</b> to determine whether or not we are using the
1140  * default options for exit policy. Return true if so, false otherwise. */
1141 static int
1143 {
1144  return (or_options->ExitPolicy == NULL && or_options->ExitRelay == -1 &&
1145  or_options->ReducedExitPolicy == 0 && or_options->IPv6Exit == 0);
1146 }
1147 
1148 /** Config helper: If there's any problem with the policy configuration
1149  * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
1150  * allocated description of the error. Else return 0. */
1151 int
1152 validate_addr_policies(const or_options_t *options, char **msg)
1153 {
1154  /* XXXX Maybe merge this into parse_policies_from_options, to make sure
1155  * that the two can't go out of sync. */
1156 
1157  smartlist_t *addr_policy=NULL;
1158  *msg = NULL;
1159 
1160  if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
1161  REJECT("Error in ExitPolicy entry.");
1162  }
1163 
1164  static int warned_about_nonexit = 0;
1165 
1166  if (public_server_mode(options) && !warned_about_nonexit &&
1168  warned_about_nonexit = 1;
1169  log_notice(LD_CONFIG, "By default, Tor does not run as an exit relay. "
1170  "If you want to be an exit relay, "
1171  "set ExitRelay to 1. To suppress this message in the future, "
1172  "set ExitRelay to 0.");
1173  }
1174 
1175  /* The rest of these calls *append* to addr_policy. So don't actually
1176  * use the results for anything other than checking if they parse! */
1177  if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
1178  REJECT("Error in DirPolicy entry.");
1179  if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
1180  REJECT("Error in SocksPolicy entry.");
1181  if (parse_addr_policy(options->AuthDirReject, &addr_policy,
1182  ADDR_POLICY_REJECT))
1183  REJECT("Error in AuthDirReject entry.");
1184  if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
1185  ADDR_POLICY_REJECT))
1186  REJECT("Error in AuthDirInvalid entry.");
1187  if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
1188  ADDR_POLICY_REJECT))
1189  REJECT("Error in AuthDirBadExit entry.");
1190  if (parse_addr_policy(options->AuthDirMiddleOnly, &addr_policy,
1191  ADDR_POLICY_REJECT))
1192  REJECT("Error in AuthDirMiddleOnly entry.");
1193 
1194  if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
1195  ADDR_POLICY_ACCEPT))
1196  REJECT("Error in ReachableAddresses entry.");
1197  if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
1198  ADDR_POLICY_ACCEPT))
1199  REJECT("Error in ReachableORAddresses entry.");
1200  if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
1201  ADDR_POLICY_ACCEPT))
1202  REJECT("Error in ReachableDirAddresses entry.");
1203 
1204  err:
1205  addr_policy_list_free(addr_policy);
1206  return *msg ? -1 : 0;
1207 #undef REJECT
1208 }
1209 
1210 /** Parse <b>string</b> in the same way that the exit policy
1211  * is parsed, and put the processed version in *<b>policy</b>.
1212  * Ignore port specifiers.
1213  */
1214 static int
1215 load_policy_from_option(config_line_t *config, const char *option_name,
1216  smartlist_t **policy,
1217  int assume_action)
1218 {
1219  int r;
1220  int killed_any_ports = 0;
1221  addr_policy_list_free(*policy);
1222  *policy = NULL;
1223  r = parse_addr_policy(config, policy, assume_action);
1224  if (r < 0) {
1225  return -1;
1226  }
1227  if (*policy) {
1228  SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
1229  /* ports aren't used in these. */
1230  if (n->prt_min > 1 || n->prt_max != 65535) {
1231  addr_policy_t newp, *c;
1232  memcpy(&newp, n, sizeof(newp));
1233  newp.prt_min = 1;
1234  newp.prt_max = 65535;
1235  newp.is_canonical = 0;
1237  SMARTLIST_REPLACE_CURRENT(*policy, n, c);
1238  addr_policy_free(n);
1239  killed_any_ports = 1;
1240  }
1241  } SMARTLIST_FOREACH_END(n);
1242  }
1243  if (killed_any_ports) {
1244  log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
1245  }
1246  return 0;
1247 }
1248 
1249 /** Helper: Parse the MetricsPortPolicy option into the metrics_policy and set
1250  * the reject all by default.
1251  *
1252  * Return 0 on success else -1. */
1253 static int
1255 {
1256  if (load_policy_from_option(options->MetricsPortPolicy, "MetricsPortPolicy",
1257  &metrics_policy, -1) < 0) {
1258  return -1;
1259  }
1260  /* It is a reject all by default. */
1261  append_exit_policy_string(&metrics_policy, "reject *:*");
1262  return 0;
1263 }
1264 
1265 /** Set all policies based on <b>options</b>, which should have been validated
1266  * first by validate_addr_policies. */
1267 int
1269 {
1270  int ret = 0;
1271  if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
1272  &socks_policy, -1) < 0)
1273  ret = -1;
1274  if (load_policy_from_option(options->DirPolicy, "DirPolicy",
1275  &dir_policy, -1) < 0)
1276  ret = -1;
1277  if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
1278  &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
1279  ret = -1;
1280  if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
1281  &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
1282  ret = -1;
1283  if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
1284  &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
1285  ret = -1;
1286  if (load_policy_from_option(options->AuthDirMiddleOnly, "AuthDirMiddleOnly",
1287  &authdir_middleonly_policy, ADDR_POLICY_REJECT) < 0)
1288  ret = -1;
1289  if (parse_metrics_port_policy(options) < 0) {
1290  ret = -1;
1291  }
1292  if (parse_reachable_addresses() < 0)
1293  ret = -1;
1294  return ret;
1295 }
1296 
1297 /** Compare two provided address policy items, and renturn -1, 0, or 1
1298  * if the first is less than, equal to, or greater than the second. */
1299 static int
1301 {
1302  int r;
1303 #define CMP_FIELD(field) do { \
1304  if (a->field != b->field) { \
1305  return 0; \
1306  } \
1307  } while (0)
1308  CMP_FIELD(policy_type);
1309  CMP_FIELD(is_private);
1310  /* refcnt and is_canonical are irrelevant to equality,
1311  * they are hash table implementation details */
1312  if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
1313  return 0;
1314  CMP_FIELD(maskbits);
1315  CMP_FIELD(prt_min);
1316  CMP_FIELD(prt_max);
1317 #undef CMP_FIELD
1318  return 1;
1319 }
1320 
1321 /** As single_addr_policy_eq, but compare every element of two policies.
1322  */
1323 int
1325 {
1326  int i;
1327  int len_a = a ? smartlist_len(a) : 0;
1328  int len_b = b ? smartlist_len(b) : 0;
1329 
1330  if (len_a != len_b)
1331  return 0;
1332 
1333  for (i = 0; i < len_a; ++i) {
1334  if (! single_addr_policy_eq(smartlist_get(a, i), smartlist_get(b, i)))
1335  return 0;
1336  }
1337 
1338  return 1;
1339 }
1340 
1341 /** Node in hashtable used to store address policy entries. */
1342 typedef struct policy_map_ent_t {
1343  HT_ENTRY(policy_map_ent_t) node;
1344  addr_policy_t *policy;
1346 
1347 /* DOCDOC policy_root */
1348 static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
1349 
1350 /** Return true iff a and b are equal. */
1351 static inline int
1352 policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
1353 {
1354  return single_addr_policy_eq(a->policy, b->policy);
1355 }
1356 
1357 /** Return a hashcode for <b>ent</b> */
1358 static unsigned int
1360 {
1361  const addr_policy_t *a = ent->policy;
1362  addr_policy_t aa;
1363  memset(&aa, 0, sizeof(aa));
1364 
1365  aa.prt_min = a->prt_min;
1366  aa.prt_max = a->prt_max;
1367  aa.maskbits = a->maskbits;
1368  aa.policy_type = a->policy_type;
1369  aa.is_private = a->is_private;
1370 
1371  if (a->is_private) {
1372  aa.is_private = 1;
1373  } else {
1374  tor_addr_copy_tight(&aa.addr, &a->addr);
1375  }
1376 
1377  return (unsigned) siphash24g(&aa, sizeof(aa));
1378 }
1379 
1380 HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
1381  policy_eq);
1382 HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
1383  policy_eq, 0.6, tor_reallocarray_, tor_free_);
1384 
1385 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
1386  * "canonical" copy of that addr_policy_t; the canonical copy is a single
1387  * reference-counted object. */
1388 addr_policy_t *
1390 {
1391  policy_map_ent_t search, *found;
1392  if (e->is_canonical)
1393  return e;
1394 
1395  search.policy = e;
1396  found = HT_FIND(policy_map, &policy_root, &search);
1397  if (!found) {
1398  found = tor_malloc_zero(sizeof(policy_map_ent_t));
1399  found->policy = tor_memdup(e, sizeof(addr_policy_t));
1400  found->policy->is_canonical = 1;
1401  found->policy->refcnt = 0;
1402  HT_INSERT(policy_map, &policy_root, found);
1403  }
1404 
1405  tor_assert(single_addr_policy_eq(found->policy, e));
1406  ++found->policy->refcnt;
1407  return found->policy;
1408 }
1409 
1410 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1411  * addr and port are both known. */
1412 static addr_policy_result_t
1414  const smartlist_t *policy)
1415 {
1416  /* We know the address and port, and we know the policy, so we can just
1417  * compute an exact match. */
1418  SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1419  if (tmpe->addr.family == AF_UNSPEC) {
1420  log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1421  "matches other AF_UNSPEC addresses.");
1422  }
1423  /* Address is known */
1424  if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1425  CMP_EXACT)) {
1426  if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
1427  /* Exact match for the policy */
1428  return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
1430  }
1431  }
1432  } SMARTLIST_FOREACH_END(tmpe);
1433 
1434  /* accept all by default. */
1435  return ADDR_POLICY_ACCEPTED;
1436 }
1437 
1438 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1439  * addr is known but port is not. */
1440 static addr_policy_result_t
1442  const smartlist_t *policy)
1443 {
1444  /* We look to see if there's a definite match. If so, we return that
1445  match's value, unless there's an intervening possible match that says
1446  something different. */
1447  int maybe_accept = 0, maybe_reject = 0;
1448 
1449  SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1450  if (tmpe->addr.family == AF_UNSPEC) {
1451  log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1452  "matches other AF_UNSPEC addresses.");
1453  }
1454  if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1455  CMP_EXACT)) {
1456  if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
1457  /* Definitely matches, since it covers all ports. */
1458  if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1459  /* If we already hit a clause that might trigger a 'reject', than we
1460  * can't be sure of this certain 'accept'.*/
1461  return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1463  } else {
1464  return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1466  }
1467  } else {
1468  /* Might match. */
1469  if (tmpe->policy_type == ADDR_POLICY_REJECT)
1470  maybe_reject = 1;
1471  else
1472  maybe_accept = 1;
1473  }
1474  }
1475  } SMARTLIST_FOREACH_END(tmpe);
1476 
1477  /* accept all by default. */
1478  return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1479 }
1480 
1481 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1482  * port is known but address is not. */
1483 static addr_policy_result_t
1485  const smartlist_t *policy)
1486 {
1487  /* We look to see if there's a definite match. If so, we return that
1488  match's value, unless there's an intervening possible match that says
1489  something different. */
1490  int maybe_accept = 0, maybe_reject = 0;
1491 
1492  SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1493  if (tmpe->addr.family == AF_UNSPEC) {
1494  log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1495  "matches other AF_UNSPEC addresses.");
1496  }
1497  if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
1498  if (tmpe->maskbits == 0) {
1499  /* Definitely matches, since it covers all addresses. */
1500  if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1501  /* If we already hit a clause that might trigger a 'reject', than we
1502  * can't be sure of this certain 'accept'.*/
1503  return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1505  } else {
1506  return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1508  }
1509  } else {
1510  /* Might match. */
1511  if (tmpe->policy_type == ADDR_POLICY_REJECT)
1512  maybe_reject = 1;
1513  else
1514  maybe_accept = 1;
1515  }
1516  }
1517  } SMARTLIST_FOREACH_END(tmpe);
1518 
1519  /* accept all by default. */
1520  return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1521 }
1522 
1523 /** Decide whether a given addr:port is definitely accepted,
1524  * definitely rejected, probably accepted, or probably rejected by a
1525  * given policy. If <b>addr</b> is 0, we don't know the IP of the
1526  * target address. If <b>port</b> is 0, we don't know the port of the
1527  * target address. (At least one of <b>addr</b> and <b>port</b> must be
1528  * provided. If you want to know whether a policy would definitely reject
1529  * an unknown address:port, use policy_is_reject_star().)
1530  *
1531  * We could do better by assuming that some ranges never match typical
1532  * addresses (127.0.0.1, and so on). But we'll try this for now.
1533  */
1535 compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
1536  const smartlist_t *policy))
1537 {
1538  if (!policy) {
1539  /* no policy? accept all. */
1540  return ADDR_POLICY_ACCEPTED;
1541  } else if (addr == NULL || tor_addr_is_null(addr)) {
1542  if (port == 0) {
1543  log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
1544  addr ? tor_addr_family(addr) : -1);
1545  return ADDR_POLICY_REJECTED;
1546  }
1547  return compare_unknown_tor_addr_to_addr_policy(port, policy);
1548  } else if (port == 0) {
1549  return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
1550  } else {
1551  return compare_known_tor_addr_to_addr_policy(addr, port, policy);
1552  }
1553 }
1554 
1555 /** Return true iff the address policy <b>a</b> covers every case that
1556  * would be covered by <b>b</b>, so that a,b is redundant. */
1557 static int
1559 {
1560  if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
1561  /* You can't cover a different family. */
1562  return 0;
1563  }
1564  /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
1565  * to "accept *:80". */
1566  if (a->maskbits > b->maskbits) {
1567  /* a has more fixed bits than b; it can't possibly cover b. */
1568  return 0;
1569  }
1570  if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
1571  /* There's a fixed bit in a that's set differently in b. */
1572  return 0;
1573  }
1574  return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
1575 }
1576 
1577 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
1578  * that is, there exists an address/port that is covered by <b>a</b> that
1579  * is also covered by <b>b</b>.
1580  */
1581 static int
1583 {
1584  maskbits_t minbits;
1585  /* All the bits we care about are those that are set in both
1586  * netmasks. If they are equal in a and b's networkaddresses
1587  * then the networks intersect. If there is a difference,
1588  * then they do not. */
1589  if (a->maskbits < b->maskbits)
1590  minbits = a->maskbits;
1591  else
1592  minbits = b->maskbits;
1593  if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
1594  return 0;
1595  if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
1596  return 0;
1597  return 1;
1598 }
1599 
1600 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
1601  */
1602 STATIC void
1603 append_exit_policy_string(smartlist_t **policy, const char *more)
1604 {
1605  config_line_t tmp;
1606 
1607  tmp.key = NULL;
1608  tmp.value = (char*) more;
1609  tmp.next = NULL;
1610  if (parse_addr_policy(&tmp, policy, -1)<0) {
1611  log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
1612  }
1613 }
1614 
1615 /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
1616 void
1618 {
1619  tor_assert(dest);
1620  tor_assert(addr);
1621 
1622  addr_policy_t p, *add;
1623  memset(&p, 0, sizeof(p));
1624  p.policy_type = ADDR_POLICY_REJECT;
1625  p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
1626  tor_addr_copy(&p.addr, addr);
1627  p.prt_min = 1;
1628  p.prt_max = 65535;
1629 
1631  if (!*dest)
1632  *dest = smartlist_new();
1633  smartlist_add(*dest, add);
1634  log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
1635  fmt_addr(addr));
1636 }
1637 
1638 /* Is addr public for the purposes of rejection? */
1639 static int
1640 tor_addr_is_public_for_reject(const tor_addr_t *addr)
1641 {
1642  return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
1643  && !tor_addr_is_multicast(addr));
1644 }
1645 
1646 /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
1647  * Filter the address, only adding an IPv4 reject rule if ipv4_rules
1648  * is true, and similarly for ipv6_rules. Check each address returns true for
1649  * tor_addr_is_public_for_reject before adding it.
1650  */
1651 static void
1652 addr_policy_append_reject_addr_filter(smartlist_t **dest,
1653  const tor_addr_t *addr,
1654  int ipv4_rules,
1655  int ipv6_rules)
1656 {
1657  tor_assert(dest);
1658  tor_assert(addr);
1659 
1660  /* Only reject IP addresses which are public */
1661  if (tor_addr_is_public_for_reject(addr)) {
1662 
1663  /* Reject IPv4 addresses and IPv6 addresses based on the filters */
1664  int is_ipv4 = tor_addr_is_v4(addr);
1665  if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
1666  addr_policy_append_reject_addr(dest, addr);
1667  }
1668  }
1669 }
1670 
1671 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1672  * list as needed. */
1673 void
1675  const smartlist_t *addrs)
1676 {
1677  tor_assert(dest);
1678  tor_assert(addrs);
1679 
1680  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1681  addr_policy_append_reject_addr(dest, addr);
1682  } SMARTLIST_FOREACH_END(addr);
1683 }
1684 
1685 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1686  * list as needed. Filter using */
1687 static void
1689  const smartlist_t *addrs,
1690  int ipv4_rules,
1691  int ipv6_rules)
1692 {
1693  tor_assert(dest);
1694  tor_assert(addrs);
1695 
1696  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1697  addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
1698  } SMARTLIST_FOREACH_END(addr);
1699 }
1700 
1701 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
1702 static void
1704 {
1705  addr_policy_t *ap, *tmp;
1706  int i, j;
1707 
1708  /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
1709  */
1710  {
1711  int kill_v4=0, kill_v6=0;
1712  for (i = 0; i < smartlist_len(dest); ++i) {
1713  sa_family_t family;
1714  ap = smartlist_get(dest, i);
1715  family = tor_addr_family(&ap->addr);
1716  if ((family == AF_INET && kill_v4) ||
1717  (family == AF_INET6 && kill_v6)) {
1718  smartlist_del_keeporder(dest, i--);
1719  addr_policy_free(ap);
1720  continue;
1721  }
1722 
1723  if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
1724  /* This is a catch-all line -- later lines are unreachable. */
1725  if (family == AF_INET) {
1726  kill_v4 = 1;
1727  } else if (family == AF_INET6) {
1728  kill_v6 = 1;
1729  }
1730  }
1731  }
1732  }
1733 
1734  /* Step two: for every entry, see if there's a redundant entry
1735  * later on, and remove it. */
1736  for (i = 0; i < smartlist_len(dest)-1; ++i) {
1737  ap = smartlist_get(dest, i);
1738  for (j = i+1; j < smartlist_len(dest); ++j) {
1739  tmp = smartlist_get(dest, j);
1740  tor_assert(j > i);
1741  if (addr_policy_covers(ap, tmp)) {
1742  char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1743  policy_write_item(p1, sizeof(p1), tmp, 0);
1744  policy_write_item(p2, sizeof(p2), ap, 0);
1745  log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
1746  "redundant by %s (%d).", p1, j, p2, i);
1747  smartlist_del_keeporder(dest, j--);
1748  addr_policy_free(tmp);
1749  }
1750  }
1751  }
1752 
1753  /* Step three: for every entry A, see if there's an entry B making this one
1754  * redundant later on. This is the case if A and B are of the same type
1755  * (accept/reject), A is a subset of B, and there is no other entry of
1756  * different type in between those two that intersects with A.
1757  *
1758  * Anybody want to double-check the logic here? XXX
1759  */
1760  for (i = 0; i < smartlist_len(dest)-1; ++i) {
1761  ap = smartlist_get(dest, i);
1762  for (j = i+1; j < smartlist_len(dest); ++j) {
1763  // tor_assert(j > i); // j starts out at i+1; j only increases; i only
1764  // // decreases.
1765  tmp = smartlist_get(dest, j);
1766  if (ap->policy_type != tmp->policy_type) {
1767  if (addr_policy_intersects(ap, tmp))
1768  break;
1769  } else { /* policy_types are equal. */
1770  if (addr_policy_covers(tmp, ap)) {
1771  char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1772  policy_write_item(p1, sizeof(p1), ap, 0);
1773  policy_write_item(p2, sizeof(p2), tmp, 0);
1774  log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
1775  "covered by %s.", p1, p2);
1776  smartlist_del_keeporder(dest, i--);
1777  addr_policy_free(ap);
1778  break;
1779  }
1780  }
1781  }
1782  }
1783 }
1784 
1785 /** Reject private helper for policies_parse_exit_policy_internal: rejects
1786  * publicly routable addresses on this exit relay.
1787  *
1788  * Add reject entries to the linked list *<b>dest</b>:
1789  * <ul>
1790  * <li>if configured_addresses is non-NULL, add entries that reject each
1791  * tor_addr_t in the list as a destination.
1792  * <li>if reject_interface_addresses is true, add entries that reject each
1793  * public IPv4 and IPv6 address of each interface on this machine.
1794  * <li>if reject_configured_port_addresses is true, add entries that reject
1795  * each IPv4 and IPv6 address configured for a port.
1796  * </ul>
1797  *
1798  * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
1799  * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
1800  * false.)
1801  *
1802  * The list in <b>dest</b> is created as needed.
1803  */
1804 void
1806  smartlist_t **dest,
1807  int ipv6_exit,
1808  const smartlist_t *configured_addresses,
1809  int reject_interface_addresses,
1810  int reject_configured_port_addresses)
1811 {
1812  tor_assert(dest);
1813 
1814  /* Reject configured addresses, if they are from public netblocks. */
1815  if (configured_addresses) {
1816  addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
1817  1, ipv6_exit);
1818  }
1819 
1820  /* Reject configured port addresses, if they are from public netblocks. */
1821  if (reject_configured_port_addresses) {
1822  const smartlist_t *port_addrs = get_configured_ports();
1823 
1824  SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
1825 
1826  /* Only reject port IP addresses, not port unix sockets */
1827  if (!port->is_unix_addr) {
1828  addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
1829  }
1830  } SMARTLIST_FOREACH_END(port);
1831  }
1832 
1833  /* Reject local addresses from public netblocks on any interface. */
1834  if (reject_interface_addresses) {
1835  smartlist_t *public_addresses = NULL;
1836 
1837  /* Reject public IPv4 addresses on any interface */
1838  public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
1839  addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
1840  interface_address6_list_free(public_addresses);
1841 
1842  /* Don't look for IPv6 addresses if we're configured as IPv4-only */
1843  if (ipv6_exit) {
1844  /* Reject public IPv6 addresses on any interface */
1845  public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
1846  addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
1847  interface_address6_list_free(public_addresses);
1848  }
1849  }
1850 
1851  /* If addresses were added multiple times, remove all but one of them. */
1852  if (*dest) {
1854  }
1855 }
1856 
1857 /**
1858  * Iterate through <b>policy</b> looking for redundant entries. Log a
1859  * warning message with the first redundant entry, if any is found.
1860  */
1861 static void
1863 {
1864  int found_final_effective_entry = 0;
1865  int first_redundant_entry = 0;
1866  tor_assert(policy);
1867  SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
1868  sa_family_t family;
1869  int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
1870  const int i = p_sl_idx;
1871 
1872  /* Look for accept/reject *[4|6|]:* entries */
1873  if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
1874  family = tor_addr_family(&p->addr);
1875  /* accept/reject *:* may have already been expanded into
1876  * accept/reject *4:*,accept/reject *6:*
1877  * But handle both forms.
1878  */
1879  if (family == AF_INET || family == AF_UNSPEC) {
1880  found_ipv4_wildcard = 1;
1881  }
1882  if (family == AF_INET6 || family == AF_UNSPEC) {
1883  found_ipv6_wildcard = 1;
1884  }
1885  }
1886 
1887  /* We also find accept *4:*,reject *6:* ; and
1888  * accept *4:*,<other policies>,accept *6:* ; and similar.
1889  * That's ok, because they make any subsequent entries redundant. */
1890  if (found_ipv4_wildcard && found_ipv6_wildcard) {
1891  found_final_effective_entry = 1;
1892  /* if we're not on the final entry in the list */
1893  if (i < smartlist_len(policy) - 1) {
1894  first_redundant_entry = i + 1;
1895  }
1896  break;
1897  }
1898  } SMARTLIST_FOREACH_END(p);
1899 
1900  /* Work out if there are redundant trailing entries in the policy list */
1901  if (found_final_effective_entry && first_redundant_entry > 0) {
1902  const addr_policy_t *p;
1903  /* Longest possible policy is
1904  * "accept6 ffff:ffff:..255/128:10000-65535",
1905  * which contains a max-length IPv6 address, plus 24 characters. */
1906  char line[TOR_ADDR_BUF_LEN + 32];
1907 
1908  tor_assert(first_redundant_entry < smartlist_len(policy));
1909  p = smartlist_get(policy, first_redundant_entry);
1910  /* since we've already parsed the policy into an addr_policy_t struct,
1911  * we might not log exactly what the user typed in */
1912  policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
1913  log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
1914  "redundant, as it follows accept/reject *:* rules for both "
1915  "IPv4 and IPv6. They will be removed from the exit policy. (Use "
1916  "accept/reject *:* as the last entry in any exit policy.)",
1917  line);
1918  }
1919 }
1920 
1921 #define DEFAULT_EXIT_POLICY \
1922  "reject *:25,reject *:119,reject *:135-139,reject *:445," \
1923  "reject *:563,reject *:1214,reject *:4661-4666," \
1924  "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
1925 
1926 #define REDUCED_EXIT_POLICY \
1927  "accept *:20-23,accept *:43,accept *:53,accept *:79-81,accept *:88," \
1928  "accept *:110,accept *:143,accept *:194,accept *:220,accept *:389," \
1929  "accept *:443,accept *:464,accept *:465,accept *:531,accept *:543-544," \
1930  "accept *:554,accept *:563,accept *:587,accept *:636,accept *:706," \
1931  "accept *:749,accept *:873,accept *:902-904,accept *:981,accept *:989-995," \
1932  "accept *:1194,accept *:1220,accept *:1293,accept *:1500,accept *:1533," \
1933  "accept *:1677,accept *:1723,accept *:1755,accept *:1863," \
1934  "accept *:2082-2083,accept *:2086-2087,accept *:2095-2096," \
1935  "accept *:2102-2104,accept *:3128,accept *:3389,accept *:3690," \
1936  "accept *:4321,accept *:4643,accept *:5050,accept *:5190," \
1937  "accept *:5222-5223,accept *:5228,accept *:5900,accept *:6660-6669," \
1938  "accept *:6679,accept *:6697,accept *:8000,accept *:8008,accept *:8074," \
1939  "accept *:8080,accept *:8082,accept *:8087-8088,accept *:8232-8233," \
1940  "accept *:8332-8333,accept *:8443,accept *:8888,accept *:9418," \
1941  "accept *:9999,accept *:10000,accept *:11371,accept *:19294," \
1942  "accept *:19638,accept *:50002,accept *:64738,reject *:*"
1943 
1944 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
1945  *
1946  * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
1947  *
1948  * If <b>configured_addresses</b> contains addresses:
1949  * - prepend entries that reject the addresses in this list. These may be the
1950  * advertised relay addresses and/or the outbound bind addresses,
1951  * depending on the ExitPolicyRejectPrivate and
1952  * ExitPolicyRejectLocalInterfaces settings.
1953  * If <b>rejectprivate</b> is true:
1954  * - prepend "reject private:*" to the policy.
1955  * If <b>reject_interface_addresses</b> is true:
1956  * - prepend entries that reject publicly routable interface addresses on
1957  * this exit relay by calling policies_parse_exit_policy_reject_private
1958  * If <b>reject_configured_port_addresses</b> is true:
1959  * - prepend entries that reject all configured port addresses
1960  *
1961  * If cfg doesn't end in an absolute accept or reject and if
1962  * <b>add_default_policy</b> is true, add the default exit
1963  * policy afterwards.
1964  *
1965  * Return -1 if we can't parse cfg, else return 0.
1966  *
1967  * This function is used to parse the exit policy from our torrc. For
1968  * the functions used to parse the exit policy from a router descriptor,
1969  * see router_add_exit_policy.
1970  */
1971 static int
1973  smartlist_t **dest,
1974  int ipv6_exit,
1975  int rejectprivate,
1976  const smartlist_t *configured_addresses,
1977  int reject_interface_addresses,
1978  int reject_configured_port_addresses,
1979  int add_default_policy,
1980  int add_reduced_policy)
1981 {
1982  if (!ipv6_exit) {
1983  append_exit_policy_string(dest, "reject *6:*");
1984  }
1985  if (rejectprivate) {
1986  /* Reject IPv4 and IPv6 reserved private netblocks */
1987  append_exit_policy_string(dest, "reject private:*");
1988  }
1989 
1990  /* Consider rejecting IPv4 and IPv6 advertised relay addresses, outbound bind
1991  * addresses, publicly routable addresses, and configured port addresses
1992  * on this exit relay */
1994  configured_addresses,
1995  reject_interface_addresses,
1996  reject_configured_port_addresses);
1997 
1998  if (parse_addr_policy(cfg, dest, -1))
1999  return -1;
2000 
2001  /* Before we add the default policy and final rejects, check to see if
2002  * there are any lines after accept *:* or reject *:*. These lines have no
2003  * effect, and are most likely an error. */
2005 
2006  if (add_reduced_policy) {
2007  append_exit_policy_string(dest, REDUCED_EXIT_POLICY);
2008  } else if (add_default_policy) {
2009  append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
2010  } else {
2011  append_exit_policy_string(dest, "reject *4:*");
2012  append_exit_policy_string(dest, "reject *6:*");
2013  }
2015 
2016  return 0;
2017 }
2018 
2019 /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
2020  *
2021  * Prepend an entry that rejects all IPv6 destinations unless
2022  * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
2023  *
2024  * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
2025  * - prepend an entry that rejects all destinations in all netblocks
2026  * reserved for private use.
2027  * - prepend entries that reject the advertised relay addresses in
2028  * configured_addresses
2029  * If <b>EXIT_POLICY_REJECT_LOCAL_INTERFACES</b> bit is set in <b>options</b>:
2030  * - prepend entries that reject publicly routable addresses on this exit
2031  * relay by calling policies_parse_exit_policy_internal
2032  * - prepend entries that reject the outbound bind addresses in
2033  * configured_addresses
2034  * - prepend entries that reject all configured port addresses
2035  *
2036  * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
2037  * default exit policy entries to <b>result</b> smartlist.
2038  */
2039 int
2041  exit_policy_parser_cfg_t options,
2042  const smartlist_t *configured_addresses)
2043 {
2044  int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
2045  int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
2046  int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
2047  int reject_local_interfaces = (options &
2048  EXIT_POLICY_REJECT_LOCAL_INTERFACES) ? 1 : 0;
2049  int add_reduced = (options & EXIT_POLICY_ADD_REDUCED) ? 1 : 0;
2050 
2051  return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
2052  reject_private,
2053  configured_addresses,
2054  reject_local_interfaces,
2055  reject_local_interfaces,
2056  add_default,
2057  add_reduced);
2058 }
2059 
2060 /** Helper function that adds a copy of addr to a smartlist as long as it is
2061  * non-NULL and not tor_addr_is_null().
2062  *
2063  * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2064  */
2065 static void
2067 {
2068  if (addr && !tor_addr_is_null(addr)) {
2069  tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
2070  tor_addr_copy(addr_copy, addr);
2071  smartlist_add(addr_list, addr_copy);
2072  }
2073 }
2074 
2075 /** Helper function that adds copies of or_options->OutboundBindAddresses
2076  * to a smartlist as tor_addr_t *, as long as or_options is non-NULL, and
2077  * the addresses are not tor_addr_is_null(), by passing them to
2078  * policies_add_addr_to_smartlist.
2079  *
2080  * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2081  */
2082 static void
2084  const or_options_t *or_options)
2085 {
2086  if (or_options) {
2087  for (int i=0;i<OUTBOUND_ADDR_MAX;i++) {
2088  for (int j=0;j<2;j++) {
2089  if (!tor_addr_is_null(&or_options->OutboundBindAddresses[i][j])) {
2091  &or_options->OutboundBindAddresses[i][j]);
2092  }
2093  }
2094  }
2095  }
2096 }
2097 
2098 /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
2099  * smartlist.
2100  * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
2101  * rejects all IPv6 destinations.
2102  *
2103  * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
2104  * - prepend an entry that rejects all destinations in all netblocks reserved
2105  * for private use.
2106  * - if ipv4_local_address is non-zero, treat it as a host-order IPv4 address,
2107  * and add it to the list of configured addresses.
2108  * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
2109  * to the list of configured addresses.
2110  * If <b>or_options->ExitPolicyRejectLocalInterfaces</b> is true:
2111  * - if or_options->OutboundBindAddresses[][0] (=IPv4) is not the null
2112  * tor_addr_t, add it to the list of configured addresses.
2113  * - if or_options->OutboundBindAddresses[][1] (=IPv6) is not the null
2114  * tor_addr_t, add it to the list of configured addresses.
2115  *
2116  * If <b>or_options->BridgeRelay</b> is false, append entries of default
2117  * Tor exit policy into <b>result</b> smartlist.
2118  *
2119  * If or_options->ExitRelay is false, or is auto without specifying an exit
2120  * policy, then make our exit policy into "reject *:*" regardless.
2121  */
2122 int
2124  const tor_addr_t *ipv4_local_address,
2125  const tor_addr_t *ipv6_local_address,
2126  smartlist_t **result)
2127 {
2128  exit_policy_parser_cfg_t parser_cfg = 0;
2129  smartlist_t *configured_addresses = NULL;
2130  int rv = 0;
2131 
2132  /* Short-circuit for non-exit relays, or for relays where we didn't specify
2133  * ExitPolicy or ReducedExitPolicy or IPv6Exit and ExitRelay is auto. */
2134  if (or_options->ExitRelay == 0 ||
2135  policy_using_default_exit_options(or_options)) {
2136  append_exit_policy_string(result, "reject *4:*");
2137  append_exit_policy_string(result, "reject *6:*");
2138  return 0;
2139  }
2140 
2141  configured_addresses = smartlist_new();
2142 
2143  /* Configure the parser */
2144  if (or_options->IPv6Exit) {
2145  parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
2146  }
2147 
2148  if (or_options->ExitPolicyRejectPrivate) {
2149  parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
2150  }
2151 
2152  if (!or_options->BridgeRelay) {
2153  if (or_options->ReducedExitPolicy)
2154  parser_cfg |= EXIT_POLICY_ADD_REDUCED;
2155  else
2156  parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
2157  }
2158 
2159  if (or_options->ExitPolicyRejectLocalInterfaces) {
2160  parser_cfg |= EXIT_POLICY_REJECT_LOCAL_INTERFACES;
2161  }
2162 
2163  /* Copy the configured addresses into the tor_addr_t* list */
2164  if (or_options->ExitPolicyRejectPrivate) {
2165  policies_copy_addr_to_smartlist(configured_addresses, ipv4_local_address);
2166  policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
2167  }
2168 
2169  if (or_options->ExitPolicyRejectLocalInterfaces) {
2170  policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2171  or_options);
2172  }
2173 
2174  rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
2175  configured_addresses);
2176 
2177  SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2178  smartlist_free(configured_addresses);
2179 
2180  return rv;
2181 }
2182 
2183 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
2184  * *<b>dest</b> as needed. */
2185 void
2187 {
2188  append_exit_policy_string(dest, "reject *4:*");
2189  append_exit_policy_string(dest, "reject *6:*");
2190 }
2191 
2192 /** Replace the exit policy of <b>node</b> with reject *:* */
2193 void
2195 {
2196  node->rejects_all = 1;
2197 }
2198 
2199 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
2200  * allows exiting to <b>port</b>. Otherwise, return 0. */
2201 static int
2203 {
2204  uint32_t mask, ip, i;
2205  /* Is this /8 rejected (1), or undecided (0)? */
2206  char subnet_status[256];
2207 
2208  memset(subnet_status, 0, sizeof(subnet_status));
2209  SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2210  if (tor_addr_family(&p->addr) != AF_INET)
2211  continue; /* IPv4 only for now */
2212  if (p->prt_min > port || p->prt_max < port)
2213  continue; /* Doesn't cover our port. */
2214  mask = 0;
2215  tor_assert(p->maskbits <= 32);
2216 
2217  if (p->maskbits)
2218  mask = UINT32_MAX<<(32-p->maskbits);
2219  ip = tor_addr_to_ipv4h(&p->addr);
2220 
2221  /* Calculate the first and last subnet that this exit policy touches
2222  * and set it as loop boundaries. */
2223  for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
2224  tor_addr_t addr;
2225  if (subnet_status[i] != 0)
2226  continue; /* We already reject some part of this /8 */
2227  tor_addr_from_ipv4h(&addr, i<<24);
2228  if (tor_addr_is_internal(&addr, 0) &&
2229  !get_options()->DirAllowPrivateAddresses) {
2230  continue; /* Local or non-routable addresses */
2231  }
2232  if (p->policy_type == ADDR_POLICY_ACCEPT) {
2233  if (p->maskbits > 8)
2234  continue; /* Narrower than a /8. */
2235  /* We found an allowed subnet of at least size /8. Done
2236  * for this port! */
2237  return 1;
2238  } else if (p->policy_type == ADDR_POLICY_REJECT) {
2239  subnet_status[i] = 1;
2240  }
2241  }
2242  } SMARTLIST_FOREACH_END(p);
2243  return 0;
2244 }
2245 
2246 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
2247  * it allows exit to at least one /8 address space for each of ports 80
2248  * and 443. */
2249 int
2251 {
2252  if (!policy) /*XXXX disallow NULL policies? */
2253  return 0;
2254 
2255  return (exit_policy_is_general_exit_helper(policy, 80) &&
2256  exit_policy_is_general_exit_helper(policy, 443));
2257 }
2258 
2259 /** Return false if <b>policy</b> might permit access to some addr:port;
2260  * otherwise if we are certain it rejects everything, return true. If no
2261  * part of <b>policy</b> matches, return <b>default_reject</b>.
2262  * NULL policies are allowed, and treated as empty. */
2263 int
2265  int default_reject)
2266 {
2267  if (!policy)
2268  return default_reject;
2269  SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
2270  if (p->policy_type == ADDR_POLICY_ACCEPT &&
2271  (tor_addr_family(&p->addr) == family ||
2272  tor_addr_family(&p->addr) == AF_UNSPEC)) {
2273  return 0;
2274  } else if (p->policy_type == ADDR_POLICY_REJECT &&
2275  p->prt_min <= 1 && p->prt_max == 65535 &&
2276  p->maskbits == 0 &&
2277  (tor_addr_family(&p->addr) == family ||
2278  tor_addr_family(&p->addr) == AF_UNSPEC)) {
2279  return 1;
2280  }
2281  } SMARTLIST_FOREACH_END(p);
2282  return default_reject;
2283 }
2284 
2285 /** Write a single address policy to the buf_len byte buffer at buf. Return
2286  * the number of characters written, or -1 on failure. */
2287 int
2288 policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
2289  int format_for_desc)
2290 {
2291  size_t written = 0;
2292  char addrbuf[TOR_ADDR_BUF_LEN];
2293  const char *addrpart;
2294  int result;
2295  const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
2296  const sa_family_t family = tor_addr_family(&policy->addr);
2297  const int is_ip6 = (family == AF_INET6);
2298 
2299  tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
2300 
2301  /* write accept/reject 1.2.3.4 */
2302  if (policy->is_private) {
2303  addrpart = "private";
2304  } else if (policy->maskbits == 0) {
2305  if (format_for_desc)
2306  addrpart = "*";
2307  else if (family == AF_INET6)
2308  addrpart = "*6";
2309  else if (family == AF_INET)
2310  addrpart = "*4";
2311  else
2312  addrpart = "*";
2313  } else {
2314  addrpart = addrbuf;
2315  }
2316 
2317  result = tor_snprintf(buf, buflen, "%s%s %s",
2318  is_accept ? "accept" : "reject",
2319  (is_ip6&&format_for_desc)?"6":"",
2320  addrpart);
2321  if (result < 0)
2322  return -1;
2323  written += strlen(buf);
2324  /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
2325  the mask is 0, we already wrote "*". */
2326  if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
2327  if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
2328  return -1;
2329  written += strlen(buf+written);
2330  }
2331  if (policy->prt_min <= 1 && policy->prt_max == 65535) {
2332  /* There is no port set; write ":*" */
2333  if (written+4 > buflen)
2334  return -1;
2335  strlcat(buf+written, ":*", buflen-written);
2336  written += 2;
2337  } else if (policy->prt_min == policy->prt_max) {
2338  /* There is only one port; write ":80". */
2339  result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
2340  if (result<0)
2341  return -1;
2342  written += result;
2343  } else {
2344  /* There is a range of ports; write ":79-80". */
2345  result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
2346  policy->prt_min, policy->prt_max);
2347  if (result<0)
2348  return -1;
2349  written += result;
2350  }
2351  if (written < buflen)
2352  buf[written] = '\0';
2353  else
2354  return -1;
2355 
2356  return (int)written;
2357 }
2358 
2359 /** Create a new exit policy summary, initially only with a single
2360  * port 1-64k item */
2361 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
2362  * RB-tree if that turns out to matter. */
2363 static smartlist_t *
2365 {
2366  smartlist_t *summary;
2367  policy_summary_item_t* item;
2368 
2369  item = tor_malloc_zero(sizeof(policy_summary_item_t));
2370  item->prt_min = 1;
2371  item->prt_max = 65535;
2372  item->reject_count = 0;
2373  item->accepted = 0;
2374 
2375  summary = smartlist_new();
2376  smartlist_add(summary, item);
2377 
2378  return summary;
2379 }
2380 
2381 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
2382  * The current item is changed to end at new-starts - 1, the new item
2383  * copies reject_count and accepted from the old item,
2384  * starts at new_starts and ends at the port where the original item
2385  * previously ended.
2386  */
2387 static policy_summary_item_t*
2389 {
2390  policy_summary_item_t* new;
2391 
2392  new = tor_malloc_zero(sizeof(policy_summary_item_t));
2393  new->prt_min = new_starts;
2394  new->prt_max = old->prt_max;
2395  new->reject_count = old->reject_count;
2396  new->accepted = old->accepted;
2397 
2398  old->prt_max = new_starts-1;
2399 
2400  tor_assert(old->prt_min <= old->prt_max);
2401  tor_assert(new->prt_min <= new->prt_max);
2402  return new;
2403 }
2404 
2405 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
2406  * my immortal soul, he can clean it up himself. */
2407 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
2408 
2409 #define IPV4_BITS (32)
2410 /* Every IPv4 address is counted as one rejection */
2411 #define REJECT_CUTOFF_SCALE_IPV4 (0)
2412 /* Ports are rejected in an IPv4 summary if they are rejected in more than two
2413  * IPv4 /8 address blocks */
2414 #define REJECT_CUTOFF_COUNT_IPV4 (UINT64_C(1) << \
2415  (IPV4_BITS - REJECT_CUTOFF_SCALE_IPV4 - 7))
2416 
2417 #define IPV6_BITS (128)
2418 /* IPv6 /64s are counted as one rejection, anything smaller is ignored */
2419 #define REJECT_CUTOFF_SCALE_IPV6 (64)
2420 /* Ports are rejected in an IPv6 summary if they are rejected in more than one
2421  * IPv6 /16 address block.
2422  * This is roughly equivalent to the IPv4 cutoff, as only five IPv6 /12s (and
2423  * some scattered smaller blocks) have been allocated to the RIRs.
2424  * Network providers are typically allocated one or more IPv6 /32s.
2425  */
2426 #define REJECT_CUTOFF_COUNT_IPV6 (UINT64_C(1) << \
2427  (IPV6_BITS - REJECT_CUTOFF_SCALE_IPV6 - 16))
2428 
2429 /** Split an exit policy summary so that prt_min and prt_max
2430  * fall at exactly the start and end of an item respectively.
2431  */
2432 static int
2434  uint16_t prt_min, uint16_t prt_max)
2435 {
2436  int start_at_index;
2437 
2438  int i = 0;
2439 
2440  while (AT(i)->prt_max < prt_min)
2441  i++;
2442  if (AT(i)->prt_min != prt_min) {
2443  policy_summary_item_t* new_item;
2444  new_item = policy_summary_item_split(AT(i), prt_min);
2445  smartlist_insert(summary, i+1, new_item);
2446  i++;
2447  }
2448  start_at_index = i;
2449 
2450  while (AT(i)->prt_max < prt_max)
2451  i++;
2452  if (AT(i)->prt_max != prt_max) {
2453  policy_summary_item_t* new_item;
2454  new_item = policy_summary_item_split(AT(i), prt_max+1);
2455  smartlist_insert(summary, i+1, new_item);
2456  }
2457 
2458  return start_at_index;
2459 }
2460 
2461 /** Mark port ranges as accepted if they are below the reject_count for family
2462  */
2463 static void
2465  uint16_t prt_min, uint16_t prt_max,
2466  sa_family_t family)
2467 {
2468  tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2469  uint64_t family_reject_count = ((family == AF_INET) ?
2470  REJECT_CUTOFF_COUNT_IPV4 :
2471  REJECT_CUTOFF_COUNT_IPV6);
2472 
2473  int i = policy_summary_split(summary, prt_min, prt_max);
2474  while (i < smartlist_len(summary) &&
2475  AT(i)->prt_max <= prt_max) {
2476  if (!AT(i)->accepted &&
2477  AT(i)->reject_count <= family_reject_count)
2478  AT(i)->accepted = 1;
2479  i++;
2480  }
2481  tor_assert(i < smartlist_len(summary) || prt_max==65535);
2482 }
2483 
2484 /** Count the number of addresses in a network in family with prefixlen
2485  * maskbits against the given portrange. */
2486 static void
2488  maskbits_t maskbits,
2489  uint16_t prt_min, uint16_t prt_max,
2490  sa_family_t family)
2491 {
2492  tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2493 
2494  int i = policy_summary_split(summary, prt_min, prt_max);
2495 
2496  /* The length of a single address mask */
2497  int addrbits = (family == AF_INET) ? IPV4_BITS : IPV6_BITS;
2498  tor_assert_nonfatal_once(addrbits >= maskbits);
2499 
2500  /* We divide IPv6 address counts by (1 << scale) to keep them in a uint64_t
2501  */
2502  int scale = ((family == AF_INET) ?
2503  REJECT_CUTOFF_SCALE_IPV4 :
2504  REJECT_CUTOFF_SCALE_IPV6);
2505 
2506  tor_assert_nonfatal_once(addrbits >= scale);
2507  if (maskbits > (addrbits - scale)) {
2508  tor_assert_nonfatal_once(family == AF_INET6);
2509  /* The address range is so small, we'd need billions of them to reach the
2510  * rejection limit. So we ignore this range in the reject count. */
2511  return;
2512  }
2513 
2514  uint64_t count = 0;
2515  if (addrbits - scale - maskbits >= 64) {
2516  tor_assert_nonfatal_once(family == AF_INET6);
2517  /* The address range is so large, it's an automatic rejection for all ports
2518  * in the range. */
2519  count = UINT64_MAX;
2520  } else {
2521  count = (UINT64_C(1) << (addrbits - scale - maskbits));
2522  }
2523  tor_assert_nonfatal_once(count > 0);
2524  while (i < smartlist_len(summary) &&
2525  AT(i)->prt_max <= prt_max) {
2526  if (AT(i)->reject_count <= UINT64_MAX - count) {
2527  AT(i)->reject_count += count;
2528  } else {
2529  /* IPv4 would require a 4-billion address redundant policy to get here,
2530  * but IPv6 just needs to have ::/0 */
2531  if (family == AF_INET) {
2532  tor_assert_nonfatal_unreached_once();
2533  }
2534  /* If we do get here, use saturating arithmetic */
2535  AT(i)->reject_count = UINT64_MAX;
2536  }
2537  i++;
2538  }
2539  tor_assert(i < smartlist_len(summary) || prt_max==65535);
2540 }
2541 
2542 /** Add a single exit policy item to our summary:
2543  *
2544  * If it is an accept, ignore it unless it is for all IP addresses
2545  * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
2546  * policy_summary_accept().
2547  *
2548  * If it is a reject, ignore it if it is about one of the private
2549  * networks. Otherwise call policy_summary_reject().
2550  */
2551 static void
2553 {
2554  if (p->policy_type == ADDR_POLICY_ACCEPT) {
2555  if (p->maskbits == 0) {
2556  policy_summary_accept(summary, p->prt_min, p->prt_max, p->addr.family);
2557  }
2558  } else if (p->policy_type == ADDR_POLICY_REJECT) {
2559 
2560  int is_private = 0;
2561  int i;
2562  for (i = 0; private_nets[i]; ++i) {
2563  tor_addr_t addr;
2564  maskbits_t maskbits;
2565  if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
2566  &maskbits, NULL, NULL)<0) {
2567  tor_assert(0);
2568  }
2569  if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
2570  p->maskbits == maskbits) {
2571  is_private = 1;
2572  break;
2573  }
2574  }
2575 
2576  if (!is_private) {
2577  policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max,
2578  p->addr.family);
2579  }
2580  } else
2581  tor_assert(0);
2582 }
2583 
2584 /** Create a string representing a summary for an exit policy.
2585  * The summary will either be an "accept" plus a comma-separated list of port
2586  * ranges or a "reject" plus port-ranges, depending on which is shorter.
2587  *
2588  * If no exits are allowed at all then "reject 1-65535" is returned. If no
2589  * ports are blocked instead of "reject " we return "accept 1-65535". (These
2590  * are an exception to the shorter-representation-wins rule).
2591  */
2592 char *
2594 {
2595  smartlist_t *summary = policy_summary_create();
2596  smartlist_t *accepts, *rejects;
2597  int i, last, start_prt;
2598  size_t accepts_len, rejects_len;
2599  char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
2600  const char *prefix;
2601 
2602  tor_assert(policy);
2603 
2604  /* Create the summary list */
2605  SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2606  sa_family_t f = tor_addr_family(&p->addr);
2607  if (f != AF_INET && f != AF_INET6) {
2608  log_warn(LD_BUG, "Weird family when summarizing address policy");
2609  }
2610  if (f != family)
2611  continue;
2612  policy_summary_add_item(summary, p);
2613  } SMARTLIST_FOREACH_END(p);
2614 
2615  /* Now create two lists of strings, one for accepted and one
2616  * for rejected ports. We take care to merge ranges so that
2617  * we avoid getting stuff like "1-4,5-9,10", instead we want
2618  * "1-10"
2619  */
2620  i = 0;
2621  start_prt = 1;
2622  accepts = smartlist_new();
2623  rejects = smartlist_new();
2624  while (1) {
2625  last = i == smartlist_len(summary)-1;
2626  if (last ||
2627  AT(i)->accepted != AT(i+1)->accepted) {
2628  char buf[POLICY_BUF_LEN];
2629 
2630  if (start_prt == AT(i)->prt_max)
2631  tor_snprintf(buf, sizeof(buf), "%d", start_prt);
2632  else
2633  tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
2634 
2635  if (AT(i)->accepted)
2636  smartlist_add_strdup(accepts, buf);
2637  else
2638  smartlist_add_strdup(rejects, buf);
2639 
2640  if (last)
2641  break;
2642 
2643  start_prt = AT(i+1)->prt_min;
2644  };
2645  i++;
2646  };
2647 
2648  /* Figure out which of the two stringlists will be shorter and use
2649  * that to build the result
2650  */
2651  if (smartlist_len(accepts) == 0) { /* no exits at all */
2652  result = tor_strdup("reject 1-65535");
2653  goto cleanup;
2654  }
2655  if (smartlist_len(rejects) == 0) { /* no rejects at all */
2656  result = tor_strdup("accept 1-65535");
2657  goto cleanup;
2658  }
2659 
2660  accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
2661  rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
2662 
2663  if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
2664  accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
2665  char *c;
2666  shorter_str = accepts_str;
2667  prefix = "accept";
2668 
2669  c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
2670  while (*c != ',' && c >= shorter_str)
2671  c--;
2672  tor_assert(c >= shorter_str);
2673  tor_assert(*c == ',');
2674  *c = '\0';
2675 
2676  } else if (rejects_len < accepts_len) {
2677  shorter_str = rejects_str;
2678  prefix = "reject";
2679  } else {
2680  shorter_str = accepts_str;
2681  prefix = "accept";
2682  }
2683 
2684  tor_asprintf(&result, "%s %s", prefix, shorter_str);
2685 
2686  cleanup:
2687  /* cleanup */
2689  smartlist_free(summary);
2690 
2691  tor_free(accepts_str);
2692  SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
2693  smartlist_free(accepts);
2694 
2695  tor_free(rejects_str);
2696  SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
2697  smartlist_free(rejects);
2698 
2699  return result;
2700 }
2701 
2702 /** Convert a summarized policy string into a short_policy_t. Return NULL
2703  * if the string is not well-formed. */
2705 parse_short_policy(const char *summary)
2706 {
2707  const char *orig_summary = summary;
2708  short_policy_t *result;
2709  int is_accept;
2710  int n_entries;
2711  short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
2712  char *next;
2713 
2714  if (!strcmpstart(summary, "accept ")) {
2715  is_accept = 1;
2716  summary += strlen("accept ");
2717  } else if (!strcmpstart(summary, "reject ")) {
2718  is_accept = 0;
2719  summary += strlen("reject ");
2720  } else {
2721  log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
2722  return NULL;
2723  }
2724 
2725  n_entries = 0;
2726  for ( ; *summary; summary = next) {
2727  if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
2728  log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
2729  escaped(orig_summary));
2730  return NULL;
2731  }
2732 
2733  unsigned low, high;
2734  int ok;
2735  low = (unsigned) tor_parse_ulong(summary, 10, 1, 65535, &ok, &next);
2736  if (!ok) {
2737  if (! TOR_ISDIGIT(*summary) || *summary == ',') {
2738  /* Unrecognized format: skip it. */
2739  goto skip_ent;
2740  } else {
2741  goto bad_ent;
2742  }
2743  }
2744 
2745  switch (*next) {
2746  case ',':
2747  ++next;
2748  FALLTHROUGH;
2749  case '\0':
2750  high = low;
2751  break;
2752  case '-':
2753  high = (unsigned) tor_parse_ulong(next+1, 10, low, 65535, &ok, &next);
2754  if (!ok)
2755  goto bad_ent;
2756 
2757  if (*next == ',')
2758  ++next;
2759  else if (*next != '\0')
2760  goto bad_ent;
2761 
2762  break;
2763  default:
2764  goto bad_ent;
2765  }
2766 
2767  entries[n_entries].min_port = low;
2768  entries[n_entries].max_port = high;
2769  n_entries++;
2770 
2771  continue;
2772  skip_ent:
2773  next = strchr(next, ',');
2774  if (!next)
2775  break;
2776  ++next;
2777  }
2778 
2779  if (n_entries == 0) {
2780  log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2781  "Found no port-range entries in summary %s", escaped(orig_summary));
2782  return NULL;
2783  }
2784 
2785  {
2786  size_t size = offsetof(short_policy_t, entries) +
2787  sizeof(short_policy_entry_t)*(n_entries);
2788  result = tor_malloc_zero(size);
2789 
2790  tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
2791  }
2792 
2793  result->is_accept = is_accept;
2794  result->n_entries = n_entries;
2795  memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
2796  return result;
2797 
2798  bad_ent:
2799  log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
2800  escaped(orig_summary));
2801  return NULL;
2802 }
2803 
2804 /** Write <b>policy</b> back out into a string. */
2805 char *
2807 {
2808  int i;
2809  char *answer;
2810  smartlist_t *sl = smartlist_new();
2811 
2812  smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
2813 
2814  for (i=0; i < policy->n_entries; i++) {
2815  const short_policy_entry_t *e = &policy->entries[i];
2816  if (e->min_port == e->max_port) {
2817  smartlist_add_asprintf(sl, "%d", e->min_port);
2818  } else {
2819  smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
2820  }
2821  if (i < policy->n_entries-1)
2822  smartlist_add_strdup(sl, ",");
2823  }
2824  answer = smartlist_join_strings(sl, "", 0, NULL);
2825  SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
2826  smartlist_free(sl);
2827  return answer;
2828 }
2829 
2830 /** Release all storage held in <b>policy</b>. */
2831 void
2833 {
2834  tor_free(policy);
2835 }
2836 
2837 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
2838  * or rejected by the summarized policy <b>policy</b>. Return values are as
2839  * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
2840  * functions, requires the <b>port</b> be specified. */
2843  const short_policy_t *policy)
2844 {
2845  int i;
2846  int found_match = 0;
2847  int accept_;
2848 
2849  tor_assert(port != 0);
2850 
2851  if (addr && tor_addr_is_null(addr))
2852  addr = NULL; /* Unspec means 'no address at all,' in this context. */
2853 
2854  if (addr && get_options()->ClientRejectInternalAddresses &&
2855  (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
2856  return ADDR_POLICY_REJECTED;
2857 
2858  for (i=0; i < policy->n_entries; ++i) {
2859  const short_policy_entry_t *e = &policy->entries[i];
2860  if (e->min_port <= port && port <= e->max_port) {
2861  found_match = 1;
2862  break;
2863  }
2864  }
2865 
2866  if (found_match)
2867  accept_ = policy->is_accept;
2868  else
2869  accept_ = ! policy->is_accept;
2870 
2871  /* ???? are these right? -NM */
2872  /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
2873  * case here, because it would cause clients to believe that the node
2874  * allows exit enclaving. Trying it anyway would open up a cool attack
2875  * where the node refuses due to exitpolicy, the client reacts in
2876  * surprise by rewriting the node's exitpolicy to reject *:*, and then
2877  * an adversary targets users by causing them to attempt such connections
2878  * to 98% of the exits.
2879  *
2880  * Once microdescriptors can handle addresses in special cases (e.g. if
2881  * we ever solve ticket 1774), we can provide certainty here. -RD */
2882  if (accept_)
2884  else
2885  return ADDR_POLICY_REJECTED;
2886 }
2887 
2888 /** Return true iff <b>policy</b> seems reject all ports */
2889 int
2891 {
2892  /* This doesn't need to be as much on the lookout as policy_is_reject_star,
2893  * since policy summaries are from the consensus or from consensus
2894  * microdescs.
2895  */
2896  tor_assert(policy);
2897  /* Check for an exact match of "reject 1-65535". */
2898  return (policy->is_accept == 0 && policy->n_entries == 1 &&
2899  policy->entries[0].min_port == 1 &&
2900  policy->entries[0].max_port == 65535);
2901 }
2902 
2903 /** Decide whether addr:port is probably or definitely accepted or rejected by
2904  * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
2905  * interpretation. */
2907 compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
2908  const node_t *node)
2909 {
2910  if (node->rejects_all)
2911  return ADDR_POLICY_REJECTED;
2912 
2913  if (addr && tor_addr_family(addr) == AF_INET6) {
2914  const short_policy_t *p = NULL;
2915  if (node->ri)
2916  p = node->ri->ipv6_exit_policy;
2917  else if (node->md)
2918  p = node->md->ipv6_exit_policy;
2919  if (p)
2920  return compare_tor_addr_to_short_policy(addr, port, p);
2921  else
2922  return ADDR_POLICY_REJECTED;
2923  }
2924 
2925  if (node->ri) {
2926  return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
2927  } else if (node->md) {
2928  if (node->md->exit_policy == NULL)
2929  return ADDR_POLICY_REJECTED;
2930  else
2931  return compare_tor_addr_to_short_policy(addr, port,
2932  node->md->exit_policy);
2933  } else {
2935  }
2936 }
2937 
2938 /**
2939  * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
2940  * representation of the list.
2941  * If <b>include_ipv4</b> is true, include IPv4 entries.
2942  * If <b>include_ipv6</b> is true, include IPv6 entries.
2943  */
2944 char *
2946  int include_ipv4,
2947  int include_ipv6)
2948 {
2949  smartlist_t *policy_string_list;
2950  char *policy_string = NULL;
2951 
2952  policy_string_list = smartlist_new();
2953 
2954  SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
2955  char *pbuf;
2956  int bytes_written_to_pbuf;
2957  if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2958  continue; /* Don't include IPv6 parts of address policy */
2959  }
2960  if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2961  continue; /* Don't include IPv4 parts of address policy */
2962  }
2963 
2964  pbuf = tor_malloc(POLICY_BUF_LEN);
2965  bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2966 
2967  if (bytes_written_to_pbuf < 0) {
2968  log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
2969  tor_free(pbuf);
2970  goto done;
2971  }
2972 
2973  smartlist_add(policy_string_list,pbuf);
2974  } SMARTLIST_FOREACH_END(tmpe);
2975 
2976  policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
2977 
2978  done:
2979  SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
2980  smartlist_free(policy_string_list);
2981 
2982  return policy_string;
2983 }
2984 
2985 /** Implementation for GETINFO control command: knows the answer for questions
2986  * about "exit-policy/..." */
2987 int
2989  const char *question, char **answer,
2990  const char **errmsg)
2991 {
2992  (void) conn;
2993  (void) errmsg;
2994  if (!strcmp(question, "exit-policy/default")) {
2995  *answer = tor_strdup(DEFAULT_EXIT_POLICY);
2996  } else if (!strcmp(question, "exit-policy/reject-private/default")) {
2997  smartlist_t *private_policy_strings;
2998  const char **priv = private_nets;
2999 
3000  private_policy_strings = smartlist_new();
3001 
3002  while (*priv != NULL) {
3003  /* IPv6 addresses are in "[]" and contain ":",
3004  * IPv4 addresses are not in "[]" and contain "." */
3005  smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
3006  priv++;
3007  }
3008 
3009  *answer = smartlist_join_strings(private_policy_strings,
3010  ",", 0, NULL);
3011 
3012  SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
3013  smartlist_free(private_policy_strings);
3014  } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
3015  const or_options_t *options = get_options();
3016  int err = 0;
3018 
3019  if (!me) {
3020  *errmsg = routerinfo_err_to_string(err);
3021  return routerinfo_err_is_transient(err) ? -1 : 0;
3022  }
3023 
3024  if (!options->ExitPolicyRejectPrivate &&
3025  !options->ExitPolicyRejectLocalInterfaces) {
3026  *answer = tor_strdup("");
3027  return 0;
3028  }
3029 
3030  smartlist_t *private_policy_list = smartlist_new();
3031  smartlist_t *configured_addresses = smartlist_new();
3032 
3033  /* Copy the configured addresses into the tor_addr_t* list */
3034  if (options->ExitPolicyRejectPrivate) {
3035  policies_copy_addr_to_smartlist(configured_addresses, &me->ipv4_addr);
3036  policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
3037  }
3038 
3039  if (options->ExitPolicyRejectLocalInterfaces) {
3040  policies_copy_outbound_addresses_to_smartlist(configured_addresses,
3041  options);
3042  }
3043 
3045  &private_policy_list,
3046  options->IPv6Exit,
3047  configured_addresses,
3050  *answer = policy_dump_to_string(private_policy_list, 1, 1);
3051 
3052  addr_policy_list_free(private_policy_list);
3053  SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
3054  smartlist_free(configured_addresses);
3055  } else if (!strcmpstart(question, "exit-policy/")) {
3056  int include_ipv4 = 0;
3057  int include_ipv6 = 0;
3058 
3059  int err = 0;
3061 
3062  if (!me) {
3063  *errmsg = routerinfo_err_to_string(err);
3064  return routerinfo_err_is_transient(err) ? -1 : 0;
3065  }
3066 
3067  if (!strcmp(question, "exit-policy/ipv4")) {
3068  include_ipv4 = 1;
3069  } else if (!strcmp(question, "exit-policy/ipv6")) {
3070  include_ipv6 = 1;
3071  } else if (!strcmp(question, "exit-policy/full")) {
3072  include_ipv4 = include_ipv6 = 1;
3073  } else {
3074  return 0; /* No such key. */
3075  }
3076 
3077  *answer = router_dump_exit_policy_to_string(me,include_ipv4,
3078  include_ipv6);
3079  }
3080 
3081  return 0;
3082 }
3083 
3084 /** Release all storage held by <b>p</b>. */
3085 void
3087 {
3088  if (!lst)
3089  return;
3090  SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
3091  smartlist_free(lst);
3092 }
3093 
3094 /** Release all storage held by <b>p</b>. */
3095 void
3097 {
3098  if (!p)
3099  return;
3100 
3101  if (--p->refcnt <= 0) {
3102  if (p->is_canonical) {
3103  policy_map_ent_t search, *found;
3104  search.policy = p;
3105  found = HT_REMOVE(policy_map, &policy_root, &search);
3106  if (found) {
3107  tor_assert(p == found->policy);
3108  tor_free(found);
3109  }
3110  }
3111  tor_free(p);
3112  }
3113 }
3114 
3115 /** Release all storage held by policy variables. */
3116 void
3118 {
3119  addr_policy_list_free(reachable_or_addr_policy);
3120  reachable_or_addr_policy = NULL;
3121  addr_policy_list_free(reachable_dir_addr_policy);
3123  addr_policy_list_free(socks_policy);
3124  socks_policy = NULL;
3125  addr_policy_list_free(dir_policy);
3126  dir_policy = NULL;
3127  addr_policy_list_free(metrics_policy);
3128  metrics_policy = NULL;
3129  addr_policy_list_free(authdir_reject_policy);
3130  authdir_reject_policy = NULL;
3131  addr_policy_list_free(authdir_invalid_policy);
3132  authdir_invalid_policy = NULL;
3133  addr_policy_list_free(authdir_badexit_policy);
3134  authdir_badexit_policy = NULL;
3135  addr_policy_list_free(authdir_middleonly_policy);
3137 
3138  if (!HT_EMPTY(&policy_root)) {
3139  policy_map_ent_t **ent;
3140  int n = 0;
3141  char buf[POLICY_BUF_LEN];
3142 
3143  log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
3144  (int)HT_SIZE(&policy_root));
3145 
3146  /* Note the first 10 cached policies to try to figure out where they
3147  * might be coming from. */
3148  HT_FOREACH(ent, policy_map, &policy_root) {
3149  if (++n > 10)
3150  break;
3151  if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
3152  log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
3153  }
3154  }
3155  HT_CLEAR(policy_map, &policy_root);
3156 }
Address policy structures.
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition: address.c:805
int tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2, maskbits_t mbits, tor_addr_comparison_t how)
Definition: address.c:1005
int tor_addr_is_v4(const tor_addr_t *addr)
Definition: address.c:750
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:984
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:780
int tor_addr_is_multicast(const tor_addr_t *a)
Definition: address.c:1624
int tor_addr_parse_mask_ports(const char *s, unsigned flags, tor_addr_t *addr_out, maskbits_t *maskbits_out, uint16_t *port_min_out, uint16_t *port_max_out)
Definition: address.c:543
smartlist_t * get_interface_address6_list(int severity, sa_family_t family, int include_internal)
Definition: address.c:1777
void tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:947
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const uint8_t *ipv6_bytes)
Definition: address.c:900
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:160
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:327
#define fmt_addr(a)
Definition: address.h:239
#define TOR_ADDR_BUF_LEN
Definition: address.h:224
uint8_t maskbits_t
Definition: address.h:62
Header file for circuitbuild.c.
const smartlist_t * get_configured_ports(void)
Definition: config.c:6674
const or_options_t * get_options(void)
Definition: config.c:926
const char * name
Definition: config.c:2443
Header file for config.c.
Header for confline.c.
int16_t country_t
Definition: country.h:17
Common functions for using (pseudo-)random number generators.
Trusted/fallback directory server structure.
const char * escaped(const char *s)
Definition: escape.c:126
const char * geoip_get_country_name(country_t num)
Definition: geoip.c:447
int geoip_get_country_by_addr(const tor_addr_t *addr)
Definition: geoip.c:424
Header file for geoip.c.
HT_PROTOTYPE(hs_circuitmap_ht, circuit_t, hs_circuitmap_node, hs_circuit_hash_token, hs_circuits_have_same_token)
typedef HT_HEAD(hs_service_ht, hs_service_t) hs_service_ht
uint16_t sa_family_t
Definition: inaddr_st.h:77
#define log_fn(severity, domain, args,...)
Definition: log.h:283
#define LD_PROTOCOL
Definition: log.h:72
#define LD_MM
Definition: log.h:74
#define LD_BUG
Definition: log.h:86
#define LD_DIR
Definition: log.h:88
#define LD_CONFIG
Definition: log.h:68
#define LOG_INFO
Definition: log.h:45
void tor_free_(void *mem)
Definition: malloc.c:227
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition: malloc.c:146
#define tor_free(p)
Definition: malloc.h:56
Header file for microdesc.c.
Microdescriptor structure.
Header file for networkstatus.c.
Node information structure.
void node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1821
void node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1922
int node_ipv6_dir_preferred(const node_t *node)
Definition: nodelist.c:1899
void node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1960
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:226
int node_ipv6_or_preferred(const node_t *node)
Definition: nodelist.c:1791
void node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1857
Header file for nodelist.c.
Master header file for Tor-specific functionality.
@ OUTBOUND_ADDR_MAX
Definition: or_options_st.h:48
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
Definition: parse_int.c:78
void addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
Definition: policies.c:1617
static smartlist_t * metrics_policy
Definition: policies.c:52
void addr_policy_free_(addr_policy_t *p)
Definition: policies.c:3096
int addr_policies_eq(const smartlist_t *a, const smartlist_t *b)
Definition: policies.c:1324
static int addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port, smartlist_t *policy)
Definition: policies.c:379
static int addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
Definition: policies.c:1582
static int addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
Definition: policies.c:1558
int reachable_addr_prefer_ipv6_dirport(const or_options_t *options)
Definition: policies.c:512
static smartlist_t * dir_policy
Definition: policies.c:50
int policies_parse_exit_policy_from_options(const or_options_t *or_options, const tor_addr_t *ipv4_local_address, const tor_addr_t *ipv6_local_address, smartlist_t **result)
Definition: policies.c:2123
static int parse_reachable_addresses(void)
Definition: policies.c:262
static int exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
Definition: policies.c:2202
static int single_addr_policy_eq(const addr_policy_t *a, const addr_policy_t *b)
Definition: policies.c:1300
#define MAX_EXITPOLICY_SUMMARY_LEN
Definition: policies.c:45
static smartlist_t * authdir_invalid_policy
Definition: policies.c:58
static int reachable_addr_prefer_ipv6_impl(const or_options_t *options)
Definition: policies.c:466
static void policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
Definition: policies.c:2552
int reachable_addr_prefer_ipv6_orport(const or_options_t *options)
Definition: policies.c:490
static smartlist_t * authdir_middleonly_policy
Definition: policies.c:64
void policy_expand_private(smartlist_t **policy)
Definition: policies.c:110
static const char * private_nets[]
Definition: policies.c:88
int reachable_addr_allows_rs(const routerstatus_t *rs, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:647
static smartlist_t * policy_summary_create(void)
Definition: policies.c:2364
int firewall_is_fascist_or(void)
Definition: policies.c:359
int metrics_policy_permits_address(const tor_addr_t *addr)
Definition: policies.c:1072
STATIC int reachable_addr_allows(const tor_addr_t *addr, uint16_t port, smartlist_t *firewall_policy, int pref_only, int pref_ipv6)
Definition: policies.c:412
void policies_parse_exit_policy_reject_private(smartlist_t **dest, int ipv6_exit, const smartlist_t *configured_addresses, int reject_interface_addresses, int reject_configured_port_addresses)
Definition: policies.c:1805
static void policy_summary_accept(smartlist_t *summary, uint16_t prt_min, uint16_t prt_max, sa_family_t family)
Definition: policies.c:2464
short_policy_t * parse_short_policy(const char *summary)
Definition: policies.c:2705
static int reachable_addr_allows_md_impl(const microdesc_t *md, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:671
void addr_policy_append_reject_addr_list(smartlist_t **dest, const smartlist_t *addrs)
Definition: policies.c:1674
static int reachable_addr_allows_rs_impl(const routerstatus_t *rs, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:625
static const tor_addr_port_t * reachable_addr_choose_impl(const tor_addr_port_t *a, const tor_addr_port_t *b, int want_a, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:754
static void policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list, const or_options_t *or_options)
Definition: policies.c:2083
static int addr_is_in_cc_list(const tor_addr_t *addr, const smartlist_t *cc_list)
Definition: policies.c:1080
int reachable_addr_allows_addr(const tor_addr_t *addr, uint16_t port, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:536
void reachable_addr_choose_from_node(const node_t *node, firewall_connection_t fw_connection, int pref_only, tor_addr_port_t *ap)
Definition: policies.c:988
void reachable_addr_choose_from_dir_server(const dir_server_t *ds, firewall_connection_t fw_connection, int pref_only, tor_addr_port_t *ap)
Definition: policies.c:1027
char * policy_dump_to_string(const smartlist_t *policy_list, int include_ipv4, int include_ipv6)
Definition: policies.c:2945
int reachable_addr_allows_node(const node_t *node, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:693
static void exit_policy_remove_redundancies(smartlist_t *dest)
Definition: policies.c:1703
static void policy_summary_reject(smartlist_t *summary, maskbits_t maskbits, uint16_t prt_min, uint16_t prt_max, sa_family_t family)
Definition: policies.c:2487
static void addr_policy_append_reject_addr_list_filter(smartlist_t **dest, const smartlist_t *addrs, int ipv4_rules, int ipv6_rules)
Definition: policies.c:1688
int getinfo_helper_policies(control_connection_t *conn, const char *question, char **answer, const char **errmsg)
Definition: policies.c:2988
void reachable_addr_choose_from_ls(const smartlist_t *lspecs, int pref_only, tor_addr_port_t *ap)
Definition: policies.c:913
STATIC void append_exit_policy_string(smartlist_t **policy, const char *more)
Definition: policies.c:1603
void reachable_addr_choose_from_rs(const routerstatus_t *rs, firewall_connection_t fw_connection, int pref_only, tor_addr_port_t *ap)
Definition: policies.c:874
static addr_policy_result_t compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr, const smartlist_t *policy)
Definition: policies.c:1441
int policies_parse_from_options(const or_options_t *options)
Definition: policies.c:1268
int authdir_policy_badexit_address(const tor_addr_t *addr, uint16_t port)
Definition: policies.c:1118
int reachable_addr_allows_dir_server(const dir_server_t *ds, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:731
static void policies_log_first_redundant_entry(const smartlist_t *policy)
Definition: policies.c:1862
void policies_set_node_exitpolicy_to_reject_all(node_t *node)
Definition: policies.c:2194
static policy_summary_item_t * policy_summary_item_split(policy_summary_item_t *old, uint16_t new_starts)
Definition: policies.c:2388
static smartlist_t * reachable_or_addr_policy
Definition: policies.c:68
static int load_policy_from_option(config_line_t *config, const char *option_name, smartlist_t **policy, int assume_action)
Definition: policies.c:1215
addr_policy_result_t compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port, const smartlist_t *policy)
Definition: policies.c:1536
char * write_short_policy(const short_policy_t *policy)
Definition: policies.c:2806
static addr_policy_result_t compare_unknown_tor_addr_to_addr_policy(uint16_t port, const smartlist_t *policy)
Definition: policies.c:1484
int policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest, exit_policy_parser_cfg_t options, const smartlist_t *configured_addresses)
Definition: policies.c:2040
static smartlist_t * reachable_dir_addr_policy
Definition: policies.c:71
static int policy_using_default_exit_options(const or_options_t *or_options)
Definition: policies.c:1142
static addr_policy_result_t compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port, const smartlist_t *policy)
Definition: policies.c:1413
int reachable_addr_use_ipv6(const or_options_t *options)
Definition: policies.c:451
addr_policy_result_t compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port, const short_policy_t *policy)
Definition: policies.c:2842
int firewall_is_fascist_dir(void)
Definition: policies.c:370
static smartlist_t * authdir_badexit_policy
Definition: policies.c:61
static unsigned int policy_hash(const policy_map_ent_t *ent)
Definition: policies.c:1359
int dir_policy_permits_address(const tor_addr_t *addr)
Definition: policies.c:1054
void policy_expand_unspec(smartlist_t **policy)
Definition: policies.c:150
addr_policy_t * addr_policy_get_canonical_entry(addr_policy_t *e)
Definition: policies.c:1389
int authdir_policy_permits_address(const tor_addr_t *addr, uint16_t port)
Definition: policies.c:1096
void policies_free_all(void)
Definition: policies.c:3117
void addr_policy_list_free_(smartlist_t *lst)
Definition: policies.c:3086
void short_policy_free_(short_policy_t *policy)
Definition: policies.c:2832
static smartlist_t * socks_policy
Definition: policies.c:48
static int reachable_addr_allows_ri_impl(const routerinfo_t *ri, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:608
int validate_addr_policies(const or_options_t *options, char **msg)
Definition: policies.c:1152
int authdir_policy_middleonly_address(const tor_addr_t *addr, uint16_t port)
Definition: policies.c:1129
int socks_policy_permits_address(const tor_addr_t *addr)
Definition: policies.c:1063
static void policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
Definition: policies.c:2066
STATIC const tor_addr_port_t * reachable_addr_choose(const tor_addr_port_t *a, const tor_addr_port_t *b, int want_a, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:792
int policy_is_reject_star(const smartlist_t *policy, sa_family_t family, int default_reject)
Definition: policies.c:2264
static smartlist_t * authdir_reject_policy
Definition: policies.c:55
addr_policy_result_t compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port, const node_t *node)
Definition: policies.c:2907
int authdir_policy_valid_address(const tor_addr_t *addr, uint16_t port)
Definition: policies.c:1107
static void reachable_addr_choose_base(const tor_addr_t *ipv4_addr, uint16_t ipv4_orport, uint16_t ipv4_dirport, const tor_addr_t *ipv6_addr, uint16_t ipv6_orport, uint16_t ipv6_dirport, firewall_connection_t fw_connection, int pref_only, int pref_ipv6, tor_addr_port_t *ap)
Definition: policies.c:825
static int policies_parse_exit_policy_internal(config_line_t *cfg, smartlist_t **dest, int ipv6_exit, int rejectprivate, const smartlist_t *configured_addresses, int reject_interface_addresses, int reject_configured_port_addresses, int add_default_policy, int add_reduced_policy)
Definition: policies.c:1972
int short_policy_is_reject_star(const short_policy_t *policy)
Definition: policies.c:2890
static int policy_summary_split(smartlist_t *summary, uint16_t prt_min, uint16_t prt_max)
Definition: policies.c:2433
static int parse_metrics_port_policy(const or_options_t *options)
Definition: policies.c:1254
static int reachable_addr_allows_base(const tor_addr_t *ipv4_addr, uint16_t ipv4_orport, uint16_t ipv4_dirport, const tor_addr_t *ipv6_addr, uint16_t ipv6_orport, uint16_t ipv6_dirport, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:578
int exit_policy_is_general_exit(smartlist_t *policy)
Definition: policies.c:2250
char * policy_summarize(smartlist_t *policy, sa_family_t family)
Definition: policies.c:2593
static int parse_addr_policy(config_line_t *cfg, smartlist_t **dest, int assume_action)
Definition: policies.c:199
void policies_exit_policy_append_reject_star(smartlist_t **dest)
Definition: policies.c:2186
int policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy, int format_for_desc)
Definition: policies.c:2288
static int reachable_addr_allows_ap(const tor_addr_port_t *ap, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:561
Header file for policies.c.
addr_policy_result_t
Definition: policies.h:38
@ ADDR_POLICY_PROBABLY_ACCEPTED
Definition: policies.h:45
@ ADDR_POLICY_ACCEPTED
Definition: policies.h:40
@ ADDR_POLICY_PROBABLY_REJECTED
Definition: policies.h:48
@ ADDR_POLICY_REJECTED
Definition: policies.h:42
addr_policy_t * router_parse_addr_policy_item_from_string(const char *s, int assume_action, int *malformed_list)
Definition: policy_parse.c:44
Header file for policy_parse.c.
Listener port configuration structure.
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
const char * routerinfo_err_to_string(int err)
Definition: router.c:157
const routerinfo_t * router_get_my_routerinfo_with_err(int *err)
Definition: router.c:1811
char * router_dump_exit_policy_to_string(const routerinfo_t *router, int include_ipv4, int include_ipv6)
Definition: router.c:3155
int routerinfo_err_is_transient(int err)
Definition: router.c:186
Header file for router.c.
Router descriptor structure.
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
int server_mode(const or_options_t *options)
Definition: routermode.c:34
Header file for routermode.c.
Routerstatus (consensus entry) structure.
int smartlist_contains_string_case(const smartlist_t *sl, const char *element)
Definition: smartlist.c:133
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
void smartlist_insert(smartlist_t *sl, int idx, void *val)
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
smartlist_t * smartlist_new(void)
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
#define SMARTLIST_REPLACE_CURRENT(sl, var, val)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
addr_policy_action_bitfield_t policy_type
uint16_t prt_max
unsigned int is_private
uint16_t prt_min
maskbits_t maskbits
unsigned int is_canonical
tor_addr_t addr
routerstatus_t fake_status
Definition: dir_server_st.h:57
uint16_t ipv6_orport
Definition: microdesc_st.h:81
struct short_policy_t * exit_policy
Definition: microdesc_st.h:85
tor_addr_t ipv6_addr
Definition: microdesc_st.h:79
struct short_policy_t * ipv6_exit_policy
Definition: microdesc_st.h:87
Definition: node_st.h:34
unsigned int rejects_all
Definition: node_st.h:85
struct config_line_t * AuthDirInvalid
int ClientPreferIPv6DirPort
struct config_line_t * AuthDirReject
int ExitPolicyRejectPrivate
struct config_line_t * AuthDirMiddleOnly
struct config_line_t * MetricsPortPolicy
int ClientPreferIPv6ORPort
struct config_line_t * SocksPolicy
struct config_line_t * ReachableORAddresses
struct config_line_t * ReachableDirAddresses
tor_addr_t OutboundBindAddresses[OUTBOUND_ADDR_MAX][2]
int ExitPolicyRejectLocalInterfaces
struct config_line_t * DirPolicy
struct config_line_t * ExitPolicy
struct config_line_t * ReachableAddresses
struct config_line_t * AuthDirBadExit
uint64_t reject_count
Definition: policies.c:77
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:30
tor_addr_t ipv4_addr
Definition: routerinfo_st.h:25
smartlist_t * exit_policy
Definition: routerinfo_st.h:59
struct short_policy_t * ipv6_exit_policy
Definition: routerinfo_st.h:63
uint16_t ipv6_orport
tor_addr_t ipv6_addr
char identity_digest[DIGEST_LEN]
uint16_t ipv4_dirport
uint16_t ipv4_orport
Definition: policies.h:52
unsigned int n_entries
Definition: policies.h:62
unsigned int is_accept
Definition: policies.h:60
short_policy_entry_t entries[FLEXIBLE_ARRAY_MEMBER]
Definition: policies.h:67
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
#define tor_assert(expr)
Definition: util_bug.h:102
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:215