1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Code to parse and use address policies and exit policies.
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.
18 #define POLICIES_PRIVATE
20 #include "core/or/or.h"
21 #include "feature/client/bridges.h"
22 #include "app/config/config.h"
23 #include "core/or/policies.h"
24 #include "feature/dirparse/policy_parse.h"
25 #include "feature/nodelist/microdesc.h"
26 #include "feature/nodelist/networkstatus.h"
27 #include "feature/nodelist/nodelist.h"
28 #include "feature/relay/router.h"
29 #include "feature/relay/routermode.h"
30 #include "lib/geoip/geoip.h"
32 #include "lib/crypt_ops/crypto_rand.h"
33 #include "lib/encoding/confline.h"
34 #include "trunnel/ed25519_cert.h"
36 #include "core/or/addr_policy_st.h"
37 #include "feature/dirclient/dir_server_st.h"
38 #include "feature/nodelist/microdesc_st.h"
39 #include "feature/nodelist/node_st.h"
40 #include "core/or/port_cfg_st.h"
41 #include "feature/nodelist/routerinfo_st.h"
42 #include "feature/nodelist/routerstatus_st.h"
44 /** Maximum length of an exit policy summary. */
45 #define MAX_EXITPOLICY_SUMMARY_LEN 1000
47 /** Policy that addresses for incoming SOCKS connections must match. */
48 static smartlist_t
*socks_policy
= NULL
;
49 /** Policy that addresses for incoming directory connections must match. */
50 static smartlist_t
*dir_policy
= NULL
;
51 /** Policy for incoming MetricsPort connections that must match. */
52 static smartlist_t
*metrics_policy
= NULL
;
53 /** Policy that addresses for incoming router descriptors must match in order
54 * to be published by us. */
55 static smartlist_t
*authdir_reject_policy
= NULL
;
56 /** Policy that addresses for incoming router descriptors must match in order
57 * to be marked as valid in our networkstatus. */
58 static smartlist_t
*authdir_invalid_policy
= NULL
;
59 /** Policy that addresses for incoming router descriptors must <b>not</b>
60 * match in order to not be marked as BadExit. */
61 static smartlist_t
*authdir_badexit_policy
= NULL
;
62 /** Policy that addresses for incoming router descriptors must <b>not</b>
63 * match in order to not be marked as MiddleOnly. */
64 static smartlist_t
*authdir_middleonly_policy
= NULL
;
66 /** Parsed addr_policy_t describing which addresses we believe we can start
68 static smartlist_t
*reachable_or_addr_policy
= NULL
;
69 /** Parsed addr_policy_t describing which addresses we believe we can connect
70 * to directories at. */
71 static smartlist_t
*reachable_dir_addr_policy
= NULL
;
73 /** Element of an exit policy summary */
74 typedef struct policy_summary_item_t
{
75 uint16_t prt_min
; /**< Lowest port number to accept/reject. */
76 uint16_t prt_max
; /**< Highest port number to accept/reject. */
77 uint64_t reject_count
; /**< Number of IP-Addresses that are rejected to
79 unsigned int accepted
:1; /** Has this port already been accepted */
80 } policy_summary_item_t
;
82 /** Private networks. This list is used in two places, once to expand the
83 * "private" keyword when parsing our own exit policy, secondly to ignore
84 * just such networks when building exit policy summaries. It is important
85 * that all authorities agree on that list when creating summaries, so don't
86 * just change this without a proper migration plan and a proposal and stuff.
88 static const char *private_nets
[] = {
89 "0.0.0.0/8", "169.254.0.0/16",
90 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
92 "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
96 static int policies_parse_exit_policy_internal(
101 const smartlist_t
*configured_addresses
,
102 int reject_interface_addresses
,
103 int reject_configured_port_addresses
,
104 int add_default_policy
,
105 int add_reduced_policy
);
107 /** Replace all "private" entries in *<b>policy</b> with their expanded
110 policy_expand_private(smartlist_t
**policy
)
112 uint16_t port_min
, port_max
;
117 if (!*policy
) /*XXXX disallow NULL policies? */
120 tmp
= smartlist_new();
122 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
123 if (! p
->is_private
) {
124 smartlist_add(tmp
, p
);
127 for (i
= 0; private_nets
[i
]; ++i
) {
128 addr_policy_t newpolicy
;
129 memcpy(&newpolicy
, p
, sizeof(addr_policy_t
));
130 newpolicy
.is_private
= 0;
131 newpolicy
.is_canonical
= 0;
132 if (tor_addr_parse_mask_ports(private_nets
[i
], 0,
134 &newpolicy
.maskbits
, &port_min
, &port_max
)<0) {
135 tor_assert_unreached();
137 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy
));
140 } SMARTLIST_FOREACH_END(p
);
142 smartlist_free(*policy
);
146 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
147 * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
148 * specific and one IPv6-specific. */
150 policy_expand_unspec(smartlist_t
**policy
)
156 tmp
= smartlist_new();
157 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
158 sa_family_t family
= tor_addr_family(&p
->addr
);
159 if (family
== AF_INET6
|| family
== AF_INET
|| p
->is_private
) {
160 smartlist_add(tmp
, p
);
161 } else if (family
== AF_UNSPEC
) {
162 addr_policy_t newpolicy_ipv4
;
163 addr_policy_t newpolicy_ipv6
;
164 memcpy(&newpolicy_ipv4
, p
, sizeof(addr_policy_t
));
165 memcpy(&newpolicy_ipv6
, p
, sizeof(addr_policy_t
));
166 newpolicy_ipv4
.is_canonical
= 0;
167 newpolicy_ipv6
.is_canonical
= 0;
168 if (p
->maskbits
!= 0) {
169 log_warn(LD_BUG
, "AF_UNSPEC policy with maskbits==%d", p
->maskbits
);
170 newpolicy_ipv4
.maskbits
= 0;
171 newpolicy_ipv6
.maskbits
= 0;
173 tor_addr_from_ipv4h(&newpolicy_ipv4
.addr
, 0);
174 tor_addr_from_ipv6_bytes(&newpolicy_ipv6
.addr
,
175 (const uint8_t *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
176 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv4
));
177 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv6
));
180 log_warn(LD_BUG
, "Funny-looking address policy with family %d", family
);
181 smartlist_add(tmp
, p
);
183 } SMARTLIST_FOREACH_END(p
);
185 smartlist_free(*policy
);
190 * Given a linked list of config lines containing "accept[6]" and "reject[6]"
191 * tokens, parse them and append the result to <b>dest</b>. Return -1
192 * if any tokens are malformed (and don't append any), else return 0.
194 * If <b>assume_action</b> is nonnegative, then insert its action
195 * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
199 parse_addr_policy(config_line_t
*cfg
, smartlist_t
**dest
,
203 smartlist_t
*entries
;
211 result
= smartlist_new();
212 entries
= smartlist_new();
213 for (; cfg
; cfg
= cfg
->next
) {
214 smartlist_split_string(entries
, cfg
->value
, ",",
215 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
216 SMARTLIST_FOREACH_BEGIN(entries
, const char *, ent
) {
217 log_debug(LD_CONFIG
,"Adding new entry '%s'",ent
);
219 item
= router_parse_addr_policy_item_from_string(ent
, assume_action
,
222 smartlist_add(result
, item
);
223 } else if (malformed_list
) {
224 /* the error is so severe the entire list should be discarded */
225 log_warn(LD_CONFIG
, "Malformed policy '%s'. Discarding entire policy "
229 /* the error is minor: don't add the item, but keep processing the
230 * rest of the policies in the list */
231 log_debug(LD_CONFIG
, "Ignored policy '%s' due to non-fatal error. "
232 "The remainder of the policy list will be used.",
235 } SMARTLIST_FOREACH_END(ent
);
236 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
237 smartlist_clear(entries
);
239 smartlist_free(entries
);
241 addr_policy_list_free(result
);
243 policy_expand_private(&result
);
244 policy_expand_unspec(&result
);
247 smartlist_add_all(*dest
, result
);
248 smartlist_free(result
);
257 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
258 * reachable_(or|dir)_addr_policy. The options should already have
259 * been validated by validate_addr_policies.
262 parse_reachable_addresses(void)
264 const or_options_t
*options
= get_options();
267 if (options
->ReachableDirAddresses
&&
268 options
->ReachableORAddresses
&&
269 options
->ReachableAddresses
) {
271 "Both ReachableDirAddresses and ReachableORAddresses are set. "
272 "ReachableAddresses setting will be ignored.");
274 addr_policy_list_free(reachable_or_addr_policy
);
275 reachable_or_addr_policy
= NULL
;
276 if (!options
->ReachableORAddresses
&& options
->ReachableAddresses
)
278 "Using ReachableAddresses as ReachableORAddresses.");
279 if (parse_addr_policy(options
->ReachableORAddresses
?
280 options
->ReachableORAddresses
:
281 options
->ReachableAddresses
,
282 &reachable_or_addr_policy
, ADDR_POLICY_ACCEPT
)) {
284 "Error parsing Reachable%sAddresses entry; ignoring.",
285 options
->ReachableORAddresses
? "OR" : "");
289 addr_policy_list_free(reachable_dir_addr_policy
);
290 reachable_dir_addr_policy
= NULL
;
291 if (!options
->ReachableDirAddresses
&& options
->ReachableAddresses
)
293 "Using ReachableAddresses as ReachableDirAddresses");
294 if (parse_addr_policy(options
->ReachableDirAddresses
?
295 options
->ReachableDirAddresses
:
296 options
->ReachableAddresses
,
297 &reachable_dir_addr_policy
, ADDR_POLICY_ACCEPT
)) {
298 if (options
->ReachableDirAddresses
)
300 "Error parsing ReachableDirAddresses entry; ignoring.");
304 /* We ignore ReachableAddresses for relays */
305 if (!server_mode(options
)) {
306 if (policy_is_reject_star(reachable_or_addr_policy
, AF_UNSPEC
, 0)
307 || policy_is_reject_star(reachable_dir_addr_policy
, AF_UNSPEC
,0)) {
308 log_warn(LD_CONFIG
, "Tor cannot connect to the Internet if "
309 "ReachableAddresses, ReachableORAddresses, or "
310 "ReachableDirAddresses reject all addresses. Please accept "
311 "some addresses in these options.");
312 } else if (options
->ClientUseIPv4
== 1
313 && (policy_is_reject_star(reachable_or_addr_policy
, AF_INET
, 0)
314 || policy_is_reject_star(reachable_dir_addr_policy
, AF_INET
, 0))) {
315 log_warn(LD_CONFIG
, "You have set ClientUseIPv4 1, but "
316 "ReachableAddresses, ReachableORAddresses, or "
317 "ReachableDirAddresses reject all IPv4 addresses. "
318 "Tor will not connect using IPv4.");
319 } else if (reachable_addr_use_ipv6(options
)
320 && (policy_is_reject_star(reachable_or_addr_policy
, AF_INET6
, 0)
321 || policy_is_reject_star(reachable_dir_addr_policy
, AF_INET6
, 0))) {
322 log_warn(LD_CONFIG
, "You have configured tor to use or prefer IPv6 "
323 "(or UseBridges 1), but "
324 "ReachableAddresses, ReachableORAddresses, or "
325 "ReachableDirAddresses reject all IPv6 addresses. "
326 "Tor will not connect using IPv6.");
330 /* Append a reject *:* to reachable_(or|dir)_addr_policy */
331 if (!ret
&& (options
->ReachableDirAddresses
||
332 options
->ReachableORAddresses
||
333 options
->ReachableAddresses
)) {
334 append_exit_policy_string(&reachable_or_addr_policy
, "reject *:*");
335 append_exit_policy_string(&reachable_dir_addr_policy
, "reject *:*");
341 /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
342 * address:port combination. */
344 firewall_is_fascist_impl(void)
346 const or_options_t
*options
= get_options();
347 /* Assume every non-bridge relay has an IPv4 address.
348 * Clients which use bridges may only know the IPv6 address of their
349 * bridge, but they will connect regardless of the ClientUseIPv6 setting. */
350 return options
->ClientUseIPv4
== 0;
353 /** Return true iff the firewall options, including ClientUseIPv4 0 and
354 * ClientUseIPv6 0, might block any OR address:port combination.
355 * Address preferences may still change which address is selected even if
356 * this function returns false.
359 firewall_is_fascist_or(void)
361 return (reachable_or_addr_policy
!= NULL
|| firewall_is_fascist_impl());
364 /** Return true iff the firewall options, including ClientUseIPv4 0 and
365 * ClientUseIPv6 0, might block any Dir address:port combination.
366 * Address preferences may still change which address is selected even if
367 * this function returns false.
370 firewall_is_fascist_dir(void)
372 return (reachable_dir_addr_policy
!= NULL
|| firewall_is_fascist_impl());
375 /** Return true iff <b>policy</b> (possibly NULL) will allow a
376 * connection to <b>addr</b>:<b>port</b>.
379 addr_policy_permits_tor_addr(const tor_addr_t
*addr
, uint16_t port
,
382 addr_policy_result_t p
;
383 p
= compare_tor_addr_to_addr_policy(addr
, port
, policy
);
385 case ADDR_POLICY_PROBABLY_ACCEPTED
:
386 case ADDR_POLICY_ACCEPTED
:
388 case ADDR_POLICY_PROBABLY_REJECTED
:
389 case ADDR_POLICY_REJECTED
:
392 log_warn(LD_BUG
, "Unexpected result: %d", (int)p
);
397 /** Return true iff we think our firewall will let us make a connection to
400 * If we are configured as a server, ignore any address family preference and
403 * - return false for all IPv4 addresses:
404 * - if ClientUseIPv4 is 0, or
405 * if pref_only and pref_ipv6 are both true;
406 * - return false for all IPv6 addresses:
407 * - if reachable_addr_use_ipv6() is 0, or
408 * - if pref_only is true and pref_ipv6 is false.
410 * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
412 reachable_addr_allows(const tor_addr_t
*addr
,
414 smartlist_t
*firewall_policy
,
415 int pref_only
, int pref_ipv6
)
417 const or_options_t
*options
= get_options();
418 const int client_mode
= !server_mode(options
);
420 if (!addr
|| tor_addr_is_null(addr
) || !port
) {
424 /* Clients stop using IPv4 if it's disabled. In most cases, clients also
425 * stop using IPv4 if it's not preferred.
426 * Servers must have IPv4 enabled and preferred. */
427 if (tor_addr_family(addr
) == AF_INET
&& client_mode
&&
428 (!options
->ClientUseIPv4
|| (pref_only
&& pref_ipv6
))) {
432 /* Clients and Servers won't use IPv6 unless it's enabled (and in most
433 * cases, IPv6 must also be preferred before it will be used). */
434 if (tor_addr_family(addr
) == AF_INET6
&&
435 (!reachable_addr_use_ipv6(options
) || (pref_only
&& !pref_ipv6
))) {
439 return addr_policy_permits_tor_addr(addr
, port
,
443 /** Is this client configured to use IPv6?
444 * Returns true if the client might use IPv6 for some of its connections
445 * (including dual-stack and IPv6-only clients), and false if it will never
446 * use IPv6 for any connections.
447 * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
448 * port: it supports bridge client per-node IPv6 preferences.
451 reachable_addr_use_ipv6(const or_options_t
*options
)
453 /* Clients use IPv6 if it's set, or they use bridges, or they don't use
454 * IPv4, or they prefer it.
455 * ClientPreferIPv6DirPort is deprecated, but check it anyway. */
456 return (options
->ClientUseIPv6
== 1 || options
->ClientUseIPv4
== 0 ||
457 options
->ClientPreferIPv6ORPort
== 1 ||
458 options
->ClientPreferIPv6DirPort
== 1 || options
->UseBridges
== 1);
461 /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
462 * ClientPreferIPv6DirPort?
463 * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
466 reachable_addr_prefer_ipv6_impl(const or_options_t
*options
)
469 Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
470 If we're a server or IPv6 is disabled, use IPv4.
471 If IPv4 is disabled, use IPv6.
474 if (server_mode(options
) || !reachable_addr_use_ipv6(options
)) {
478 if (!options
->ClientUseIPv4
) {
485 /** Do we prefer to connect to IPv6 ORPorts?
486 * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
487 * per-node IPv6 preferences.
490 reachable_addr_prefer_ipv6_orport(const or_options_t
*options
)
492 int pref_ipv6
= reachable_addr_prefer_ipv6_impl(options
);
494 if (pref_ipv6
>= 0) {
498 /* We can use both IPv4 and IPv6 - which do we prefer? */
499 if (options
->ClientPreferIPv6ORPort
== 1) {
506 /** Do we prefer to connect to IPv6 DirPorts?
508 * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
509 * preferences. There's no reason to use it instead of this function.)
512 reachable_addr_prefer_ipv6_dirport(const or_options_t
*options
)
514 int pref_ipv6
= reachable_addr_prefer_ipv6_impl(options
);
516 if (pref_ipv6
>= 0) {
520 /* We can use both IPv4 and IPv6 - which do we prefer? */
521 if (options
->ClientPreferIPv6DirPort
== 1) {
528 /** Return true iff we think our firewall will let us make a connection to
529 * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
531 * If pref_only is true, return true if addr is in the client's preferred
532 * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
533 * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
536 reachable_addr_allows_addr(const tor_addr_t
*addr
, uint16_t port
,
537 firewall_connection_t fw_connection
,
538 int pref_only
, int pref_ipv6
)
540 if (fw_connection
== FIREWALL_OR_CONNECTION
) {
541 return reachable_addr_allows(addr
, port
,
542 reachable_or_addr_policy
,
543 pref_only
, pref_ipv6
);
544 } else if (fw_connection
== FIREWALL_DIR_CONNECTION
) {
545 return reachable_addr_allows(addr
, port
,
546 reachable_dir_addr_policy
,
547 pref_only
, pref_ipv6
);
549 log_warn(LD_BUG
, "Bad firewall_connection_t value %d.",
555 /** Return true iff we think our firewall will let us make a connection to
556 * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
558 * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
561 reachable_addr_allows_ap(const tor_addr_port_t
*ap
,
562 firewall_connection_t fw_connection
,
563 int pref_only
, int pref_ipv6
)
566 return reachable_addr_allows_addr(&ap
->addr
, ap
->port
,
567 fw_connection
, pref_only
,
571 /** Return true iff we think our firewall will let us make a connection to
572 * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
573 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
574 * <b>fw_connection</b>.
575 * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
578 reachable_addr_allows_base(const tor_addr_t
*ipv4_addr
, uint16_t ipv4_orport
,
579 uint16_t ipv4_dirport
,
580 const tor_addr_t
*ipv6_addr
, uint16_t ipv6_orport
,
581 uint16_t ipv6_dirport
,
582 firewall_connection_t fw_connection
,
583 int pref_only
, int pref_ipv6
)
585 if (reachable_addr_allows_addr(ipv4_addr
,
586 (fw_connection
== FIREWALL_OR_CONNECTION
590 pref_only
, pref_ipv6
)) {
594 if (reachable_addr_allows_addr(ipv6_addr
,
595 (fw_connection
== FIREWALL_OR_CONNECTION
599 pref_only
, pref_ipv6
)) {
606 /** Like reachable_addr_allows_base(), but takes ri. */
608 reachable_addr_allows_ri_impl(const routerinfo_t
*ri
,
609 firewall_connection_t fw_connection
,
610 int pref_only
, int pref_ipv6
)
616 /* Assume IPv4 and IPv6 DirPorts are the same */
617 return reachable_addr_allows_base(&ri
->ipv4_addr
, ri
->ipv4_orport
,
618 ri
->ipv4_dirport
, &ri
->ipv6_addr
,
619 ri
->ipv6_orport
, ri
->ipv4_dirport
,
620 fw_connection
, pref_only
, pref_ipv6
);
623 /** Like reachable_addr_allows_rs, but takes pref_ipv6. */
625 reachable_addr_allows_rs_impl(const routerstatus_t
*rs
,
626 firewall_connection_t fw_connection
,
627 int pref_only
, int pref_ipv6
)
633 /* Assume IPv4 and IPv6 DirPorts are the same */
634 return reachable_addr_allows_base(&rs
->ipv4_addr
, rs
->ipv4_orport
,
635 rs
->ipv4_dirport
, &rs
->ipv6_addr
,
636 rs
->ipv6_orport
, rs
->ipv4_dirport
,
637 fw_connection
, pref_only
, pref_ipv6
);
640 /** Like reachable_addr_allows_base(), but takes rs.
641 * When rs is a fake_status from a dir_server_t, it can have a reachable
642 * address, even when the corresponding node does not.
643 * nodes can be missing addresses when there's no consensus (IPv4 and IPv6),
644 * or when there is a microdescriptor consensus, but no microdescriptors
645 * (microdescriptors have IPv6, the microdesc consensus does not). */
647 reachable_addr_allows_rs(const routerstatus_t
*rs
,
648 firewall_connection_t fw_connection
, int pref_only
)
654 /* We don't have access to the node-specific IPv6 preference, so use the
655 * generic IPv6 preference instead. */
656 const or_options_t
*options
= get_options();
657 int pref_ipv6
= (fw_connection
== FIREWALL_OR_CONNECTION
658 ? reachable_addr_prefer_ipv6_orport(options
)
659 : reachable_addr_prefer_ipv6_dirport(options
));
661 return reachable_addr_allows_rs_impl(rs
, fw_connection
, pref_only
,
665 /** Return true iff we think our firewall will let us make a connection to
666 * ipv6_addr:ipv6_orport based on ReachableORAddresses.
667 * If <b>fw_connection</b> is FIREWALL_DIR_CONNECTION, returns 0.
668 * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
671 reachable_addr_allows_md_impl(const microdesc_t
*md
,
672 firewall_connection_t fw_connection
,
673 int pref_only
, int pref_ipv6
)
679 /* Can't check dirport, it doesn't have one */
680 if (fw_connection
== FIREWALL_DIR_CONNECTION
) {
684 /* Also can't check IPv4, doesn't have that either */
685 return reachable_addr_allows_addr(&md
->ipv6_addr
, md
->ipv6_orport
,
686 fw_connection
, pref_only
,
690 /** Like reachable_addr_allows_base(), but takes node, and looks up pref_ipv6
691 * from node_ipv6_or/dir_preferred(). */
693 reachable_addr_allows_node(const node_t
*node
,
694 firewall_connection_t fw_connection
,
701 node_assert_ok(node
);
703 const int pref_ipv6
= (fw_connection
== FIREWALL_OR_CONNECTION
704 ? node_ipv6_or_preferred(node
)
705 : node_ipv6_dir_preferred(node
));
707 /* Sometimes, the rs is missing the IPv6 address info, and we need to go
708 * all the way to the md */
709 if (node
->ri
&& reachable_addr_allows_ri_impl(node
->ri
, fw_connection
,
710 pref_only
, pref_ipv6
)) {
712 } else if (node
->rs
&& reachable_addr_allows_rs_impl(node
->rs
,
717 } else if (node
->md
&& reachable_addr_allows_md_impl(node
->md
,
723 /* If we know nothing, assume it's unreachable, we'll never get an address
729 /** Like reachable_addr_allows_rs(), but takes ds. */
731 reachable_addr_allows_dir_server(const dir_server_t
*ds
,
732 firewall_connection_t fw_connection
,
739 /* A dir_server_t always has a fake_status. As long as it has the same
740 * addresses/ports in both fake_status and dir_server_t, this works fine.
742 * reachable_addr_allows_rs only checks the addresses in fake_status. */
743 return reachable_addr_allows_rs(&ds
->fake_status
, fw_connection
,
747 /** If a and b are both valid and allowed by fw_connection,
748 * choose one based on want_a and return it.
749 * Otherwise, return whichever is allowed.
750 * Otherwise, return NULL.
751 * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
753 static const tor_addr_port_t
*
754 reachable_addr_choose_impl(const tor_addr_port_t
*a
,
755 const tor_addr_port_t
*b
,
757 firewall_connection_t fw_connection
,
758 int pref_only
, int pref_ipv6
)
760 const tor_addr_port_t
*use_a
= NULL
;
761 const tor_addr_port_t
*use_b
= NULL
;
763 if (reachable_addr_allows_ap(a
, fw_connection
, pref_only
,
768 if (reachable_addr_allows_ap(b
, fw_connection
, pref_only
,
773 /* If both are allowed */
774 if (use_a
&& use_b
) {
775 /* Choose a if we want it */
776 return (want_a
? use_a
: use_b
);
778 /* Choose a if we have it */
779 return (use_a
? use_a
: use_b
);
783 /** If a and b are both valid and preferred by fw_connection,
784 * choose one based on want_a and return it.
785 * Otherwise, return whichever is preferred.
786 * If neither are preferred, and pref_only is false:
787 * - If a and b are both allowed by fw_connection,
788 * choose one based on want_a and return it.
789 * - Otherwise, return whichever is preferred.
790 * Otherwise, return NULL. */
791 STATIC
const tor_addr_port_t
*
792 reachable_addr_choose(const tor_addr_port_t
*a
,
793 const tor_addr_port_t
*b
,
795 firewall_connection_t fw_connection
,
796 int pref_only
, int pref_ipv6
)
798 const tor_addr_port_t
*pref
= reachable_addr_choose_impl(
802 if (pref_only
|| pref
) {
803 /* If there is a preferred address, use it. If we can only use preferred
804 * addresses, and neither address is preferred, pref will be NULL, and we
805 * want to return NULL, so return it. */
808 /* If there's no preferred address, and we can return addresses that are
809 * not preferred, use an address that's allowed */
810 return reachable_addr_choose_impl(a
, b
, want_a
, fw_connection
,
815 /** Copy an address and port into <b>ap</b> that we think our firewall will
816 * let us connect to. Uses ipv4_addr/ipv6_addr and
817 * ipv4_orport/ipv6_orport/ReachableORAddresses or
818 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
819 * <b>fw_connection</b>.
820 * If pref_only, only choose preferred addresses. In either case, choose
821 * a preferred address before an address that's not preferred.
822 * If both addresses could be chosen (they are both preferred or both allowed)
823 * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4. */
825 reachable_addr_choose_base(const tor_addr_t
*ipv4_addr
,
826 uint16_t ipv4_orport
,
827 uint16_t ipv4_dirport
,
828 const tor_addr_t
*ipv6_addr
,
829 uint16_t ipv6_orport
,
830 uint16_t ipv6_dirport
,
831 firewall_connection_t fw_connection
,
836 const tor_addr_port_t
*result
= NULL
;
837 const int want_ipv4
= !pref_ipv6
;
839 tor_assert(ipv6_addr
);
842 tor_addr_make_null(&ap
->addr
, AF_UNSPEC
);
845 tor_addr_port_t ipv4_ap
;
846 tor_addr_copy(&ipv4_ap
.addr
, ipv4_addr
);
847 ipv4_ap
.port
= (fw_connection
== FIREWALL_OR_CONNECTION
851 tor_addr_port_t ipv6_ap
;
852 tor_addr_copy(&ipv6_ap
.addr
, ipv6_addr
);
853 ipv6_ap
.port
= (fw_connection
== FIREWALL_OR_CONNECTION
857 result
= reachable_addr_choose(&ipv4_ap
, &ipv6_ap
,
859 fw_connection
, pref_only
,
863 tor_addr_copy(&ap
->addr
, &result
->addr
);
864 ap
->port
= result
->port
;
868 /** Like reachable_addr_choose_base(), but takes <b>rs</b>.
869 * Consults the corresponding node, then falls back to rs if node is NULL.
870 * This should only happen when there's no valid consensus, and rs doesn't
871 * correspond to a bridge client's bridge.
874 reachable_addr_choose_from_rs(const routerstatus_t
*rs
,
875 firewall_connection_t fw_connection
,
876 int pref_only
, tor_addr_port_t
* ap
)
880 tor_addr_make_null(&ap
->addr
, AF_UNSPEC
);
887 const or_options_t
*options
= get_options();
888 const node_t
*node
= node_get_by_id(rs
->identity_digest
);
891 reachable_addr_choose_from_node(node
, fw_connection
, pref_only
, ap
);
893 /* There's no node-specific IPv6 preference, so use the generic IPv6
894 * preference instead. */
895 int pref_ipv6
= (fw_connection
== FIREWALL_OR_CONNECTION
896 ? reachable_addr_prefer_ipv6_orport(options
)
897 : reachable_addr_prefer_ipv6_dirport(options
));
899 reachable_addr_choose_base(&rs
->ipv4_addr
, rs
->ipv4_orport
,
900 rs
->ipv4_dirport
, &rs
->ipv6_addr
,
901 rs
->ipv6_orport
, rs
->ipv4_dirport
,
902 fw_connection
, pref_only
, pref_ipv6
,
907 /** Like reachable_addr_choose_base(), but takes in a smartlist
908 * <b>lspecs</b> consisting of one or more link specifiers. We assume
909 * fw_connection is FIREWALL_OR_CONNECTION as link specifiers cannot
913 reachable_addr_choose_from_ls(const smartlist_t
*lspecs
,
914 int pref_only
, tor_addr_port_t
* ap
)
916 int have_v4
= 0, have_v6
= 0;
917 uint16_t port_v4
= 0, port_v6
= 0;
918 tor_addr_t addr_v4
, addr_v6
;
922 if (lspecs
== NULL
) {
923 log_warn(LD_BUG
, "Unknown or missing link specifiers");
926 if (smartlist_len(lspecs
) == 0) {
927 log_warn(LD_PROTOCOL
, "Link specifiers are empty");
931 tor_addr_make_null(&ap
->addr
, AF_UNSPEC
);
934 tor_addr_make_null(&addr_v4
, AF_INET
);
935 tor_addr_make_null(&addr_v6
, AF_INET6
);
937 SMARTLIST_FOREACH_BEGIN(lspecs
, const link_specifier_t
*, ls
) {
938 switch (link_specifier_get_ls_type(ls
)) {
940 /* Skip if we already seen a v4. */
941 if (have_v4
) continue;
942 tor_addr_from_ipv4h(&addr_v4
,
943 link_specifier_get_un_ipv4_addr(ls
));
944 port_v4
= link_specifier_get_un_ipv4_port(ls
);
948 /* Skip if we already seen a v6, or deliberately skip it if we're not a
949 * direct connection. */
950 if (have_v6
) continue;
951 tor_addr_from_ipv6_bytes(&addr_v6
,
952 link_specifier_getconstarray_un_ipv6_addr(ls
));
953 port_v6
= link_specifier_get_un_ipv6_port(ls
);
957 /* Ignore unknown. */
960 } SMARTLIST_FOREACH_END(ls
);
962 /* If we don't have IPv4 or IPv6 in link specifiers, log a bug and return. */
963 if (!have_v4
&& !have_v6
) {
965 log_warn(LD_PROTOCOL
, "None of our link specifiers have IPv4 or IPv6");
967 log_warn(LD_PROTOCOL
, "None of our link specifiers have IPv4");
972 /* Here, don't check for DirPorts as link specifiers are only used for
974 const or_options_t
*options
= get_options();
975 int pref_ipv6
= reachable_addr_prefer_ipv6_orport(options
);
976 /* Assume that the DirPorts are zero as link specifiers only use ORPorts. */
977 reachable_addr_choose_base(&addr_v4
, port_v4
, 0,
978 &addr_v6
, port_v6
, 0,
979 FIREWALL_OR_CONNECTION
,
980 pref_only
, pref_ipv6
,
984 /** Like reachable_addr_choose_base(), but takes <b>node</b>, and
985 * looks up the node's IPv6 preference rather than taking an argument
988 reachable_addr_choose_from_node(const node_t
*node
,
989 firewall_connection_t fw_connection
,
990 int pref_only
, tor_addr_port_t
*ap
)
994 tor_addr_make_null(&ap
->addr
, AF_UNSPEC
);
1001 node_assert_ok(node
);
1003 const int pref_ipv6_node
= (fw_connection
== FIREWALL_OR_CONNECTION
1004 ? node_ipv6_or_preferred(node
)
1005 : node_ipv6_dir_preferred(node
));
1007 tor_addr_port_t ipv4_or_ap
;
1008 node_get_prim_orport(node
, &ipv4_or_ap
);
1009 tor_addr_port_t ipv4_dir_ap
;
1010 node_get_prim_dirport(node
, &ipv4_dir_ap
);
1012 tor_addr_port_t ipv6_or_ap
;
1013 node_get_pref_ipv6_orport(node
, &ipv6_or_ap
);
1014 tor_addr_port_t ipv6_dir_ap
;
1015 node_get_pref_ipv6_dirport(node
, &ipv6_dir_ap
);
1017 /* Assume the IPv6 OR and Dir addresses are the same. */
1018 reachable_addr_choose_base(&ipv4_or_ap
.addr
, ipv4_or_ap
.port
,
1019 ipv4_dir_ap
.port
, &ipv6_or_ap
.addr
,
1020 ipv6_or_ap
.port
, ipv6_dir_ap
.port
,
1021 fw_connection
, pref_only
,
1022 pref_ipv6_node
, ap
);
1025 /** Like reachable_addr_choose_from_rs(), but takes <b>ds</b>. */
1027 reachable_addr_choose_from_dir_server(const dir_server_t
*ds
,
1028 firewall_connection_t fw_connection
,
1030 tor_addr_port_t
*ap
)
1034 tor_addr_make_null(&ap
->addr
, AF_UNSPEC
);
1041 /* A dir_server_t always has a fake_status. As long as it has the same
1042 * addresses/ports in both fake_status and dir_server_t, this works fine.
1044 * This function relies on reachable_addr_choose_from_rs looking up the
1045 * node if it can, because that will get the latest info for the relay. */
1046 reachable_addr_choose_from_rs(&ds
->fake_status
, fw_connection
,
1050 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
1051 * based on <b>dir_policy</b>. Else return 0.
1054 dir_policy_permits_address(const tor_addr_t
*addr
)
1056 return addr_policy_permits_tor_addr(addr
, 1, dir_policy
);
1059 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1060 * based on <b>socks_policy</b>. Else return 0.
1063 socks_policy_permits_address(const tor_addr_t
*addr
)
1065 return addr_policy_permits_tor_addr(addr
, 1, socks_policy
);
1068 /** Return 1 if <b>addr</b> is permitted to connect to our metrics port,
1069 * based on <b>metrics_policy</b>. Else return 0.
1072 metrics_policy_permits_address(const tor_addr_t
*addr
)
1074 return addr_policy_permits_tor_addr(addr
, 1, metrics_policy
);
1077 /** Return true iff the address <b>addr</b> is in a country listed in the
1078 * case-insensitive list of country codes <b>cc_list</b>. */
1080 addr_is_in_cc_list(const tor_addr_t
*addr
, const smartlist_t
*cc_list
)
1087 country
= geoip_get_country_by_addr(addr
);
1088 name
= geoip_get_country_name(country
);
1089 return smartlist_contains_string_case(cc_list
, name
);
1092 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
1093 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
1096 authdir_policy_permits_address(const tor_addr_t
*addr
, uint16_t port
)
1098 if (!addr_policy_permits_tor_addr(addr
, port
, authdir_reject_policy
))
1100 return !addr_is_in_cc_list(addr
, get_options()->AuthDirRejectCCs
);
1103 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
1104 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
1107 authdir_policy_valid_address(const tor_addr_t
*addr
, uint16_t port
)
1109 if (!addr_policy_permits_tor_addr(addr
, port
, authdir_invalid_policy
))
1111 return !addr_is_in_cc_list(addr
, get_options()->AuthDirInvalidCCs
);
1114 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
1115 * based on <b>authdir_badexit_policy</b>. Else return 0.
1118 authdir_policy_badexit_address(const tor_addr_t
*addr
, uint16_t port
)
1120 if (!addr_policy_permits_tor_addr(addr
, port
, authdir_badexit_policy
))
1122 return addr_is_in_cc_list(addr
, get_options()->AuthDirBadExitCCs
);
1125 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as MiddleOnly,
1126 * based on <b>authdir_middleonly_policy</b>. Else return 0.
1129 authdir_policy_middleonly_address(const tor_addr_t
*addr
, uint16_t port
)
1131 if (!addr_policy_permits_tor_addr(addr
, port
, authdir_middleonly_policy
))
1133 return addr_is_in_cc_list(addr
, get_options()->AuthDirMiddleOnlyCCs
);
1136 #define REJECT(arg) \
1137 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
1139 /** Check <b>or_options</b> to determine whether or not we are using the
1140 * default options for exit policy. Return true if so, false otherwise. */
1142 policy_using_default_exit_options(const or_options_t
*or_options
)
1144 return (or_options
->ExitPolicy
== NULL
&& or_options
->ExitRelay
== -1 &&
1145 or_options
->ReducedExitPolicy
== 0 && or_options
->IPv6Exit
== 0);
1148 /** Config helper: If there's any problem with the policy configuration
1149 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
1150 * allocated description of the error. Else return 0. */
1152 validate_addr_policies(const or_options_t
*options
, char **msg
)
1154 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
1155 * that the two can't go out of sync. */
1157 smartlist_t
*addr_policy
=NULL
;
1160 if (policies_parse_exit_policy_from_options(options
,0,NULL
,&addr_policy
)) {
1161 REJECT("Error in ExitPolicy entry.");
1164 static int warned_about_nonexit
= 0;
1166 if (public_server_mode(options
) && !warned_about_nonexit
&&
1167 policy_using_default_exit_options(options
)) {
1168 warned_about_nonexit
= 1;
1169 log_notice(LD_CONFIG
, "By default, Tor does not run as an exit relay. "
1170 "If you want to be an exit relay, "
1171 "set ExitRelay to 1. To suppress this message in the future, "
1172 "set ExitRelay to 0.");
1175 /* The rest of these calls *append* to addr_policy. So don't actually
1176 * use the results for anything other than checking if they parse! */
1177 if (parse_addr_policy(options
->DirPolicy
, &addr_policy
, -1))
1178 REJECT("Error in DirPolicy entry.");
1179 if (parse_addr_policy(options
->SocksPolicy
, &addr_policy
, -1))
1180 REJECT("Error in SocksPolicy entry.");
1181 if (parse_addr_policy(options
->AuthDirReject
, &addr_policy
,
1182 ADDR_POLICY_REJECT
))
1183 REJECT("Error in AuthDirReject entry.");
1184 if (parse_addr_policy(options
->AuthDirInvalid
, &addr_policy
,
1185 ADDR_POLICY_REJECT
))
1186 REJECT("Error in AuthDirInvalid entry.");
1187 if (parse_addr_policy(options
->AuthDirBadExit
, &addr_policy
,
1188 ADDR_POLICY_REJECT
))
1189 REJECT("Error in AuthDirBadExit entry.");
1190 if (parse_addr_policy(options
->AuthDirMiddleOnly
, &addr_policy
,
1191 ADDR_POLICY_REJECT
))
1192 REJECT("Error in AuthDirMiddleOnly entry.");
1194 if (parse_addr_policy(options
->ReachableAddresses
, &addr_policy
,
1195 ADDR_POLICY_ACCEPT
))
1196 REJECT("Error in ReachableAddresses entry.");
1197 if (parse_addr_policy(options
->ReachableORAddresses
, &addr_policy
,
1198 ADDR_POLICY_ACCEPT
))
1199 REJECT("Error in ReachableORAddresses entry.");
1200 if (parse_addr_policy(options
->ReachableDirAddresses
, &addr_policy
,
1201 ADDR_POLICY_ACCEPT
))
1202 REJECT("Error in ReachableDirAddresses entry.");
1205 addr_policy_list_free(addr_policy
);
1206 return *msg
? -1 : 0;
1210 /** Parse <b>string</b> in the same way that the exit policy
1211 * is parsed, and put the processed version in *<b>policy</b>.
1212 * Ignore port specifiers.
1215 load_policy_from_option(config_line_t
*config
, const char *option_name
,
1216 smartlist_t
**policy
,
1220 int killed_any_ports
= 0;
1221 addr_policy_list_free(*policy
);
1223 r
= parse_addr_policy(config
, policy
, assume_action
);
1228 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, n
) {
1229 /* ports aren't used in these. */
1230 if (n
->prt_min
> 1 || n
->prt_max
!= 65535) {
1231 addr_policy_t newp
, *c
;
1232 memcpy(&newp
, n
, sizeof(newp
));
1234 newp
.prt_max
= 65535;
1235 newp
.is_canonical
= 0;
1236 c
= addr_policy_get_canonical_entry(&newp
);
1237 SMARTLIST_REPLACE_CURRENT(*policy
, n
, c
);
1238 addr_policy_free(n
);
1239 killed_any_ports
= 1;
1241 } SMARTLIST_FOREACH_END(n
);
1243 if (killed_any_ports
) {
1244 log_warn(LD_CONFIG
, "Ignoring ports in %s option.", option_name
);
1249 /** Helper: Parse the MetricsPortPolicy option into the metrics_policy and set
1250 * the reject all by default.
1252 * Return 0 on success else -1. */
1254 parse_metrics_port_policy(const or_options_t
*options
)
1256 if (load_policy_from_option(options
->MetricsPortPolicy
, "MetricsPortPolicy",
1257 &metrics_policy
, -1) < 0) {
1260 /* It is a reject all by default. */
1261 append_exit_policy_string(&metrics_policy
, "reject *:*");
1265 /** Set all policies based on <b>options</b>, which should have been validated
1266 * first by validate_addr_policies. */
1268 policies_parse_from_options(const or_options_t
*options
)
1271 if (load_policy_from_option(options
->SocksPolicy
, "SocksPolicy",
1272 &socks_policy
, -1) < 0)
1274 if (load_policy_from_option(options
->DirPolicy
, "DirPolicy",
1275 &dir_policy
, -1) < 0)
1277 if (load_policy_from_option(options
->AuthDirReject
, "AuthDirReject",
1278 &authdir_reject_policy
, ADDR_POLICY_REJECT
) < 0)
1280 if (load_policy_from_option(options
->AuthDirInvalid
, "AuthDirInvalid",
1281 &authdir_invalid_policy
, ADDR_POLICY_REJECT
) < 0)
1283 if (load_policy_from_option(options
->AuthDirBadExit
, "AuthDirBadExit",
1284 &authdir_badexit_policy
, ADDR_POLICY_REJECT
) < 0)
1286 if (load_policy_from_option(options
->AuthDirMiddleOnly
, "AuthDirMiddleOnly",
1287 &authdir_middleonly_policy
, ADDR_POLICY_REJECT
) < 0)
1289 if (parse_metrics_port_policy(options
) < 0) {
1292 if (parse_reachable_addresses() < 0)
1297 /** Compare two provided address policy items, and renturn -1, 0, or 1
1298 * if the first is less than, equal to, or greater than the second. */
1300 single_addr_policy_eq(const addr_policy_t
*a
, const addr_policy_t
*b
)
1303 #define CMP_FIELD(field) do { \
1304 if (a->field != b->field) { \
1308 CMP_FIELD(policy_type
);
1309 CMP_FIELD(is_private
);
1310 /* refcnt and is_canonical are irrelevant to equality,
1311 * they are hash table implementation details */
1312 if ((r
=tor_addr_compare(&a
->addr
, &b
->addr
, CMP_EXACT
)))
1314 CMP_FIELD(maskbits
);
1321 /** As single_addr_policy_eq, but compare every element of two policies.
1324 addr_policies_eq(const smartlist_t
*a
, const smartlist_t
*b
)
1327 int len_a
= a
? smartlist_len(a
) : 0;
1328 int len_b
= b
? smartlist_len(b
) : 0;
1333 for (i
= 0; i
< len_a
; ++i
) {
1334 if (! single_addr_policy_eq(smartlist_get(a
, i
), smartlist_get(b
, i
)))
1341 /** Node in hashtable used to store address policy entries. */
1342 typedef struct policy_map_ent_t
{
1343 HT_ENTRY(policy_map_ent_t
) node
;
1344 addr_policy_t
*policy
;
1347 /* DOCDOC policy_root */
1348 static HT_HEAD(policy_map
, policy_map_ent_t
) policy_root
= HT_INITIALIZER();
1350 /** Return true iff a and b are equal. */
1352 policy_eq(policy_map_ent_t
*a
, policy_map_ent_t
*b
)
1354 return single_addr_policy_eq(a
->policy
, b
->policy
);
1357 /** Return a hashcode for <b>ent</b> */
1359 policy_hash(const policy_map_ent_t
*ent
)
1361 const addr_policy_t
*a
= ent
->policy
;
1363 memset(&aa
, 0, sizeof(aa
));
1365 aa
.prt_min
= a
->prt_min
;
1366 aa
.prt_max
= a
->prt_max
;
1367 aa
.maskbits
= a
->maskbits
;
1368 aa
.policy_type
= a
->policy_type
;
1369 aa
.is_private
= a
->is_private
;
1371 if (a
->is_private
) {
1374 tor_addr_copy_tight(&aa
.addr
, &a
->addr
);
1377 return (unsigned) siphash24g(&aa
, sizeof(aa
));
1380 HT_PROTOTYPE(policy_map
, policy_map_ent_t
, node
, policy_hash
,
1382 HT_GENERATE2(policy_map
, policy_map_ent_t
, node
, policy_hash
,
1383 policy_eq
, 0.6, tor_reallocarray_
, tor_free_
);
1385 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
1386 * "canonical" copy of that addr_policy_t; the canonical copy is a single
1387 * reference-counted object. */
1389 addr_policy_get_canonical_entry(addr_policy_t
*e
)
1391 policy_map_ent_t search
, *found
;
1392 if (e
->is_canonical
)
1396 found
= HT_FIND(policy_map
, &policy_root
, &search
);
1398 found
= tor_malloc_zero(sizeof(policy_map_ent_t
));
1399 found
->policy
= tor_memdup(e
, sizeof(addr_policy_t
));
1400 found
->policy
->is_canonical
= 1;
1401 found
->policy
->refcnt
= 0;
1402 HT_INSERT(policy_map
, &policy_root
, found
);
1405 tor_assert(single_addr_policy_eq(found
->policy
, e
));
1406 ++found
->policy
->refcnt
;
1407 return found
->policy
;
1410 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1411 * addr and port are both known. */
1412 static addr_policy_result_t
1413 compare_known_tor_addr_to_addr_policy(const tor_addr_t
*addr
, uint16_t port
,
1414 const smartlist_t
*policy
)
1416 /* We know the address and port, and we know the policy, so we can just
1417 * compute an exact match. */
1418 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
1419 if (tmpe
->addr
.family
== AF_UNSPEC
) {
1420 log_warn(LD_BUG
, "Policy contains an AF_UNSPEC address, which only "
1421 "matches other AF_UNSPEC addresses.");
1423 /* Address is known */
1424 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
1426 if (port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) {
1427 /* Exact match for the policy */
1428 return tmpe
->policy_type
== ADDR_POLICY_ACCEPT
?
1429 ADDR_POLICY_ACCEPTED
: ADDR_POLICY_REJECTED
;
1432 } SMARTLIST_FOREACH_END(tmpe
);
1434 /* accept all by default. */
1435 return ADDR_POLICY_ACCEPTED
;
1438 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1439 * addr is known but port is not. */
1440 static addr_policy_result_t
1441 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t
*addr
,
1442 const smartlist_t
*policy
)
1444 /* We look to see if there's a definite match. If so, we return that
1445 match's value, unless there's an intervening possible match that says
1446 something different. */
1447 int maybe_accept
= 0, maybe_reject
= 0;
1449 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
1450 if (tmpe
->addr
.family
== AF_UNSPEC
) {
1451 log_warn(LD_BUG
, "Policy contains an AF_UNSPEC address, which only "
1452 "matches other AF_UNSPEC addresses.");
1454 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
1456 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
>= 65535) {
1457 /* Definitely matches, since it covers all ports. */
1458 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
1459 /* If we already hit a clause that might trigger a 'reject', than we
1460 * can't be sure of this certain 'accept'.*/
1461 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
1462 ADDR_POLICY_ACCEPTED
;
1464 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
1465 ADDR_POLICY_REJECTED
;
1469 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
1475 } SMARTLIST_FOREACH_END(tmpe
);
1477 /* accept all by default. */
1478 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
1481 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1482 * port is known but address is not. */
1483 static addr_policy_result_t
1484 compare_unknown_tor_addr_to_addr_policy(uint16_t port
,
1485 const smartlist_t
*policy
)
1487 /* We look to see if there's a definite match. If so, we return that
1488 match's value, unless there's an intervening possible match that says
1489 something different. */
1490 int maybe_accept
= 0, maybe_reject
= 0;
1492 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
1493 if (tmpe
->addr
.family
== AF_UNSPEC
) {
1494 log_warn(LD_BUG
, "Policy contains an AF_UNSPEC address, which only "
1495 "matches other AF_UNSPEC addresses.");
1497 if (tmpe
->prt_min
<= port
&& port
<= tmpe
->prt_max
) {
1498 if (tmpe
->maskbits
== 0) {
1499 /* Definitely matches, since it covers all addresses. */
1500 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
1501 /* If we already hit a clause that might trigger a 'reject', than we
1502 * can't be sure of this certain 'accept'.*/
1503 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
1504 ADDR_POLICY_ACCEPTED
;
1506 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
1507 ADDR_POLICY_REJECTED
;
1511 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
1517 } SMARTLIST_FOREACH_END(tmpe
);
1519 /* accept all by default. */
1520 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
1523 /** Decide whether a given addr:port is definitely accepted,
1524 * definitely rejected, probably accepted, or probably rejected by a
1525 * given policy. If <b>addr</b> is 0, we don't know the IP of the
1526 * target address. If <b>port</b> is 0, we don't know the port of the
1527 * target address. (At least one of <b>addr</b> and <b>port</b> must be
1528 * provided. If you want to know whether a policy would definitely reject
1529 * an unknown address:port, use policy_is_reject_star().)
1531 * We could do better by assuming that some ranges never match typical
1532 * addresses (127.0.0.1, and so on). But we'll try this for now.
1534 MOCK_IMPL(addr_policy_result_t
,
1535 compare_tor_addr_to_addr_policy
,(const tor_addr_t
*addr
, uint16_t port
,
1536 const smartlist_t
*policy
))
1539 /* no policy? accept all. */
1540 return ADDR_POLICY_ACCEPTED
;
1541 } else if (addr
== NULL
|| tor_addr_is_null(addr
)) {
1543 log_info(LD_BUG
, "Rejecting null address with 0 port (family %d)",
1544 addr
? tor_addr_family(addr
) : -1);
1545 return ADDR_POLICY_REJECTED
;
1547 return compare_unknown_tor_addr_to_addr_policy(port
, policy
);
1548 } else if (port
== 0) {
1549 return compare_known_tor_addr_to_addr_policy_noport(addr
, policy
);
1551 return compare_known_tor_addr_to_addr_policy(addr
, port
, policy
);
1555 /** Return true iff the address policy <b>a</b> covers every case that
1556 * would be covered by <b>b</b>, so that a,b is redundant. */
1558 addr_policy_covers(addr_policy_t
*a
, addr_policy_t
*b
)
1560 if (tor_addr_family(&a
->addr
) != tor_addr_family(&b
->addr
)) {
1561 /* You can't cover a different family. */
1564 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
1565 * to "accept *:80". */
1566 if (a
->maskbits
> b
->maskbits
) {
1567 /* a has more fixed bits than b; it can't possibly cover b. */
1570 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, a
->maskbits
, CMP_EXACT
)) {
1571 /* There's a fixed bit in a that's set differently in b. */
1574 return (a
->prt_min
<= b
->prt_min
&& a
->prt_max
>= b
->prt_max
);
1577 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
1578 * that is, there exists an address/port that is covered by <b>a</b> that
1579 * is also covered by <b>b</b>.
1582 addr_policy_intersects(addr_policy_t
*a
, addr_policy_t
*b
)
1585 /* All the bits we care about are those that are set in both
1586 * netmasks. If they are equal in a and b's networkaddresses
1587 * then the networks intersect. If there is a difference,
1588 * then they do not. */
1589 if (a
->maskbits
< b
->maskbits
)
1590 minbits
= a
->maskbits
;
1592 minbits
= b
->maskbits
;
1593 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, minbits
, CMP_EXACT
))
1595 if (a
->prt_max
< b
->prt_min
|| b
->prt_max
< a
->prt_min
)
1600 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
1603 append_exit_policy_string(smartlist_t
**policy
, const char *more
)
1608 tmp
.value
= (char*) more
;
1610 if (parse_addr_policy(&tmp
, policy
, -1)<0) {
1611 log_warn(LD_BUG
, "Unable to parse internally generated policy %s",more
);
1615 /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
1617 addr_policy_append_reject_addr(smartlist_t
**dest
, const tor_addr_t
*addr
)
1622 addr_policy_t p
, *add
;
1623 memset(&p
, 0, sizeof(p
));
1624 p
.policy_type
= ADDR_POLICY_REJECT
;
1625 p
.maskbits
= tor_addr_family(addr
) == AF_INET6
? 128 : 32;
1626 tor_addr_copy(&p
.addr
, addr
);
1630 add
= addr_policy_get_canonical_entry(&p
);
1632 *dest
= smartlist_new();
1633 smartlist_add(*dest
, add
);
1634 log_debug(LD_CONFIG
, "Adding a reject ExitPolicy 'reject %s:*'",
1638 /* Is addr public for the purposes of rejection? */
1640 tor_addr_is_public_for_reject(const tor_addr_t
*addr
)
1642 return (!tor_addr_is_null(addr
) && !tor_addr_is_internal(addr
, 0)
1643 && !tor_addr_is_multicast(addr
));
1646 /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
1647 * Filter the address, only adding an IPv4 reject rule if ipv4_rules
1648 * is true, and similarly for ipv6_rules. Check each address returns true for
1649 * tor_addr_is_public_for_reject before adding it.
1652 addr_policy_append_reject_addr_filter(smartlist_t
**dest
,
1653 const tor_addr_t
*addr
,
1660 /* Only reject IP addresses which are public */
1661 if (tor_addr_is_public_for_reject(addr
)) {
1663 /* Reject IPv4 addresses and IPv6 addresses based on the filters */
1664 int is_ipv4
= tor_addr_is_v4(addr
);
1665 if ((is_ipv4
&& ipv4_rules
) || (!is_ipv4
&& ipv6_rules
)) {
1666 addr_policy_append_reject_addr(dest
, addr
);
1671 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1672 * list as needed. */
1674 addr_policy_append_reject_addr_list(smartlist_t
**dest
,
1675 const smartlist_t
*addrs
)
1680 SMARTLIST_FOREACH_BEGIN(addrs
, tor_addr_t
*, addr
) {
1681 addr_policy_append_reject_addr(dest
, addr
);
1682 } SMARTLIST_FOREACH_END(addr
);
1685 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1686 * list as needed. Filter using */
1688 addr_policy_append_reject_addr_list_filter(smartlist_t
**dest
,
1689 const smartlist_t
*addrs
,
1696 SMARTLIST_FOREACH_BEGIN(addrs
, tor_addr_t
*, addr
) {
1697 addr_policy_append_reject_addr_filter(dest
, addr
, ipv4_rules
, ipv6_rules
);
1698 } SMARTLIST_FOREACH_END(addr
);
1701 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
1703 exit_policy_remove_redundancies(smartlist_t
*dest
)
1705 addr_policy_t
*ap
, *tmp
;
1708 /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
1711 int kill_v4
=0, kill_v6
=0;
1712 for (i
= 0; i
< smartlist_len(dest
); ++i
) {
1714 ap
= smartlist_get(dest
, i
);
1715 family
= tor_addr_family(&ap
->addr
);
1716 if ((family
== AF_INET
&& kill_v4
) ||
1717 (family
== AF_INET6
&& kill_v6
)) {
1718 smartlist_del_keeporder(dest
, i
--);
1719 addr_policy_free(ap
);
1723 if (ap
->maskbits
== 0 && ap
->prt_min
<= 1 && ap
->prt_max
>= 65535) {
1724 /* This is a catch-all line -- later lines are unreachable. */
1725 if (family
== AF_INET
) {
1727 } else if (family
== AF_INET6
) {
1734 /* Step two: for every entry, see if there's a redundant entry
1735 * later on, and remove it. */
1736 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
1737 ap
= smartlist_get(dest
, i
);
1738 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
1739 tmp
= smartlist_get(dest
, j
);
1741 if (addr_policy_covers(ap
, tmp
)) {
1742 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
1743 policy_write_item(p1
, sizeof(p1
), tmp
, 0);
1744 policy_write_item(p2
, sizeof(p2
), ap
, 0);
1745 log_debug(LD_CONFIG
, "Removing exit policy %s (%d). It is made "
1746 "redundant by %s (%d).", p1
, j
, p2
, i
);
1747 smartlist_del_keeporder(dest
, j
--);
1748 addr_policy_free(tmp
);
1753 /* Step three: for every entry A, see if there's an entry B making this one
1754 * redundant later on. This is the case if A and B are of the same type
1755 * (accept/reject), A is a subset of B, and there is no other entry of
1756 * different type in between those two that intersects with A.
1758 * Anybody want to double-check the logic here? XXX
1760 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
1761 ap
= smartlist_get(dest
, i
);
1762 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
1763 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
1765 tmp
= smartlist_get(dest
, j
);
1766 if (ap
->policy_type
!= tmp
->policy_type
) {
1767 if (addr_policy_intersects(ap
, tmp
))
1769 } else { /* policy_types are equal. */
1770 if (addr_policy_covers(tmp
, ap
)) {
1771 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
1772 policy_write_item(p1
, sizeof(p1
), ap
, 0);
1773 policy_write_item(p2
, sizeof(p2
), tmp
, 0);
1774 log_debug(LD_CONFIG
, "Removing exit policy %s. It is already "
1775 "covered by %s.", p1
, p2
);
1776 smartlist_del_keeporder(dest
, i
--);
1777 addr_policy_free(ap
);
1785 /** Reject private helper for policies_parse_exit_policy_internal: rejects
1786 * publicly routable addresses on this exit relay.
1788 * Add reject entries to the linked list *<b>dest</b>:
1790 * <li>if configured_addresses is non-NULL, add entries that reject each
1791 * tor_addr_t in the list as a destination.
1792 * <li>if reject_interface_addresses is true, add entries that reject each
1793 * public IPv4 and IPv6 address of each interface on this machine.
1794 * <li>if reject_configured_port_addresses is true, add entries that reject
1795 * each IPv4 and IPv6 address configured for a port.
1798 * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
1799 * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
1802 * The list in <b>dest</b> is created as needed.
1805 policies_parse_exit_policy_reject_private(
1808 const smartlist_t
*configured_addresses
,
1809 int reject_interface_addresses
,
1810 int reject_configured_port_addresses
)
1814 /* Reject configured addresses, if they are from public netblocks. */
1815 if (configured_addresses
) {
1816 addr_policy_append_reject_addr_list_filter(dest
, configured_addresses
,
1820 /* Reject configured port addresses, if they are from public netblocks. */
1821 if (reject_configured_port_addresses
) {
1822 const smartlist_t
*port_addrs
= get_configured_ports();
1824 SMARTLIST_FOREACH_BEGIN(port_addrs
, port_cfg_t
*, port
) {
1826 /* Only reject port IP addresses, not port unix sockets */
1827 if (!port
->is_unix_addr
) {
1828 addr_policy_append_reject_addr_filter(dest
, &port
->addr
, 1, ipv6_exit
);
1830 } SMARTLIST_FOREACH_END(port
);
1833 /* Reject local addresses from public netblocks on any interface. */
1834 if (reject_interface_addresses
) {
1835 smartlist_t
*public_addresses
= NULL
;
1837 /* Reject public IPv4 addresses on any interface */
1838 public_addresses
= get_interface_address6_list(LOG_INFO
, AF_INET
, 0);
1839 addr_policy_append_reject_addr_list_filter(dest
, public_addresses
, 1, 0);
1840 interface_address6_list_free(public_addresses
);
1842 /* Don't look for IPv6 addresses if we're configured as IPv4-only */
1844 /* Reject public IPv6 addresses on any interface */
1845 public_addresses
= get_interface_address6_list(LOG_INFO
, AF_INET6
, 0);
1846 addr_policy_append_reject_addr_list_filter(dest
, public_addresses
, 0, 1);
1847 interface_address6_list_free(public_addresses
);
1851 /* If addresses were added multiple times, remove all but one of them. */
1853 exit_policy_remove_redundancies(*dest
);
1858 * Iterate through <b>policy</b> looking for redundant entries. Log a
1859 * warning message with the first redundant entry, if any is found.
1862 policies_log_first_redundant_entry(const smartlist_t
*policy
)
1864 int found_final_effective_entry
= 0;
1865 int first_redundant_entry
= 0;
1867 SMARTLIST_FOREACH_BEGIN(policy
, const addr_policy_t
*, p
) {
1869 int found_ipv4_wildcard
= 0, found_ipv6_wildcard
= 0;
1870 const int i
= p_sl_idx
;
1872 /* Look for accept/reject *[4|6|]:* entries */
1873 if (p
->prt_min
<= 1 && p
->prt_max
== 65535 && p
->maskbits
== 0) {
1874 family
= tor_addr_family(&p
->addr
);
1875 /* accept/reject *:* may have already been expanded into
1876 * accept/reject *4:*,accept/reject *6:*
1877 * But handle both forms.
1879 if (family
== AF_INET
|| family
== AF_UNSPEC
) {
1880 found_ipv4_wildcard
= 1;
1882 if (family
== AF_INET6
|| family
== AF_UNSPEC
) {
1883 found_ipv6_wildcard
= 1;
1887 /* We also find accept *4:*,reject *6:* ; and
1888 * accept *4:*,<other policies>,accept *6:* ; and similar.
1889 * That's ok, because they make any subsequent entries redundant. */
1890 if (found_ipv4_wildcard
&& found_ipv6_wildcard
) {
1891 found_final_effective_entry
= 1;
1892 /* if we're not on the final entry in the list */
1893 if (i
< smartlist_len(policy
) - 1) {
1894 first_redundant_entry
= i
+ 1;
1898 } SMARTLIST_FOREACH_END(p
);
1900 /* Work out if there are redundant trailing entries in the policy list */
1901 if (found_final_effective_entry
&& first_redundant_entry
> 0) {
1902 const addr_policy_t
*p
;
1903 /* Longest possible policy is
1904 * "accept6 ffff:ffff:..255/128:10000-65535",
1905 * which contains a max-length IPv6 address, plus 24 characters. */
1906 char line
[TOR_ADDR_BUF_LEN
+ 32];
1908 tor_assert(first_redundant_entry
< smartlist_len(policy
));
1909 p
= smartlist_get(policy
, first_redundant_entry
);
1910 /* since we've already parsed the policy into an addr_policy_t struct,
1911 * we might not log exactly what the user typed in */
1912 policy_write_item(line
, TOR_ADDR_BUF_LEN
+ 32, p
, 0);
1913 log_warn(LD_DIR
, "Exit policy '%s' and all following policies are "
1914 "redundant, as it follows accept/reject *:* rules for both "
1915 "IPv4 and IPv6. They will be removed from the exit policy. (Use "
1916 "accept/reject *:* as the last entry in any exit policy.)",
1921 #define DEFAULT_EXIT_POLICY \
1922 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
1923 "reject *:563,reject *:1214,reject *:4661-4666," \
1924 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
1926 #define REDUCED_EXIT_POLICY \
1927 "accept *:20-23,accept *:43,accept *:53,accept *:79-81,accept *:88," \
1928 "accept *:110,accept *:143,accept *:194,accept *:220,accept *:389," \
1929 "accept *:443,accept *:464,accept *:465,accept *:531,accept *:543-544," \
1930 "accept *:554,accept *:563,accept *:587,accept *:636,accept *:706," \
1931 "accept *:749,accept *:873,accept *:902-904,accept *:981,accept *:989-995," \
1932 "accept *:1194,accept *:1220,accept *:1293,accept *:1500,accept *:1533," \
1933 "accept *:1677,accept *:1723,accept *:1755,accept *:1863," \
1934 "accept *:2082-2083,accept *:2086-2087,accept *:2095-2096," \
1935 "accept *:2102-2104,accept *:3128,accept *:3389,accept *:3690," \
1936 "accept *:4321,accept *:4643,accept *:5050,accept *:5190," \
1937 "accept *:5222-5223,accept *:5228,accept *:5900,accept *:6660-6669," \
1938 "accept *:6679,accept *:6697,accept *:8000,accept *:8008,accept *:8074," \
1939 "accept *:8080,accept *:8082,accept *:8087-8088,accept *:8232-8233," \
1940 "accept *:8332-8333,accept *:8443,accept *:8888,accept *:9418," \
1941 "accept *:9999,accept *:10000,accept *:11371,accept *:19294," \
1942 "accept *:19638,accept *:50002,accept *:64738,reject *:*"
1944 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
1946 * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
1948 * If <b>configured_addresses</b> contains addresses:
1949 * - prepend entries that reject the addresses in this list. These may be the
1950 * advertised relay addresses and/or the outbound bind addresses,
1951 * depending on the ExitPolicyRejectPrivate and
1952 * ExitPolicyRejectLocalInterfaces settings.
1953 * If <b>rejectprivate</b> is true:
1954 * - prepend "reject private:*" to the policy.
1955 * If <b>reject_interface_addresses</b> is true:
1956 * - prepend entries that reject publicly routable interface addresses on
1957 * this exit relay by calling policies_parse_exit_policy_reject_private
1958 * If <b>reject_configured_port_addresses</b> is true:
1959 * - prepend entries that reject all configured port addresses
1961 * If cfg doesn't end in an absolute accept or reject and if
1962 * <b>add_default_policy</b> is true, add the default exit
1963 * policy afterwards.
1965 * Return -1 if we can't parse cfg, else return 0.
1967 * This function is used to parse the exit policy from our torrc. For
1968 * the functions used to parse the exit policy from a router descriptor,
1969 * see router_add_exit_policy.
1972 policies_parse_exit_policy_internal(config_line_t
*cfg
,
1976 const smartlist_t
*configured_addresses
,
1977 int reject_interface_addresses
,
1978 int reject_configured_port_addresses
,
1979 int add_default_policy
,
1980 int add_reduced_policy
)
1983 append_exit_policy_string(dest
, "reject *6:*");
1985 if (rejectprivate
) {
1986 /* Reject IPv4 and IPv6 reserved private netblocks */
1987 append_exit_policy_string(dest
, "reject private:*");
1990 /* Consider rejecting IPv4 and IPv6 advertised relay addresses, outbound bind
1991 * addresses, publicly routable addresses, and configured port addresses
1992 * on this exit relay */
1993 policies_parse_exit_policy_reject_private(dest
, ipv6_exit
,
1994 configured_addresses
,
1995 reject_interface_addresses
,
1996 reject_configured_port_addresses
);
1998 if (parse_addr_policy(cfg
, dest
, -1))
2001 /* Before we add the default policy and final rejects, check to see if
2002 * there are any lines after accept *:* or reject *:*. These lines have no
2003 * effect, and are most likely an error. */
2004 policies_log_first_redundant_entry(*dest
);
2006 if (add_reduced_policy
) {
2007 append_exit_policy_string(dest
, REDUCED_EXIT_POLICY
);
2008 } else if (add_default_policy
) {
2009 append_exit_policy_string(dest
, DEFAULT_EXIT_POLICY
);
2011 append_exit_policy_string(dest
, "reject *4:*");
2012 append_exit_policy_string(dest
, "reject *6:*");
2014 exit_policy_remove_redundancies(*dest
);
2019 /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
2021 * Prepend an entry that rejects all IPv6 destinations unless
2022 * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
2024 * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
2025 * - prepend an entry that rejects all destinations in all netblocks
2026 * reserved for private use.
2027 * - prepend entries that reject the advertised relay addresses in
2028 * configured_addresses
2029 * If <b>EXIT_POLICY_REJECT_LOCAL_INTERFACES</b> bit is set in <b>options</b>:
2030 * - prepend entries that reject publicly routable addresses on this exit
2031 * relay by calling policies_parse_exit_policy_internal
2032 * - prepend entries that reject the outbound bind addresses in
2033 * configured_addresses
2034 * - prepend entries that reject all configured port addresses
2036 * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
2037 * default exit policy entries to <b>result</b> smartlist.
2040 policies_parse_exit_policy(config_line_t
*cfg
, smartlist_t
**dest
,
2041 exit_policy_parser_cfg_t options
,
2042 const smartlist_t
*configured_addresses
)
2044 int ipv6_enabled
= (options
& EXIT_POLICY_IPV6_ENABLED
) ? 1 : 0;
2045 int reject_private
= (options
& EXIT_POLICY_REJECT_PRIVATE
) ? 1 : 0;
2046 int add_default
= (options
& EXIT_POLICY_ADD_DEFAULT
) ? 1 : 0;
2047 int reject_local_interfaces
= (options
&
2048 EXIT_POLICY_REJECT_LOCAL_INTERFACES
) ? 1 : 0;
2049 int add_reduced
= (options
& EXIT_POLICY_ADD_REDUCED
) ? 1 : 0;
2051 return policies_parse_exit_policy_internal(cfg
,dest
,ipv6_enabled
,
2053 configured_addresses
,
2054 reject_local_interfaces
,
2055 reject_local_interfaces
,
2060 /** Helper function that adds a copy of addr to a smartlist as long as it is
2061 * non-NULL and not tor_addr_is_null().
2063 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2066 policies_copy_addr_to_smartlist(smartlist_t
*addr_list
, const tor_addr_t
*addr
)
2068 if (addr
&& !tor_addr_is_null(addr
)) {
2069 tor_addr_t
*addr_copy
= tor_malloc(sizeof(tor_addr_t
));
2070 tor_addr_copy(addr_copy
, addr
);
2071 smartlist_add(addr_list
, addr_copy
);
2075 /** Helper function that adds copies of or_options->OutboundBindAddresses
2076 * to a smartlist as tor_addr_t *, as long as or_options is non-NULL, and
2077 * the addresses are not tor_addr_is_null(), by passing them to
2078 * policies_add_addr_to_smartlist.
2080 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2083 policies_copy_outbound_addresses_to_smartlist(smartlist_t
*addr_list
,
2084 const or_options_t
*or_options
)
2087 for (int i
=0;i
<OUTBOUND_ADDR_MAX
;i
++) {
2088 for (int j
=0;j
<2;j
++) {
2089 if (!tor_addr_is_null(&or_options
->OutboundBindAddresses
[i
][j
])) {
2090 policies_copy_addr_to_smartlist(addr_list
,
2091 &or_options
->OutboundBindAddresses
[i
][j
]);
2098 /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
2100 * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
2101 * rejects all IPv6 destinations.
2103 * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
2104 * - prepend an entry that rejects all destinations in all netblocks reserved
2106 * - if ipv4_local_address is non-zero, treat it as a host-order IPv4 address,
2107 * and add it to the list of configured addresses.
2108 * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
2109 * to the list of configured addresses.
2110 * If <b>or_options->ExitPolicyRejectLocalInterfaces</b> is true:
2111 * - if or_options->OutboundBindAddresses[][0] (=IPv4) is not the null
2112 * tor_addr_t, add it to the list of configured addresses.
2113 * - if or_options->OutboundBindAddresses[][1] (=IPv6) is not the null
2114 * tor_addr_t, add it to the list of configured addresses.
2116 * If <b>or_options->BridgeRelay</b> is false, append entries of default
2117 * Tor exit policy into <b>result</b> smartlist.
2119 * If or_options->ExitRelay is false, or is auto without specifying an exit
2120 * policy, then make our exit policy into "reject *:*" regardless.
2123 policies_parse_exit_policy_from_options(const or_options_t
*or_options
,
2124 const tor_addr_t
*ipv4_local_address
,
2125 const tor_addr_t
*ipv6_local_address
,
2126 smartlist_t
**result
)
2128 exit_policy_parser_cfg_t parser_cfg
= 0;
2129 smartlist_t
*configured_addresses
= NULL
;
2132 /* Short-circuit for non-exit relays, or for relays where we didn't specify
2133 * ExitPolicy or ReducedExitPolicy or IPv6Exit and ExitRelay is auto. */
2134 if (or_options
->ExitRelay
== 0 ||
2135 policy_using_default_exit_options(or_options
)) {
2136 append_exit_policy_string(result
, "reject *4:*");
2137 append_exit_policy_string(result
, "reject *6:*");
2141 configured_addresses
= smartlist_new();
2143 /* Configure the parser */
2144 if (or_options
->IPv6Exit
) {
2145 parser_cfg
|= EXIT_POLICY_IPV6_ENABLED
;
2148 if (or_options
->ExitPolicyRejectPrivate
) {
2149 parser_cfg
|= EXIT_POLICY_REJECT_PRIVATE
;
2152 if (!or_options
->BridgeRelay
) {
2153 if (or_options
->ReducedExitPolicy
)
2154 parser_cfg
|= EXIT_POLICY_ADD_REDUCED
;
2156 parser_cfg
|= EXIT_POLICY_ADD_DEFAULT
;
2159 if (or_options
->ExitPolicyRejectLocalInterfaces
) {
2160 parser_cfg
|= EXIT_POLICY_REJECT_LOCAL_INTERFACES
;
2163 /* Copy the configured addresses into the tor_addr_t* list */
2164 if (or_options
->ExitPolicyRejectPrivate
) {
2165 policies_copy_addr_to_smartlist(configured_addresses
, ipv4_local_address
);
2166 policies_copy_addr_to_smartlist(configured_addresses
, ipv6_local_address
);
2169 if (or_options
->ExitPolicyRejectLocalInterfaces
) {
2170 policies_copy_outbound_addresses_to_smartlist(configured_addresses
,
2174 rv
= policies_parse_exit_policy(or_options
->ExitPolicy
, result
, parser_cfg
,
2175 configured_addresses
);
2177 SMARTLIST_FOREACH(configured_addresses
, tor_addr_t
*, a
, tor_free(a
));
2178 smartlist_free(configured_addresses
);
2183 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
2184 * *<b>dest</b> as needed. */
2186 policies_exit_policy_append_reject_star(smartlist_t
**dest
)
2188 append_exit_policy_string(dest
, "reject *4:*");
2189 append_exit_policy_string(dest
, "reject *6:*");
2192 /** Replace the exit policy of <b>node</b> with reject *:* */
2194 policies_set_node_exitpolicy_to_reject_all(node_t
*node
)
2196 node
->rejects_all
= 1;
2199 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
2200 * allows exiting to <b>port</b>. Otherwise, return 0. */
2202 exit_policy_is_general_exit_helper(smartlist_t
*policy
, int port
)
2204 uint32_t mask
, ip
, i
;
2205 /* Is this /8 rejected (1), or undecided (0)? */
2206 char subnet_status
[256];
2208 memset(subnet_status
, 0, sizeof(subnet_status
));
2209 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
2210 if (tor_addr_family(&p
->addr
) != AF_INET
)
2211 continue; /* IPv4 only for now */
2212 if (p
->prt_min
> port
|| p
->prt_max
< port
)
2213 continue; /* Doesn't cover our port. */
2215 tor_assert(p
->maskbits
<= 32);
2218 mask
= UINT32_MAX
<<(32-p
->maskbits
);
2219 ip
= tor_addr_to_ipv4h(&p
->addr
);
2221 /* Calculate the first and last subnet that this exit policy touches
2222 * and set it as loop boundaries. */
2223 for (i
= ((mask
& ip
)>>24); i
<= (~((mask
& ip
) ^ mask
)>>24); ++i
) {
2225 if (subnet_status
[i
] != 0)
2226 continue; /* We already reject some part of this /8 */
2227 tor_addr_from_ipv4h(&addr
, i
<<24);
2228 if (tor_addr_is_internal(&addr
, 0) &&
2229 !get_options()->DirAllowPrivateAddresses
) {
2230 continue; /* Local or non-routable addresses */
2232 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
2233 if (p
->maskbits
> 8)
2234 continue; /* Narrower than a /8. */
2235 /* We found an allowed subnet of at least size /8. Done
2238 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
2239 subnet_status
[i
] = 1;
2242 } SMARTLIST_FOREACH_END(p
);
2246 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
2247 * it allows exit to at least one /8 address space for each of ports 80
2250 exit_policy_is_general_exit(smartlist_t
*policy
)
2252 if (!policy
) /*XXXX disallow NULL policies? */
2255 return (exit_policy_is_general_exit_helper(policy
, 80) &&
2256 exit_policy_is_general_exit_helper(policy
, 443));
2259 /** Return false if <b>policy</b> might permit access to some addr:port;
2260 * otherwise if we are certain it rejects everything, return true. If no
2261 * part of <b>policy</b> matches, return <b>default_reject</b>.
2262 * NULL policies are allowed, and treated as empty. */
2264 policy_is_reject_star(const smartlist_t
*policy
, sa_family_t family
,
2268 return default_reject
;
2269 SMARTLIST_FOREACH_BEGIN(policy
, const addr_policy_t
*, p
) {
2270 if (p
->policy_type
== ADDR_POLICY_ACCEPT
&&
2271 (tor_addr_family(&p
->addr
) == family
||
2272 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
2274 } else if (p
->policy_type
== ADDR_POLICY_REJECT
&&
2275 p
->prt_min
<= 1 && p
->prt_max
== 65535 &&
2277 (tor_addr_family(&p
->addr
) == family
||
2278 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
2281 } SMARTLIST_FOREACH_END(p
);
2282 return default_reject
;
2285 /** Write a single address policy to the buf_len byte buffer at buf. Return
2286 * the number of characters written, or -1 on failure. */
2288 policy_write_item(char *buf
, size_t buflen
, const addr_policy_t
*policy
,
2289 int format_for_desc
)
2292 char addrbuf
[TOR_ADDR_BUF_LEN
];
2293 const char *addrpart
;
2295 const int is_accept
= policy
->policy_type
== ADDR_POLICY_ACCEPT
;
2296 const sa_family_t family
= tor_addr_family(&policy
->addr
);
2297 const int is_ip6
= (family
== AF_INET6
);
2299 tor_addr_to_str(addrbuf
, &policy
->addr
, sizeof(addrbuf
), 1);
2301 /* write accept/reject 1.2.3.4 */
2302 if (policy
->is_private
) {
2303 addrpart
= "private";
2304 } else if (policy
->maskbits
== 0) {
2305 if (format_for_desc
)
2307 else if (family
== AF_INET6
)
2309 else if (family
== AF_INET
)
2317 result
= tor_snprintf(buf
, buflen
, "%s%s %s",
2318 is_accept
? "accept" : "reject",
2319 (is_ip6
&&format_for_desc
)?"6":"",
2323 written
+= strlen(buf
);
2324 /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
2325 the mask is 0, we already wrote "*". */
2326 if (policy
->maskbits
< (is_ip6
?128:32) && policy
->maskbits
> 0) {
2327 if (tor_snprintf(buf
+written
, buflen
-written
, "/%d", policy
->maskbits
)<0)
2329 written
+= strlen(buf
+written
);
2331 if (policy
->prt_min
<= 1 && policy
->prt_max
== 65535) {
2332 /* There is no port set; write ":*" */
2333 if (written
+4 > buflen
)
2335 strlcat(buf
+written
, ":*", buflen
-written
);
2337 } else if (policy
->prt_min
== policy
->prt_max
) {
2338 /* There is only one port; write ":80". */
2339 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d", policy
->prt_min
);
2344 /* There is a range of ports; write ":79-80". */
2345 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d-%d",
2346 policy
->prt_min
, policy
->prt_max
);
2351 if (written
< buflen
)
2352 buf
[written
] = '\0';
2356 return (int)written
;
2359 /** Create a new exit policy summary, initially only with a single
2360 * port 1-64k item */
2361 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
2362 * RB-tree if that turns out to matter. */
2363 static smartlist_t
*
2364 policy_summary_create(void)
2366 smartlist_t
*summary
;
2367 policy_summary_item_t
* item
;
2369 item
= tor_malloc_zero(sizeof(policy_summary_item_t
));
2371 item
->prt_max
= 65535;
2372 item
->reject_count
= 0;
2375 summary
= smartlist_new();
2376 smartlist_add(summary
, item
);
2381 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
2382 * The current item is changed to end at new-starts - 1, the new item
2383 * copies reject_count and accepted from the old item,
2384 * starts at new_starts and ends at the port where the original item
2387 static policy_summary_item_t
*
2388 policy_summary_item_split(policy_summary_item_t
* old
, uint16_t new_starts
)
2390 policy_summary_item_t
* new;
2392 new = tor_malloc_zero(sizeof(policy_summary_item_t
));
2393 new->prt_min
= new_starts
;
2394 new->prt_max
= old
->prt_max
;
2395 new->reject_count
= old
->reject_count
;
2396 new->accepted
= old
->accepted
;
2398 old
->prt_max
= new_starts
-1;
2400 tor_assert(old
->prt_min
<= old
->prt_max
);
2401 tor_assert(new->prt_min
<= new->prt_max
);
2405 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
2406 * my immortal soul, he can clean it up himself. */
2407 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
2409 #define IPV4_BITS (32)
2410 /* Every IPv4 address is counted as one rejection */
2411 #define REJECT_CUTOFF_SCALE_IPV4 (0)
2412 /* Ports are rejected in an IPv4 summary if they are rejected in more than two
2413 * IPv4 /8 address blocks */
2414 #define REJECT_CUTOFF_COUNT_IPV4 (UINT64_C(1) << \
2415 (IPV4_BITS - REJECT_CUTOFF_SCALE_IPV4 - 7))
2417 #define IPV6_BITS (128)
2418 /* IPv6 /64s are counted as one rejection, anything smaller is ignored */
2419 #define REJECT_CUTOFF_SCALE_IPV6 (64)
2420 /* Ports are rejected in an IPv6 summary if they are rejected in more than one
2421 * IPv6 /16 address block.
2422 * This is roughly equivalent to the IPv4 cutoff, as only five IPv6 /12s (and
2423 * some scattered smaller blocks) have been allocated to the RIRs.
2424 * Network providers are typically allocated one or more IPv6 /32s.
2426 #define REJECT_CUTOFF_COUNT_IPV6 (UINT64_C(1) << \
2427 (IPV6_BITS - REJECT_CUTOFF_SCALE_IPV6 - 16))
2429 /** Split an exit policy summary so that prt_min and prt_max
2430 * fall at exactly the start and end of an item respectively.
2433 policy_summary_split(smartlist_t
*summary
,
2434 uint16_t prt_min
, uint16_t prt_max
)
2440 while (AT(i
)->prt_max
< prt_min
)
2442 if (AT(i
)->prt_min
!= prt_min
) {
2443 policy_summary_item_t
* new_item
;
2444 new_item
= policy_summary_item_split(AT(i
), prt_min
);
2445 smartlist_insert(summary
, i
+1, new_item
);
2450 while (AT(i
)->prt_max
< prt_max
)
2452 if (AT(i
)->prt_max
!= prt_max
) {
2453 policy_summary_item_t
* new_item
;
2454 new_item
= policy_summary_item_split(AT(i
), prt_max
+1);
2455 smartlist_insert(summary
, i
+1, new_item
);
2458 return start_at_index
;
2461 /** Mark port ranges as accepted if they are below the reject_count for family
2464 policy_summary_accept(smartlist_t
*summary
,
2465 uint16_t prt_min
, uint16_t prt_max
,
2468 tor_assert_nonfatal_once(family
== AF_INET
|| family
== AF_INET6
);
2469 uint64_t family_reject_count
= ((family
== AF_INET
) ?
2470 REJECT_CUTOFF_COUNT_IPV4
:
2471 REJECT_CUTOFF_COUNT_IPV6
);
2473 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
2474 while (i
< smartlist_len(summary
) &&
2475 AT(i
)->prt_max
<= prt_max
) {
2476 if (!AT(i
)->accepted
&&
2477 AT(i
)->reject_count
<= family_reject_count
)
2478 AT(i
)->accepted
= 1;
2481 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
2484 /** Count the number of addresses in a network in family with prefixlen
2485 * maskbits against the given portrange. */
2487 policy_summary_reject(smartlist_t
*summary
,
2488 maskbits_t maskbits
,
2489 uint16_t prt_min
, uint16_t prt_max
,
2492 tor_assert_nonfatal_once(family
== AF_INET
|| family
== AF_INET6
);
2494 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
2496 /* The length of a single address mask */
2497 int addrbits
= (family
== AF_INET
) ? IPV4_BITS
: IPV6_BITS
;
2498 tor_assert_nonfatal_once(addrbits
>= maskbits
);
2500 /* We divide IPv6 address counts by (1 << scale) to keep them in a uint64_t
2502 int scale
= ((family
== AF_INET
) ?
2503 REJECT_CUTOFF_SCALE_IPV4
:
2504 REJECT_CUTOFF_SCALE_IPV6
);
2506 tor_assert_nonfatal_once(addrbits
>= scale
);
2507 if (maskbits
> (addrbits
- scale
)) {
2508 tor_assert_nonfatal_once(family
== AF_INET6
);
2509 /* The address range is so small, we'd need billions of them to reach the
2510 * rejection limit. So we ignore this range in the reject count. */
2515 if (addrbits
- scale
- maskbits
>= 64) {
2516 tor_assert_nonfatal_once(family
== AF_INET6
);
2517 /* The address range is so large, it's an automatic rejection for all ports
2521 count
= (UINT64_C(1) << (addrbits
- scale
- maskbits
));
2523 tor_assert_nonfatal_once(count
> 0);
2524 while (i
< smartlist_len(summary
) &&
2525 AT(i
)->prt_max
<= prt_max
) {
2526 if (AT(i
)->reject_count
<= UINT64_MAX
- count
) {
2527 AT(i
)->reject_count
+= count
;
2529 /* IPv4 would require a 4-billion address redundant policy to get here,
2530 * but IPv6 just needs to have ::/0 */
2531 if (family
== AF_INET
) {
2532 tor_assert_nonfatal_unreached_once();
2534 /* If we do get here, use saturating arithmetic */
2535 AT(i
)->reject_count
= UINT64_MAX
;
2539 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
2542 /** Add a single exit policy item to our summary:
2544 * If it is an accept, ignore it unless it is for all IP addresses
2545 * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
2546 * policy_summary_accept().
2548 * If it is a reject, ignore it if it is about one of the private
2549 * networks. Otherwise call policy_summary_reject().
2552 policy_summary_add_item(smartlist_t
*summary
, addr_policy_t
*p
)
2554 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
2555 if (p
->maskbits
== 0) {
2556 policy_summary_accept(summary
, p
->prt_min
, p
->prt_max
, p
->addr
.family
);
2558 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
2562 for (i
= 0; private_nets
[i
]; ++i
) {
2564 maskbits_t maskbits
;
2565 if (tor_addr_parse_mask_ports(private_nets
[i
], 0, &addr
,
2566 &maskbits
, NULL
, NULL
)<0) {
2569 if (tor_addr_compare(&p
->addr
, &addr
, CMP_EXACT
) == 0 &&
2570 p
->maskbits
== maskbits
) {
2577 policy_summary_reject(summary
, p
->maskbits
, p
->prt_min
, p
->prt_max
,
2584 /** Create a string representing a summary for an exit policy.
2585 * The summary will either be an "accept" plus a comma-separated list of port
2586 * ranges or a "reject" plus port-ranges, depending on which is shorter.
2588 * If no exits are allowed at all then "reject 1-65535" is returned. If no
2589 * ports are blocked instead of "reject " we return "accept 1-65535". (These
2590 * are an exception to the shorter-representation-wins rule).
2593 policy_summarize(smartlist_t
*policy
, sa_family_t family
)
2595 smartlist_t
*summary
= policy_summary_create();
2596 smartlist_t
*accepts
, *rejects
;
2597 int i
, last
, start_prt
;
2598 size_t accepts_len
, rejects_len
;
2599 char *accepts_str
= NULL
, *rejects_str
= NULL
, *shorter_str
, *result
;
2604 /* Create the summary list */
2605 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
2606 sa_family_t f
= tor_addr_family(&p
->addr
);
2607 if (f
!= AF_INET
&& f
!= AF_INET6
) {
2608 log_warn(LD_BUG
, "Weird family when summarizing address policy");
2612 policy_summary_add_item(summary
, p
);
2613 } SMARTLIST_FOREACH_END(p
);
2615 /* Now create two lists of strings, one for accepted and one
2616 * for rejected ports. We take care to merge ranges so that
2617 * we avoid getting stuff like "1-4,5-9,10", instead we want
2622 accepts
= smartlist_new();
2623 rejects
= smartlist_new();
2625 last
= i
== smartlist_len(summary
)-1;
2627 AT(i
)->accepted
!= AT(i
+1)->accepted
) {
2628 char buf
[POLICY_BUF_LEN
];
2630 if (start_prt
== AT(i
)->prt_max
)
2631 tor_snprintf(buf
, sizeof(buf
), "%d", start_prt
);
2633 tor_snprintf(buf
, sizeof(buf
), "%d-%d", start_prt
, AT(i
)->prt_max
);
2635 if (AT(i
)->accepted
)
2636 smartlist_add_strdup(accepts
, buf
);
2638 smartlist_add_strdup(rejects
, buf
);
2643 start_prt
= AT(i
+1)->prt_min
;
2648 /* Figure out which of the two stringlists will be shorter and use
2649 * that to build the result
2651 if (smartlist_len(accepts
) == 0) { /* no exits at all */
2652 result
= tor_strdup("reject 1-65535");
2655 if (smartlist_len(rejects
) == 0) { /* no rejects at all */
2656 result
= tor_strdup("accept 1-65535");
2660 accepts_str
= smartlist_join_strings(accepts
, ",", 0, &accepts_len
);
2661 rejects_str
= smartlist_join_strings(rejects
, ",", 0, &rejects_len
);
2663 if (rejects_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("reject")-1 &&
2664 accepts_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("accept")-1) {
2666 shorter_str
= accepts_str
;
2669 c
= shorter_str
+ (MAX_EXITPOLICY_SUMMARY_LEN
-strlen(prefix
)-1);
2670 while (*c
!= ',' && c
>= shorter_str
)
2672 tor_assert(c
>= shorter_str
);
2673 tor_assert(*c
== ',');
2676 } else if (rejects_len
< accepts_len
) {
2677 shorter_str
= rejects_str
;
2680 shorter_str
= accepts_str
;
2684 tor_asprintf(&result
, "%s %s", prefix
, shorter_str
);
2688 SMARTLIST_FOREACH(summary
, policy_summary_item_t
*, s
, tor_free(s
));
2689 smartlist_free(summary
);
2691 tor_free(accepts_str
);
2692 SMARTLIST_FOREACH(accepts
, char *, s
, tor_free(s
));
2693 smartlist_free(accepts
);
2695 tor_free(rejects_str
);
2696 SMARTLIST_FOREACH(rejects
, char *, s
, tor_free(s
));
2697 smartlist_free(rejects
);
2702 /** Convert a summarized policy string into a short_policy_t. Return NULL
2703 * if the string is not well-formed. */
2705 parse_short_policy(const char *summary
)
2707 const char *orig_summary
= summary
;
2708 short_policy_t
*result
;
2711 short_policy_entry_t entries
[MAX_EXITPOLICY_SUMMARY_LEN
]; /* overkill */
2714 if (!strcmpstart(summary
, "accept ")) {
2716 summary
+= strlen("accept ");
2717 } else if (!strcmpstart(summary
, "reject ")) {
2719 summary
+= strlen("reject ");
2721 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Unrecognized policy summary keyword");
2726 for ( ; *summary
; summary
= next
) {
2727 if (n_entries
== MAX_EXITPOLICY_SUMMARY_LEN
) {
2728 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Impossibly long policy summary %s",
2729 escaped(orig_summary
));
2735 low
= (unsigned) tor_parse_ulong(summary
, 10, 1, 65535, &ok
, &next
);
2737 if (! TOR_ISDIGIT(*summary
) || *summary
== ',') {
2738 /* Unrecognized format: skip it. */
2753 high
= (unsigned) tor_parse_ulong(next
+1, 10, low
, 65535, &ok
, &next
);
2759 else if (*next
!= '\0')
2767 entries
[n_entries
].min_port
= low
;
2768 entries
[n_entries
].max_port
= high
;
2773 next
= strchr(next
, ',');
2779 if (n_entries
== 0) {
2780 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
2781 "Found no port-range entries in summary %s", escaped(orig_summary
));
2786 size_t size
= offsetof(short_policy_t
, entries
) +
2787 sizeof(short_policy_entry_t
)*(n_entries
);
2788 result
= tor_malloc_zero(size
);
2790 tor_assert( (char*)&result
->entries
[n_entries
-1] < ((char*)result
)+size
);
2793 result
->is_accept
= is_accept
;
2794 result
->n_entries
= n_entries
;
2795 memcpy(result
->entries
, entries
, sizeof(short_policy_entry_t
)*n_entries
);
2799 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,"Found bad entry in policy summary %s",
2800 escaped(orig_summary
));
2804 /** Write <b>policy</b> back out into a string. */
2806 write_short_policy(const short_policy_t
*policy
)
2810 smartlist_t
*sl
= smartlist_new();
2812 smartlist_add_asprintf(sl
, "%s", policy
->is_accept
? "accept " : "reject ");
2814 for (i
=0; i
< policy
->n_entries
; i
++) {
2815 const short_policy_entry_t
*e
= &policy
->entries
[i
];
2816 if (e
->min_port
== e
->max_port
) {
2817 smartlist_add_asprintf(sl
, "%d", e
->min_port
);
2819 smartlist_add_asprintf(sl
, "%d-%d", e
->min_port
, e
->max_port
);
2821 if (i
< policy
->n_entries
-1)
2822 smartlist_add_strdup(sl
, ",");
2824 answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2825 SMARTLIST_FOREACH(sl
, char *, a
, tor_free(a
));
2830 /** Release all storage held in <b>policy</b>. */
2832 short_policy_free_(short_policy_t
*policy
)
2837 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
2838 * or rejected by the summarized policy <b>policy</b>. Return values are as
2839 * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
2840 * functions, requires the <b>port</b> be specified. */
2841 addr_policy_result_t
2842 compare_tor_addr_to_short_policy(const tor_addr_t
*addr
, uint16_t port
,
2843 const short_policy_t
*policy
)
2846 int found_match
= 0;
2849 tor_assert(port
!= 0);
2851 if (addr
&& tor_addr_is_null(addr
))
2852 addr
= NULL
; /* Unspec means 'no address at all,' in this context. */
2854 if (addr
&& get_options()->ClientRejectInternalAddresses
&&
2855 (tor_addr_is_internal(addr
, 0) || tor_addr_is_loopback(addr
)))
2856 return ADDR_POLICY_REJECTED
;
2858 for (i
=0; i
< policy
->n_entries
; ++i
) {
2859 const short_policy_entry_t
*e
= &policy
->entries
[i
];
2860 if (e
->min_port
<= port
&& port
<= e
->max_port
) {
2867 accept_
= policy
->is_accept
;
2869 accept_
= ! policy
->is_accept
;
2871 /* ???? are these right? -NM */
2872 /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
2873 * case here, because it would cause clients to believe that the node
2874 * allows exit enclaving. Trying it anyway would open up a cool attack
2875 * where the node refuses due to exitpolicy, the client reacts in
2876 * surprise by rewriting the node's exitpolicy to reject *:*, and then
2877 * an adversary targets users by causing them to attempt such connections
2878 * to 98% of the exits.
2880 * Once microdescriptors can handle addresses in special cases (e.g. if
2881 * we ever solve ticket 1774), we can provide certainty here. -RD */
2883 return ADDR_POLICY_PROBABLY_ACCEPTED
;
2885 return ADDR_POLICY_REJECTED
;
2888 /** Return true iff <b>policy</b> seems reject all ports */
2890 short_policy_is_reject_star(const short_policy_t
*policy
)
2892 /* This doesn't need to be as much on the lookout as policy_is_reject_star,
2893 * since policy summaries are from the consensus or from consensus
2897 /* Check for an exact match of "reject 1-65535". */
2898 return (policy
->is_accept
== 0 && policy
->n_entries
== 1 &&
2899 policy
->entries
[0].min_port
== 1 &&
2900 policy
->entries
[0].max_port
== 65535);
2903 /** Decide whether addr:port is probably or definitely accepted or rejected by
2904 * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
2905 * interpretation. */
2906 addr_policy_result_t
2907 compare_tor_addr_to_node_policy(const tor_addr_t
*addr
, uint16_t port
,
2910 if (node
->rejects_all
)
2911 return ADDR_POLICY_REJECTED
;
2913 if (addr
&& tor_addr_family(addr
) == AF_INET6
) {
2914 const short_policy_t
*p
= NULL
;
2916 p
= node
->ri
->ipv6_exit_policy
;
2918 p
= node
->md
->ipv6_exit_policy
;
2920 return compare_tor_addr_to_short_policy(addr
, port
, p
);
2922 return ADDR_POLICY_REJECTED
;
2926 return compare_tor_addr_to_addr_policy(addr
, port
, node
->ri
->exit_policy
);
2927 } else if (node
->md
) {
2928 if (node
->md
->exit_policy
== NULL
)
2929 return ADDR_POLICY_REJECTED
;
2931 return compare_tor_addr_to_short_policy(addr
, port
,
2932 node
->md
->exit_policy
);
2934 return ADDR_POLICY_PROBABLY_REJECTED
;
2939 * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
2940 * representation of the list.
2941 * If <b>include_ipv4</b> is true, include IPv4 entries.
2942 * If <b>include_ipv6</b> is true, include IPv6 entries.
2945 policy_dump_to_string(const smartlist_t
*policy_list
,
2949 smartlist_t
*policy_string_list
;
2950 char *policy_string
= NULL
;
2952 policy_string_list
= smartlist_new();
2954 SMARTLIST_FOREACH_BEGIN(policy_list
, addr_policy_t
*, tmpe
) {
2956 int bytes_written_to_pbuf
;
2957 if ((tor_addr_family(&tmpe
->addr
) == AF_INET6
) && (!include_ipv6
)) {
2958 continue; /* Don't include IPv6 parts of address policy */
2960 if ((tor_addr_family(&tmpe
->addr
) == AF_INET
) && (!include_ipv4
)) {
2961 continue; /* Don't include IPv4 parts of address policy */
2964 pbuf
= tor_malloc(POLICY_BUF_LEN
);
2965 bytes_written_to_pbuf
= policy_write_item(pbuf
,POLICY_BUF_LEN
, tmpe
, 1);
2967 if (bytes_written_to_pbuf
< 0) {
2968 log_warn(LD_BUG
, "policy_dump_to_string ran out of room!");
2973 smartlist_add(policy_string_list
,pbuf
);
2974 } SMARTLIST_FOREACH_END(tmpe
);
2976 policy_string
= smartlist_join_strings(policy_string_list
, "\n", 0, NULL
);
2979 SMARTLIST_FOREACH(policy_string_list
, char *, str
, tor_free(str
));
2980 smartlist_free(policy_string_list
);
2982 return policy_string
;
2985 /** Implementation for GETINFO control command: knows the answer for questions
2986 * about "exit-policy/..." */
2988 getinfo_helper_policies(control_connection_t
*conn
,
2989 const char *question
, char **answer
,
2990 const char **errmsg
)
2994 if (!strcmp(question
, "exit-policy/default")) {
2995 *answer
= tor_strdup(DEFAULT_EXIT_POLICY
);
2996 } else if (!strcmp(question
, "exit-policy/reject-private/default")) {
2997 smartlist_t
*private_policy_strings
;
2998 const char **priv
= private_nets
;
3000 private_policy_strings
= smartlist_new();
3002 while (*priv
!= NULL
) {
3003 /* IPv6 addresses are in "[]" and contain ":",
3004 * IPv4 addresses are not in "[]" and contain "." */
3005 smartlist_add_asprintf(private_policy_strings
, "reject %s:*", *priv
);
3009 *answer
= smartlist_join_strings(private_policy_strings
,
3012 SMARTLIST_FOREACH(private_policy_strings
, char *, str
, tor_free(str
));
3013 smartlist_free(private_policy_strings
);
3014 } else if (!strcmp(question
, "exit-policy/reject-private/relay")) {
3015 const or_options_t
*options
= get_options();
3017 const routerinfo_t
*me
= router_get_my_routerinfo_with_err(&err
);
3020 *errmsg
= routerinfo_err_to_string(err
);
3021 return routerinfo_err_is_transient(err
) ? -1 : 0;
3024 if (!options
->ExitPolicyRejectPrivate
&&
3025 !options
->ExitPolicyRejectLocalInterfaces
) {
3026 *answer
= tor_strdup("");
3030 smartlist_t
*private_policy_list
= smartlist_new();
3031 smartlist_t
*configured_addresses
= smartlist_new();
3033 /* Copy the configured addresses into the tor_addr_t* list */
3034 if (options
->ExitPolicyRejectPrivate
) {
3035 policies_copy_addr_to_smartlist(configured_addresses
, &me
->ipv4_addr
);
3036 policies_copy_addr_to_smartlist(configured_addresses
, &me
->ipv6_addr
);
3039 if (options
->ExitPolicyRejectLocalInterfaces
) {
3040 policies_copy_outbound_addresses_to_smartlist(configured_addresses
,
3044 policies_parse_exit_policy_reject_private(
3045 &private_policy_list
,
3047 configured_addresses
,
3048 options
->ExitPolicyRejectLocalInterfaces
,
3049 options
->ExitPolicyRejectLocalInterfaces
);
3050 *answer
= policy_dump_to_string(private_policy_list
, 1, 1);
3052 addr_policy_list_free(private_policy_list
);
3053 SMARTLIST_FOREACH(configured_addresses
, tor_addr_t
*, a
, tor_free(a
));
3054 smartlist_free(configured_addresses
);
3055 } else if (!strcmpstart(question
, "exit-policy/")) {
3056 int include_ipv4
= 0;
3057 int include_ipv6
= 0;
3060 const routerinfo_t
*me
= router_get_my_routerinfo_with_err(&err
);
3063 *errmsg
= routerinfo_err_to_string(err
);
3064 return routerinfo_err_is_transient(err
) ? -1 : 0;
3067 if (!strcmp(question
, "exit-policy/ipv4")) {
3069 } else if (!strcmp(question
, "exit-policy/ipv6")) {
3071 } else if (!strcmp(question
, "exit-policy/full")) {
3072 include_ipv4
= include_ipv6
= 1;
3074 return 0; /* No such key. */
3077 *answer
= router_dump_exit_policy_to_string(me
,include_ipv4
,
3084 /** Release all storage held by <b>p</b>. */
3086 addr_policy_list_free_(smartlist_t
*lst
)
3090 SMARTLIST_FOREACH(lst
, addr_policy_t
*, policy
, addr_policy_free(policy
));
3091 smartlist_free(lst
);
3094 /** Release all storage held by <b>p</b>. */
3096 addr_policy_free_(addr_policy_t
*p
)
3101 if (--p
->refcnt
<= 0) {
3102 if (p
->is_canonical
) {
3103 policy_map_ent_t search
, *found
;
3105 found
= HT_REMOVE(policy_map
, &policy_root
, &search
);
3107 tor_assert(p
== found
->policy
);
3115 /** Release all storage held by policy variables. */
3117 policies_free_all(void)
3119 addr_policy_list_free(reachable_or_addr_policy
);
3120 reachable_or_addr_policy
= NULL
;
3121 addr_policy_list_free(reachable_dir_addr_policy
);
3122 reachable_dir_addr_policy
= NULL
;
3123 addr_policy_list_free(socks_policy
);
3124 socks_policy
= NULL
;
3125 addr_policy_list_free(dir_policy
);
3127 addr_policy_list_free(metrics_policy
);
3128 metrics_policy
= NULL
;
3129 addr_policy_list_free(authdir_reject_policy
);
3130 authdir_reject_policy
= NULL
;
3131 addr_policy_list_free(authdir_invalid_policy
);
3132 authdir_invalid_policy
= NULL
;
3133 addr_policy_list_free(authdir_badexit_policy
);
3134 authdir_badexit_policy
= NULL
;
3135 addr_policy_list_free(authdir_middleonly_policy
);
3136 authdir_middleonly_policy
= NULL
;
3138 if (!HT_EMPTY(&policy_root
)) {
3139 policy_map_ent_t
**ent
;
3141 char buf
[POLICY_BUF_LEN
];
3143 log_warn(LD_MM
, "Still had %d address policies cached at shutdown.",
3144 (int)HT_SIZE(&policy_root
));
3146 /* Note the first 10 cached policies to try to figure out where they
3147 * might be coming from. */
3148 HT_FOREACH(ent
, policy_map
, &policy_root
) {
3151 if (policy_write_item(buf
, sizeof(buf
), (*ent
)->policy
, 0) >= 0)
3152 log_warn(LD_MM
," %d [%d]: %s", n
, (*ent
)->policy
->refcnt
, buf
);
3155 HT_CLEAR(policy_map
, &policy_root
);