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