1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Code to parse and use address policies and exit policies.
17 #include "routerparse.h"
21 /** Policy that addresses for incoming SOCKS connections must match. */
22 static smartlist_t
*socks_policy
= NULL
;
23 /** Policy that addresses for incoming directory connections must match. */
24 static smartlist_t
*dir_policy
= NULL
;
25 /** Policy that addresses for incoming router descriptors must match in order
26 * to be published by us. */
27 static smartlist_t
*authdir_reject_policy
= NULL
;
28 /** Policy that addresses for incoming router descriptors must match in order
29 * to be marked as valid in our networkstatus. */
30 static smartlist_t
*authdir_invalid_policy
= NULL
;
31 /** Policy that addresses for incoming router descriptors must <b>not</b>
32 * match in order to not be marked as BadDirectory. */
33 static smartlist_t
*authdir_baddir_policy
= NULL
;
34 /** Policy that addresses for incoming router descriptors must <b>not</b>
35 * match in order to not be marked as BadExit. */
36 static smartlist_t
*authdir_badexit_policy
= NULL
;
38 /** Parsed addr_policy_t describing which addresses we believe we can start
40 static smartlist_t
*reachable_or_addr_policy
= NULL
;
41 /** Parsed addr_policy_t describing which addresses we believe we can connect
42 * to directories at. */
43 static smartlist_t
*reachable_dir_addr_policy
= NULL
;
45 /** Element of an exit policy summary */
46 typedef struct policy_summary_item_t
{
47 uint16_t prt_min
; /**< Lowest port number to accept/reject. */
48 uint16_t prt_max
; /**< Highest port number to accept/reject. */
49 uint64_t reject_count
; /**< Number of IP-Addresses that are rejected to
51 unsigned int accepted
:1; /** Has this port already been accepted */
52 } policy_summary_item_t
;
54 /** Private networks. This list is used in two places, once to expand the
55 * "private" keyword when parsing our own exit policy, secondly to ignore
56 * just such networks when building exit policy summaries. It is important
57 * that all authorities agree on that list when creating summaries, so don't
58 * just change this without a proper migration plan and a proposal and stuff.
60 static const char *private_nets
[] = {
61 "0.0.0.0/8", "169.254.0.0/16",
62 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
64 "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
68 /** Replace all "private" entries in *<b>policy</b> with their expanded
71 policy_expand_private(smartlist_t
**policy
)
73 uint16_t port_min
, port_max
;
78 if (!*policy
) /*XXXX disallow NULL policies? */
81 tmp
= smartlist_new();
83 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
84 if (! p
->is_private
) {
85 smartlist_add(tmp
, p
);
88 for (i
= 0; private_nets
[i
]; ++i
) {
89 addr_policy_t newpolicy
;
90 memcpy(&newpolicy
, p
, sizeof(addr_policy_t
));
91 newpolicy
.is_private
= 0;
92 newpolicy
.is_canonical
= 0;
93 if (tor_addr_parse_mask_ports(private_nets
[i
], 0,
95 &newpolicy
.maskbits
, &port_min
, &port_max
)<0) {
98 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy
));
101 } SMARTLIST_FOREACH_END(p
);
103 smartlist_free(*policy
);
107 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
108 * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
109 * specific and one IPv6-specific. */
111 policy_expand_unspec(smartlist_t
**policy
)
117 tmp
= smartlist_new();
118 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
119 sa_family_t family
= tor_addr_family(&p
->addr
);
120 if (family
== AF_INET6
|| family
== AF_INET
|| p
->is_private
) {
121 smartlist_add(tmp
, p
);
122 } else if (family
== AF_UNSPEC
) {
123 addr_policy_t newpolicy_ipv4
;
124 addr_policy_t newpolicy_ipv6
;
125 memcpy(&newpolicy_ipv4
, p
, sizeof(addr_policy_t
));
126 memcpy(&newpolicy_ipv6
, p
, sizeof(addr_policy_t
));
127 newpolicy_ipv4
.is_canonical
= 0;
128 newpolicy_ipv6
.is_canonical
= 0;
129 if (p
->maskbits
!= 0) {
130 log_warn(LD_BUG
, "AF_UNSPEC policy with maskbits==%d", p
->maskbits
);
131 newpolicy_ipv4
.maskbits
= 0;
132 newpolicy_ipv6
.maskbits
= 0;
134 tor_addr_from_ipv4h(&newpolicy_ipv4
.addr
, 0);
135 tor_addr_from_ipv6_bytes(&newpolicy_ipv6
.addr
,
136 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
137 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv4
));
138 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv6
));
141 log_warn(LD_BUG
, "Funny-looking address policy with family %d", family
);
142 smartlist_add(tmp
, p
);
144 } SMARTLIST_FOREACH_END(p
);
146 smartlist_free(*policy
);
151 * Given a linked list of config lines containing "allow" and "deny"
152 * tokens, parse them and append the result to <b>dest</b>. Return -1
153 * if any tokens are malformed (and don't append any), else return 0.
155 * If <b>assume_action</b> is nonnegative, then insert its action
156 * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
160 parse_addr_policy(config_line_t
*cfg
, smartlist_t
**dest
,
164 smartlist_t
*entries
;
171 result
= smartlist_new();
172 entries
= smartlist_new();
173 for (; cfg
; cfg
= cfg
->next
) {
174 smartlist_split_string(entries
, cfg
->value
, ",",
175 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
176 SMARTLIST_FOREACH_BEGIN(entries
, const char *, ent
) {
177 log_debug(LD_CONFIG
,"Adding new entry '%s'",ent
);
178 item
= router_parse_addr_policy_item_from_string(ent
, assume_action
);
180 smartlist_add(result
, item
);
182 log_warn(LD_CONFIG
,"Malformed policy '%s'.", ent
);
185 } SMARTLIST_FOREACH_END(ent
);
186 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
187 smartlist_clear(entries
);
189 smartlist_free(entries
);
191 addr_policy_list_free(result
);
193 policy_expand_private(&result
);
194 policy_expand_unspec(&result
);
197 smartlist_add_all(*dest
, result
);
198 smartlist_free(result
);
207 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
208 * reachable_(or|dir)_addr_policy. The options should already have
209 * been validated by validate_addr_policies.
212 parse_reachable_addresses(void)
214 const or_options_t
*options
= get_options();
217 if (options
->ReachableDirAddresses
&&
218 options
->ReachableORAddresses
&&
219 options
->ReachableAddresses
) {
221 "Both ReachableDirAddresses and ReachableORAddresses are set. "
222 "ReachableAddresses setting will be ignored.");
224 addr_policy_list_free(reachable_or_addr_policy
);
225 reachable_or_addr_policy
= NULL
;
226 if (!options
->ReachableORAddresses
&& options
->ReachableAddresses
)
228 "Using ReachableAddresses as ReachableORAddresses.");
229 if (parse_addr_policy(options
->ReachableORAddresses
?
230 options
->ReachableORAddresses
:
231 options
->ReachableAddresses
,
232 &reachable_or_addr_policy
, ADDR_POLICY_ACCEPT
)) {
234 "Error parsing Reachable%sAddresses entry; ignoring.",
235 options
->ReachableORAddresses
? "OR" : "");
239 addr_policy_list_free(reachable_dir_addr_policy
);
240 reachable_dir_addr_policy
= NULL
;
241 if (!options
->ReachableDirAddresses
&& options
->ReachableAddresses
)
243 "Using ReachableAddresses as ReachableDirAddresses");
244 if (parse_addr_policy(options
->ReachableDirAddresses
?
245 options
->ReachableDirAddresses
:
246 options
->ReachableAddresses
,
247 &reachable_dir_addr_policy
, ADDR_POLICY_ACCEPT
)) {
248 if (options
->ReachableDirAddresses
)
250 "Error parsing ReachableDirAddresses entry; ignoring.");
256 /** Return true iff the firewall options might block any address:port
260 firewall_is_fascist_or(void)
262 return reachable_or_addr_policy
!= NULL
;
265 /** Return true iff <b>policy</b> (possibly NULL) will allow a
266 * connection to <b>addr</b>:<b>port</b>.
269 addr_policy_permits_tor_addr(const tor_addr_t
*addr
, uint16_t port
,
272 addr_policy_result_t p
;
273 p
= compare_tor_addr_to_addr_policy(addr
, port
, policy
);
275 case ADDR_POLICY_PROBABLY_ACCEPTED
:
276 case ADDR_POLICY_ACCEPTED
:
278 case ADDR_POLICY_PROBABLY_REJECTED
:
279 case ADDR_POLICY_REJECTED
:
282 log_warn(LD_BUG
, "Unexpected result: %d", (int)p
);
287 /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
288 * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
290 /* XXXX deprecate when possible. */
292 addr_policy_permits_address(uint32_t addr
, uint16_t port
,
296 tor_addr_from_ipv4h(&a
, addr
);
297 return addr_policy_permits_tor_addr(&a
, port
, policy
);
300 /** Return true iff we think our firewall will let us make an OR connection to
303 fascist_firewall_allows_address_or(const tor_addr_t
*addr
, uint16_t port
)
305 return addr_policy_permits_tor_addr(addr
, port
,
306 reachable_or_addr_policy
);
309 /** Return true iff we think our firewall will let us make an OR connection to
312 fascist_firewall_allows_or(const routerinfo_t
*ri
)
314 /* XXXX proposal 118 */
316 tor_addr_from_ipv4h(&addr
, ri
->addr
);
317 return fascist_firewall_allows_address_or(&addr
, ri
->or_port
);
320 /** Return true iff we think our firewall will let us make an OR connection to
323 fascist_firewall_allows_node(const node_t
*node
)
326 return fascist_firewall_allows_or(node
->ri
);
327 } else if (node
->rs
) {
329 tor_addr_from_ipv4h(&addr
, node
->rs
->addr
);
330 return fascist_firewall_allows_address_or(&addr
, node
->rs
->or_port
);
336 /** Return true iff we think our firewall will let us make a directory
337 * connection to addr:port. */
339 fascist_firewall_allows_address_dir(const tor_addr_t
*addr
, uint16_t port
)
341 return addr_policy_permits_tor_addr(addr
, port
,
342 reachable_dir_addr_policy
);
345 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
346 * based on <b>dir_policy</b>. Else return 0.
349 dir_policy_permits_address(const tor_addr_t
*addr
)
351 return addr_policy_permits_tor_addr(addr
, 1, dir_policy
);
354 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
355 * based on <b>socks_policy</b>. Else return 0.
358 socks_policy_permits_address(const tor_addr_t
*addr
)
360 return addr_policy_permits_tor_addr(addr
, 1, socks_policy
);
363 /** Return true iff the address <b>addr</b> is in a country listed in the
364 * case-insensitive list of country codes <b>cc_list</b>. */
366 addr_is_in_cc_list(uint32_t addr
, const smartlist_t
*cc_list
)
375 tor_addr_from_ipv4h(&tar
, addr
);
376 country
= geoip_get_country_by_addr(&tar
);
377 name
= geoip_get_country_name(country
);
378 return smartlist_contains_string_case(cc_list
, name
);
381 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
382 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
385 authdir_policy_permits_address(uint32_t addr
, uint16_t port
)
387 if (! addr_policy_permits_address(addr
, port
, authdir_reject_policy
))
389 return !addr_is_in_cc_list(addr
, get_options()->AuthDirRejectCCs
);
392 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
393 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
396 authdir_policy_valid_address(uint32_t addr
, uint16_t port
)
398 if (! addr_policy_permits_address(addr
, port
, authdir_invalid_policy
))
400 return !addr_is_in_cc_list(addr
, get_options()->AuthDirInvalidCCs
);
403 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad dir,
404 * based on <b>authdir_baddir_policy</b>. Else return 0.
407 authdir_policy_baddir_address(uint32_t addr
, uint16_t port
)
409 if (! addr_policy_permits_address(addr
, port
, authdir_baddir_policy
))
411 return addr_is_in_cc_list(addr
, get_options()->AuthDirBadDirCCs
);
414 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
415 * based on <b>authdir_badexit_policy</b>. Else return 0.
418 authdir_policy_badexit_address(uint32_t addr
, uint16_t port
)
420 if (! addr_policy_permits_address(addr
, port
, authdir_badexit_policy
))
422 return addr_is_in_cc_list(addr
, get_options()->AuthDirBadExitCCs
);
425 #define REJECT(arg) \
426 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
428 /** Config helper: If there's any problem with the policy configuration
429 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
430 * allocated description of the error. Else return 0. */
432 validate_addr_policies(const or_options_t
*options
, char **msg
)
434 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
435 * that the two can't go out of sync. */
437 smartlist_t
*addr_policy
=NULL
;
440 if (policies_parse_exit_policy(options
->ExitPolicy
, &addr_policy
,
442 options
->ExitPolicyRejectPrivate
, 0,
443 !options
->BridgeRelay
))
444 REJECT("Error in ExitPolicy entry.");
446 /* The rest of these calls *append* to addr_policy. So don't actually
447 * use the results for anything other than checking if they parse! */
448 if (parse_addr_policy(options
->DirPolicy
, &addr_policy
, -1))
449 REJECT("Error in DirPolicy entry.");
450 if (parse_addr_policy(options
->SocksPolicy
, &addr_policy
, -1))
451 REJECT("Error in SocksPolicy entry.");
452 if (parse_addr_policy(options
->AuthDirReject
, &addr_policy
,
454 REJECT("Error in AuthDirReject entry.");
455 if (parse_addr_policy(options
->AuthDirInvalid
, &addr_policy
,
457 REJECT("Error in AuthDirInvalid entry.");
458 if (parse_addr_policy(options
->AuthDirBadDir
, &addr_policy
,
460 REJECT("Error in AuthDirBadDir entry.");
461 if (parse_addr_policy(options
->AuthDirBadExit
, &addr_policy
,
463 REJECT("Error in AuthDirBadExit entry.");
465 if (parse_addr_policy(options
->ReachableAddresses
, &addr_policy
,
467 REJECT("Error in ReachableAddresses entry.");
468 if (parse_addr_policy(options
->ReachableORAddresses
, &addr_policy
,
470 REJECT("Error in ReachableORAddresses entry.");
471 if (parse_addr_policy(options
->ReachableDirAddresses
, &addr_policy
,
473 REJECT("Error in ReachableDirAddresses entry.");
476 addr_policy_list_free(addr_policy
);
477 return *msg
? -1 : 0;
481 /** Parse <b>string</b> in the same way that the exit policy
482 * is parsed, and put the processed version in *<b>policy</b>.
483 * Ignore port specifiers.
486 load_policy_from_option(config_line_t
*config
, const char *option_name
,
487 smartlist_t
**policy
,
491 int killed_any_ports
= 0;
492 addr_policy_list_free(*policy
);
494 r
= parse_addr_policy(config
, policy
, assume_action
);
499 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, n
) {
500 /* ports aren't used in these. */
501 if (n
->prt_min
> 1 || n
->prt_max
!= 65535) {
502 addr_policy_t newp
, *c
;
503 memcpy(&newp
, n
, sizeof(newp
));
505 newp
.prt_max
= 65535;
506 newp
.is_canonical
= 0;
507 c
= addr_policy_get_canonical_entry(&newp
);
508 SMARTLIST_REPLACE_CURRENT(*policy
, n
, c
);
510 killed_any_ports
= 1;
512 } SMARTLIST_FOREACH_END(n
);
514 if (killed_any_ports
) {
515 log_warn(LD_CONFIG
, "Ignoring ports in %s option.", option_name
);
520 /** Set all policies based on <b>options</b>, which should have been validated
521 * first by validate_addr_policies. */
523 policies_parse_from_options(const or_options_t
*options
)
526 if (load_policy_from_option(options
->SocksPolicy
, "SocksPolicy",
527 &socks_policy
, -1) < 0)
529 if (load_policy_from_option(options
->DirPolicy
, "DirPolicy",
530 &dir_policy
, -1) < 0)
532 if (load_policy_from_option(options
->AuthDirReject
, "AuthDirReject",
533 &authdir_reject_policy
, ADDR_POLICY_REJECT
) < 0)
535 if (load_policy_from_option(options
->AuthDirInvalid
, "AuthDirInvalid",
536 &authdir_invalid_policy
, ADDR_POLICY_REJECT
) < 0)
538 if (load_policy_from_option(options
->AuthDirBadDir
, "AuthDirBadDir",
539 &authdir_baddir_policy
, ADDR_POLICY_REJECT
) < 0)
541 if (load_policy_from_option(options
->AuthDirBadExit
, "AuthDirBadExit",
542 &authdir_badexit_policy
, ADDR_POLICY_REJECT
) < 0)
544 if (parse_reachable_addresses() < 0)
549 /** Compare two provided address policy items, and return -1, 0, or 1
550 * if the first is less than, equal to, or greater than the second. */
552 cmp_single_addr_policy(addr_policy_t
*a
, addr_policy_t
*b
)
555 if ((r
=((int)a
->policy_type
- (int)b
->policy_type
)))
557 if ((r
=((int)a
->is_private
- (int)b
->is_private
)))
559 if ((r
=tor_addr_compare(&a
->addr
, &b
->addr
, CMP_EXACT
)))
561 if ((r
=((int)a
->maskbits
- (int)b
->maskbits
)))
563 if ((r
=((int)a
->prt_min
- (int)b
->prt_min
)))
565 if ((r
=((int)a
->prt_max
- (int)b
->prt_max
)))
570 /** Like cmp_single_addr_policy() above, but looks at the
571 * whole set of policies in each case. */
573 cmp_addr_policies(smartlist_t
*a
, smartlist_t
*b
)
576 int len_a
= a
? smartlist_len(a
) : 0;
577 int len_b
= b
? smartlist_len(b
) : 0;
579 for (i
= 0; i
< len_a
&& i
< len_b
; ++i
) {
580 if ((r
= cmp_single_addr_policy(smartlist_get(a
, i
), smartlist_get(b
, i
))))
583 if (i
== len_a
&& i
== len_b
)
591 /** Node in hashtable used to store address policy entries. */
592 typedef struct policy_map_ent_t
{
593 HT_ENTRY(policy_map_ent_t
) node
;
594 addr_policy_t
*policy
;
597 /* DOCDOC policy_root */
598 static HT_HEAD(policy_map
, policy_map_ent_t
) policy_root
= HT_INITIALIZER();
600 /** Return true iff a and b are equal. */
602 policy_eq(policy_map_ent_t
*a
, policy_map_ent_t
*b
)
604 return cmp_single_addr_policy(a
->policy
, b
->policy
) == 0;
607 /** Return a hashcode for <b>ent</b> */
609 policy_hash(const policy_map_ent_t
*ent
)
611 const addr_policy_t
*a
= ent
->policy
;
613 memset(&aa
, 0, sizeof(aa
));
615 aa
.prt_min
= a
->prt_min
;
616 aa
.prt_max
= a
->prt_max
;
617 aa
.maskbits
= a
->maskbits
;
618 aa
.policy_type
= a
->policy_type
;
619 aa
.is_private
= a
->is_private
;
624 tor_addr_copy_tight(&aa
.addr
, &a
->addr
);
627 return (unsigned) siphash24g(&aa
, sizeof(aa
));
630 HT_PROTOTYPE(policy_map
, policy_map_ent_t
, node
, policy_hash
,
632 HT_GENERATE(policy_map
, policy_map_ent_t
, node
, policy_hash
,
633 policy_eq
, 0.6, malloc
, realloc
, free
)
635 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
636 * "canonical" copy of that addr_policy_t; the canonical copy is a single
637 * reference-counted object. */
639 addr_policy_get_canonical_entry(addr_policy_t
*e
)
641 policy_map_ent_t search
, *found
;
646 found
= HT_FIND(policy_map
, &policy_root
, &search
);
648 found
= tor_malloc_zero(sizeof(policy_map_ent_t
));
649 found
->policy
= tor_memdup(e
, sizeof(addr_policy_t
));
650 found
->policy
->is_canonical
= 1;
651 found
->policy
->refcnt
= 0;
652 HT_INSERT(policy_map
, &policy_root
, found
);
655 tor_assert(!cmp_single_addr_policy(found
->policy
, e
));
656 ++found
->policy
->refcnt
;
657 return found
->policy
;
660 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
661 * addr and port are both known. */
662 static addr_policy_result_t
663 compare_known_tor_addr_to_addr_policy(const tor_addr_t
*addr
, uint16_t port
,
664 const smartlist_t
*policy
)
666 /* We know the address and port, and we know the policy, so we can just
667 * compute an exact match. */
668 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
669 /* Address is known */
670 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
672 if (port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) {
673 /* Exact match for the policy */
674 return tmpe
->policy_type
== ADDR_POLICY_ACCEPT
?
675 ADDR_POLICY_ACCEPTED
: ADDR_POLICY_REJECTED
;
678 } SMARTLIST_FOREACH_END(tmpe
);
680 /* accept all by default. */
681 return ADDR_POLICY_ACCEPTED
;
684 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
685 * addr is known but port is not. */
686 static addr_policy_result_t
687 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t
*addr
,
688 const smartlist_t
*policy
)
690 /* We look to see if there's a definite match. If so, we return that
691 match's value, unless there's an intervening possible match that says
692 something different. */
693 int maybe_accept
= 0, maybe_reject
= 0;
695 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
696 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
698 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
>= 65535) {
699 /* Definitely matches, since it covers all ports. */
700 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
701 /* If we already hit a clause that might trigger a 'reject', than we
702 * can't be sure of this certain 'accept'.*/
703 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
704 ADDR_POLICY_ACCEPTED
;
706 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
707 ADDR_POLICY_REJECTED
;
711 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
717 } SMARTLIST_FOREACH_END(tmpe
);
719 /* accept all by default. */
720 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
723 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
724 * port is known but address is not. */
725 static addr_policy_result_t
726 compare_unknown_tor_addr_to_addr_policy(uint16_t port
,
727 const smartlist_t
*policy
)
729 /* We look to see if there's a definite match. If so, we return that
730 match's value, unless there's an intervening possible match that says
731 something different. */
732 int maybe_accept
= 0, maybe_reject
= 0;
734 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
735 if (tmpe
->prt_min
<= port
&& port
<= tmpe
->prt_max
) {
736 if (tmpe
->maskbits
== 0) {
737 /* Definitely matches, since it covers all addresses. */
738 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
739 /* If we already hit a clause that might trigger a 'reject', than we
740 * can't be sure of this certain 'accept'.*/
741 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
742 ADDR_POLICY_ACCEPTED
;
744 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
745 ADDR_POLICY_REJECTED
;
749 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
755 } SMARTLIST_FOREACH_END(tmpe
);
757 /* accept all by default. */
758 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
761 /** Decide whether a given addr:port is definitely accepted,
762 * definitely rejected, probably accepted, or probably rejected by a
763 * given policy. If <b>addr</b> is 0, we don't know the IP of the
764 * target address. If <b>port</b> is 0, we don't know the port of the
765 * target address. (At least one of <b>addr</b> and <b>port</b> must be
766 * provided. If you want to know whether a policy would definitely reject
767 * an unknown address:port, use policy_is_reject_star().)
769 * We could do better by assuming that some ranges never match typical
770 * addresses (127.0.0.1, and so on). But we'll try this for now.
773 compare_tor_addr_to_addr_policy(const tor_addr_t
*addr
, uint16_t port
,
774 const smartlist_t
*policy
)
777 /* no policy? accept all. */
778 return ADDR_POLICY_ACCEPTED
;
779 } else if (addr
== NULL
|| tor_addr_is_null(addr
)) {
781 log_info(LD_BUG
, "Rejecting null address with 0 port (family %d)",
782 addr
? tor_addr_family(addr
) : -1);
783 return ADDR_POLICY_REJECTED
;
785 return compare_unknown_tor_addr_to_addr_policy(port
, policy
);
786 } else if (port
== 0) {
787 return compare_known_tor_addr_to_addr_policy_noport(addr
, policy
);
789 return compare_known_tor_addr_to_addr_policy(addr
, port
, policy
);
793 /** Return true iff the address policy <b>a</b> covers every case that
794 * would be covered by <b>b</b>, so that a,b is redundant. */
796 addr_policy_covers(addr_policy_t
*a
, addr_policy_t
*b
)
798 if (tor_addr_family(&a
->addr
) != tor_addr_family(&b
->addr
)) {
799 /* You can't cover a different family. */
802 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
803 * to "accept *:80". */
804 if (a
->maskbits
> b
->maskbits
) {
805 /* a has more fixed bits than b; it can't possibly cover b. */
808 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, a
->maskbits
, CMP_EXACT
)) {
809 /* There's a fixed bit in a that's set differently in b. */
812 return (a
->prt_min
<= b
->prt_min
&& a
->prt_max
>= b
->prt_max
);
815 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
816 * that is, there exists an address/port that is covered by <b>a</b> that
817 * is also covered by <b>b</b>.
820 addr_policy_intersects(addr_policy_t
*a
, addr_policy_t
*b
)
823 /* All the bits we care about are those that are set in both
824 * netmasks. If they are equal in a and b's networkaddresses
825 * then the networks intersect. If there is a difference,
826 * then they do not. */
827 if (a
->maskbits
< b
->maskbits
)
828 minbits
= a
->maskbits
;
830 minbits
= b
->maskbits
;
831 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, minbits
, CMP_EXACT
))
833 if (a
->prt_max
< b
->prt_min
|| b
->prt_max
< a
->prt_min
)
838 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
841 append_exit_policy_string(smartlist_t
**policy
, const char *more
)
846 tmp
.value
= (char*) more
;
848 if (parse_addr_policy(&tmp
, policy
, -1)<0) {
849 log_warn(LD_BUG
, "Unable to parse internally generated policy %s",more
);
853 /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
855 addr_policy_append_reject_addr(smartlist_t
**dest
, const tor_addr_t
*addr
)
857 addr_policy_t p
, *add
;
858 memset(&p
, 0, sizeof(p
));
859 p
.policy_type
= ADDR_POLICY_REJECT
;
860 p
.maskbits
= tor_addr_family(addr
) == AF_INET6
? 128 : 32;
861 tor_addr_copy(&p
.addr
, addr
);
865 add
= addr_policy_get_canonical_entry(&p
);
867 *dest
= smartlist_new();
868 smartlist_add(*dest
, add
);
871 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
873 exit_policy_remove_redundancies(smartlist_t
*dest
)
875 addr_policy_t
*ap
, *tmp
;
878 /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
881 int kill_v4
=0, kill_v6
=0;
882 for (i
= 0; i
< smartlist_len(dest
); ++i
) {
884 ap
= smartlist_get(dest
, i
);
885 family
= tor_addr_family(&ap
->addr
);
886 if ((family
== AF_INET
&& kill_v4
) ||
887 (family
== AF_INET6
&& kill_v6
)) {
888 smartlist_del_keeporder(dest
, i
--);
889 addr_policy_free(ap
);
893 if (ap
->maskbits
== 0 && ap
->prt_min
<= 1 && ap
->prt_max
>= 65535) {
894 /* This is a catch-all line -- later lines are unreachable. */
895 if (family
== AF_INET
) {
897 } else if (family
== AF_INET6
) {
904 /* Step two: for every entry, see if there's a redundant entry
905 * later on, and remove it. */
906 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
907 ap
= smartlist_get(dest
, i
);
908 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
909 tmp
= smartlist_get(dest
, j
);
911 if (addr_policy_covers(ap
, tmp
)) {
912 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
913 policy_write_item(p1
, sizeof(p1
), tmp
, 0);
914 policy_write_item(p2
, sizeof(p2
), ap
, 0);
915 log_debug(LD_CONFIG
, "Removing exit policy %s (%d). It is made "
916 "redundant by %s (%d).", p1
, j
, p2
, i
);
917 smartlist_del_keeporder(dest
, j
--);
918 addr_policy_free(tmp
);
923 /* Step three: for every entry A, see if there's an entry B making this one
924 * redundant later on. This is the case if A and B are of the same type
925 * (accept/reject), A is a subset of B, and there is no other entry of
926 * different type in between those two that intersects with A.
928 * Anybody want to double-check the logic here? XXX
930 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
931 ap
= smartlist_get(dest
, i
);
932 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
933 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
935 tmp
= smartlist_get(dest
, j
);
936 if (ap
->policy_type
!= tmp
->policy_type
) {
937 if (addr_policy_intersects(ap
, tmp
))
939 } else { /* policy_types are equal. */
940 if (addr_policy_covers(tmp
, ap
)) {
941 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
942 policy_write_item(p1
, sizeof(p1
), ap
, 0);
943 policy_write_item(p2
, sizeof(p2
), tmp
, 0);
944 log_debug(LD_CONFIG
, "Removing exit policy %s. It is already "
945 "covered by %s.", p1
, p2
);
946 smartlist_del_keeporder(dest
, i
--);
947 addr_policy_free(ap
);
955 #define DEFAULT_EXIT_POLICY \
956 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
957 "reject *:563,reject *:1214,reject *:4661-4666," \
958 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
960 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
961 * cfg doesn't end in an absolute accept or reject and if
962 * <b>add_default_policy</b> is true, add the default exit
963 * policy afterwards. If <b>rejectprivate</b> is true, prepend
964 * "reject private:*" to the policy. Return -1 if we can't parse cfg,
967 * This function is used to parse the exit policy from our torrc. For
968 * the functions used to parse the exit policy from a router descriptor,
969 * see router_add_exit_policy.
972 policies_parse_exit_policy(config_line_t
*cfg
, smartlist_t
**dest
,
974 int rejectprivate
, uint32_t local_address
,
975 int add_default_policy
)
978 append_exit_policy_string(dest
, "reject *6:*");
981 append_exit_policy_string(dest
, "reject private:*");
983 char buf
[POLICY_BUF_LEN
];
984 tor_snprintf(buf
, sizeof(buf
), "reject %s:*", fmt_addr32(local_address
));
985 append_exit_policy_string(dest
, buf
);
988 if (parse_addr_policy(cfg
, dest
, -1))
990 if (add_default_policy
) {
991 append_exit_policy_string(dest
, DEFAULT_EXIT_POLICY
);
993 append_exit_policy_string(dest
, "reject *4:*");
994 append_exit_policy_string(dest
, "reject *6:*");
996 exit_policy_remove_redundancies(*dest
);
1001 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
1002 * *<b>dest</b> as needed. */
1004 policies_exit_policy_append_reject_star(smartlist_t
**dest
)
1006 append_exit_policy_string(dest
, "reject *4:*");
1007 append_exit_policy_string(dest
, "reject *6:*");
1010 /** Replace the exit policy of <b>node</b> with reject *:* */
1012 policies_set_node_exitpolicy_to_reject_all(node_t
*node
)
1014 node
->rejects_all
= 1;
1017 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
1018 * allows exiting to <b>port</b>. Otherwise, return 0. */
1020 exit_policy_is_general_exit_helper(smartlist_t
*policy
, int port
)
1022 uint32_t mask
, ip
, i
;
1023 /* Is this /8 rejected (1), or undecided (0)? */
1024 char subnet_status
[256];
1026 memset(subnet_status
, 0, sizeof(subnet_status
));
1027 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
1028 if (tor_addr_family(&p
->addr
) != AF_INET
)
1029 continue; /* IPv4 only for now */
1030 if (p
->prt_min
> port
|| p
->prt_max
< port
)
1031 continue; /* Doesn't cover our port. */
1033 tor_assert(p
->maskbits
<= 32);
1036 mask
= UINT32_MAX
<<(32-p
->maskbits
);
1037 ip
= tor_addr_to_ipv4h(&p
->addr
);
1039 /* Calculate the first and last subnet that this exit policy touches
1040 * and set it as loop boundaries. */
1041 for (i
= ((mask
& ip
)>>24); i
<= (~((mask
& ip
) ^ mask
)>>24); ++i
) {
1043 if (subnet_status
[i
] != 0)
1044 continue; /* We already reject some part of this /8 */
1045 tor_addr_from_ipv4h(&addr
, i
<<24);
1046 if (tor_addr_is_internal(&addr
, 0))
1047 continue; /* Local or non-routable addresses */
1048 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
1049 if (p
->maskbits
> 8)
1050 continue; /* Narrower than a /8. */
1051 /* We found an allowed subnet of at least size /8. Done
1054 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
1055 subnet_status
[i
] = 1;
1058 } SMARTLIST_FOREACH_END(p
);
1062 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
1063 * it allows exit to at least one /8 address space for at least
1064 * two of ports 80, 443, and 6667. */
1066 exit_policy_is_general_exit(smartlist_t
*policy
)
1068 static const int ports
[] = { 80, 443, 6667 };
1071 if (!policy
) /*XXXX disallow NULL policies? */
1074 for (i
= 0; i
< 3; ++i
) {
1075 n_allowed
+= exit_policy_is_general_exit_helper(policy
, ports
[i
]);
1077 return n_allowed
>= 2;
1080 /** Return false if <b>policy</b> might permit access to some addr:port;
1081 * otherwise if we are certain it rejects everything, return true. */
1083 policy_is_reject_star(const smartlist_t
*policy
, sa_family_t family
)
1085 if (!policy
) /*XXXX disallow NULL policies? */
1087 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
1088 if (p
->policy_type
== ADDR_POLICY_ACCEPT
&&
1089 (tor_addr_family(&p
->addr
) == family
||
1090 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
1092 } else if (p
->policy_type
== ADDR_POLICY_REJECT
&&
1093 p
->prt_min
<= 1 && p
->prt_max
== 65535 &&
1095 (tor_addr_family(&p
->addr
) == family
||
1096 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
1099 } SMARTLIST_FOREACH_END(p
);
1103 /** Write a single address policy to the buf_len byte buffer at buf. Return
1104 * the number of characters written, or -1 on failure. */
1106 policy_write_item(char *buf
, size_t buflen
, addr_policy_t
*policy
,
1107 int format_for_desc
)
1110 char addrbuf
[TOR_ADDR_BUF_LEN
];
1111 const char *addrpart
;
1113 const int is_accept
= policy
->policy_type
== ADDR_POLICY_ACCEPT
;
1114 const sa_family_t family
= tor_addr_family(&policy
->addr
);
1115 const int is_ip6
= (family
== AF_INET6
);
1117 tor_addr_to_str(addrbuf
, &policy
->addr
, sizeof(addrbuf
), 1);
1119 /* write accept/reject 1.2.3.4 */
1120 if (policy
->is_private
) {
1121 addrpart
= "private";
1122 } else if (policy
->maskbits
== 0) {
1123 if (format_for_desc
)
1125 else if (family
== AF_INET6
)
1127 else if (family
== AF_INET
)
1135 result
= tor_snprintf(buf
, buflen
, "%s%s %s",
1136 is_accept
? "accept" : "reject",
1137 (is_ip6
&&format_for_desc
)?"6":"",
1141 written
+= strlen(buf
);
1142 /* If the maskbits is 32 we don't need to give it. If the mask is 0,
1143 * we already wrote "*". */
1144 if (policy
->maskbits
< 32 && policy
->maskbits
> 0) {
1145 if (tor_snprintf(buf
+written
, buflen
-written
, "/%d", policy
->maskbits
)<0)
1147 written
+= strlen(buf
+written
);
1149 if (policy
->prt_min
<= 1 && policy
->prt_max
== 65535) {
1150 /* There is no port set; write ":*" */
1151 if (written
+4 > buflen
)
1153 strlcat(buf
+written
, ":*", buflen
-written
);
1155 } else if (policy
->prt_min
== policy
->prt_max
) {
1156 /* There is only one port; write ":80". */
1157 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d", policy
->prt_min
);
1162 /* There is a range of ports; write ":79-80". */
1163 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d-%d",
1164 policy
->prt_min
, policy
->prt_max
);
1169 if (written
< buflen
)
1170 buf
[written
] = '\0';
1174 return (int)written
;
1177 /** Create a new exit policy summary, initially only with a single
1178 * port 1-64k item */
1179 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
1180 * RB-tree if that turns out to matter. */
1181 static smartlist_t
*
1182 policy_summary_create(void)
1184 smartlist_t
*summary
;
1185 policy_summary_item_t
* item
;
1187 item
= tor_malloc_zero(sizeof(policy_summary_item_t
));
1189 item
->prt_max
= 65535;
1190 item
->reject_count
= 0;
1193 summary
= smartlist_new();
1194 smartlist_add(summary
, item
);
1199 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
1200 * The current item is changed to end at new-starts - 1, the new item
1201 * copies reject_count and accepted from the old item,
1202 * starts at new_starts and ends at the port where the original item
1205 static policy_summary_item_t
*
1206 policy_summary_item_split(policy_summary_item_t
* old
, uint16_t new_starts
)
1208 policy_summary_item_t
* new;
1210 new = tor_malloc_zero(sizeof(policy_summary_item_t
));
1211 new->prt_min
= new_starts
;
1212 new->prt_max
= old
->prt_max
;
1213 new->reject_count
= old
->reject_count
;
1214 new->accepted
= old
->accepted
;
1216 old
->prt_max
= new_starts
-1;
1218 tor_assert(old
->prt_min
<= old
->prt_max
);
1219 tor_assert(new->prt_min
<= new->prt_max
);
1223 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
1224 * my immortal soul, he can clean it up himself. */
1225 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
1227 #define REJECT_CUTOFF_COUNT (1<<25)
1228 /** Split an exit policy summary so that prt_min and prt_max
1229 * fall at exactly the start and end of an item respectively.
1232 policy_summary_split(smartlist_t
*summary
,
1233 uint16_t prt_min
, uint16_t prt_max
)
1239 while (AT(i
)->prt_max
< prt_min
)
1241 if (AT(i
)->prt_min
!= prt_min
) {
1242 policy_summary_item_t
* new_item
;
1243 new_item
= policy_summary_item_split(AT(i
), prt_min
);
1244 smartlist_insert(summary
, i
+1, new_item
);
1249 while (AT(i
)->prt_max
< prt_max
)
1251 if (AT(i
)->prt_max
!= prt_max
) {
1252 policy_summary_item_t
* new_item
;
1253 new_item
= policy_summary_item_split(AT(i
), prt_max
+1);
1254 smartlist_insert(summary
, i
+1, new_item
);
1257 return start_at_index
;
1260 /** Mark port ranges as accepted if they are below the reject_count */
1262 policy_summary_accept(smartlist_t
*summary
,
1263 uint16_t prt_min
, uint16_t prt_max
)
1265 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
1266 while (i
< smartlist_len(summary
) &&
1267 AT(i
)->prt_max
<= prt_max
) {
1268 if (!AT(i
)->accepted
&&
1269 AT(i
)->reject_count
<= REJECT_CUTOFF_COUNT
)
1270 AT(i
)->accepted
= 1;
1273 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
1276 /** Count the number of addresses in a network with prefixlen maskbits
1277 * against the given portrange. */
1279 policy_summary_reject(smartlist_t
*summary
,
1280 maskbits_t maskbits
,
1281 uint16_t prt_min
, uint16_t prt_max
)
1283 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
1284 /* XXX: ipv4 specific */
1285 uint64_t count
= (U64_LITERAL(1) << (32-maskbits
));
1286 while (i
< smartlist_len(summary
) &&
1287 AT(i
)->prt_max
<= prt_max
) {
1288 AT(i
)->reject_count
+= count
;
1291 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
1294 /** Add a single exit policy item to our summary:
1295 * If it is an accept ignore it unless it is for all IP addresses
1296 * ("*"), i.e. it's prefixlen/maskbits is 0, else call
1297 * policy_summary_accept().
1298 * If it's a reject ignore it if it is about one of the private
1299 * networks, else call policy_summary_reject().
1302 policy_summary_add_item(smartlist_t
*summary
, addr_policy_t
*p
)
1304 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
1305 if (p
->maskbits
== 0) {
1306 policy_summary_accept(summary
, p
->prt_min
, p
->prt_max
);
1308 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
1312 for (i
= 0; private_nets
[i
]; ++i
) {
1314 maskbits_t maskbits
;
1315 if (tor_addr_parse_mask_ports(private_nets
[i
], 0, &addr
,
1316 &maskbits
, NULL
, NULL
)<0) {
1319 if (tor_addr_compare(&p
->addr
, &addr
, CMP_EXACT
) == 0 &&
1320 p
->maskbits
== maskbits
) {
1327 policy_summary_reject(summary
, p
->maskbits
, p
->prt_min
, p
->prt_max
);
1333 /** Create a string representing a summary for an exit policy.
1334 * The summary will either be an "accept" plus a comma-separated list of port
1335 * ranges or a "reject" plus port-ranges, depending on which is shorter.
1337 * If no exits are allowed at all then NULL is returned, if no ports
1338 * are blocked instead of "reject " we return "accept 1-65535" (this
1339 * is an exception to the shorter-representation-wins rule).
1342 policy_summarize(smartlist_t
*policy
, sa_family_t family
)
1344 smartlist_t
*summary
= policy_summary_create();
1345 smartlist_t
*accepts
, *rejects
;
1346 int i
, last
, start_prt
;
1347 size_t accepts_len
, rejects_len
;
1348 char *accepts_str
= NULL
, *rejects_str
= NULL
, *shorter_str
, *result
;
1353 /* Create the summary list */
1354 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
1355 sa_family_t f
= tor_addr_family(&p
->addr
);
1356 if (f
!= AF_INET
&& f
!= AF_INET6
) {
1357 log_warn(LD_BUG
, "Weird family when summarizing address policy");
1361 /* XXXX-ipv6 More family work is needed */
1362 policy_summary_add_item(summary
, p
);
1363 } SMARTLIST_FOREACH_END(p
);
1365 /* Now create two lists of strings, one for accepted and one
1366 * for rejected ports. We take care to merge ranges so that
1367 * we avoid getting stuff like "1-4,5-9,10", instead we want
1372 accepts
= smartlist_new();
1373 rejects
= smartlist_new();
1375 last
= i
== smartlist_len(summary
)-1;
1377 AT(i
)->accepted
!= AT(i
+1)->accepted
) {
1378 char buf
[POLICY_BUF_LEN
];
1380 if (start_prt
== AT(i
)->prt_max
)
1381 tor_snprintf(buf
, sizeof(buf
), "%d", start_prt
);
1383 tor_snprintf(buf
, sizeof(buf
), "%d-%d", start_prt
, AT(i
)->prt_max
);
1385 if (AT(i
)->accepted
)
1386 smartlist_add(accepts
, tor_strdup(buf
));
1388 smartlist_add(rejects
, tor_strdup(buf
));
1393 start_prt
= AT(i
+1)->prt_min
;
1398 /* Figure out which of the two stringlists will be shorter and use
1399 * that to build the result
1401 if (smartlist_len(accepts
) == 0) { /* no exits at all */
1402 result
= tor_strdup("reject 1-65535");
1405 if (smartlist_len(rejects
) == 0) { /* no rejects at all */
1406 result
= tor_strdup("accept 1-65535");
1410 accepts_str
= smartlist_join_strings(accepts
, ",", 0, &accepts_len
);
1411 rejects_str
= smartlist_join_strings(rejects
, ",", 0, &rejects_len
);
1413 if (rejects_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("reject")-1 &&
1414 accepts_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("accept")-1) {
1416 shorter_str
= accepts_str
;
1419 c
= shorter_str
+ (MAX_EXITPOLICY_SUMMARY_LEN
-strlen(prefix
)-1);
1420 while (*c
!= ',' && c
>= shorter_str
)
1422 tor_assert(c
>= shorter_str
);
1423 tor_assert(*c
== ',');
1426 } else if (rejects_len
< accepts_len
) {
1427 shorter_str
= rejects_str
;
1430 shorter_str
= accepts_str
;
1434 tor_asprintf(&result
, "%s %s", prefix
, shorter_str
);
1438 SMARTLIST_FOREACH(summary
, policy_summary_item_t
*, s
, tor_free(s
));
1439 smartlist_free(summary
);
1441 tor_free(accepts_str
);
1442 SMARTLIST_FOREACH(accepts
, char *, s
, tor_free(s
));
1443 smartlist_free(accepts
);
1445 tor_free(rejects_str
);
1446 SMARTLIST_FOREACH(rejects
, char *, s
, tor_free(s
));
1447 smartlist_free(rejects
);
1452 /** Convert a summarized policy string into a short_policy_t. Return NULL
1453 * if the string is not well-formed. */
1455 parse_short_policy(const char *summary
)
1457 const char *orig_summary
= summary
;
1458 short_policy_t
*result
;
1461 short_policy_entry_t entries
[MAX_EXITPOLICY_SUMMARY_LEN
]; /* overkill */
1464 if (!strcmpstart(summary
, "accept ")) {
1466 summary
+= strlen("accept ");
1467 } else if (!strcmpstart(summary
, "reject ")) {
1469 summary
+= strlen("reject ");
1471 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Unrecognized policy summary keyword");
1476 for ( ; *summary
; summary
= next
) {
1477 const char *comma
= strchr(summary
, ',');
1483 next
= comma
? comma
+1 : strchr(summary
, '\0');
1484 len
= comma
? (size_t)(comma
- summary
) : strlen(summary
);
1486 if (n_entries
== MAX_EXITPOLICY_SUMMARY_LEN
) {
1487 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Impossibly long policy summary %s",
1488 escaped(orig_summary
));
1492 if (! TOR_ISDIGIT(*summary
) || len
> (sizeof(ent_buf
)-1)) {
1493 /* unrecognized entry format. skip it. */
1497 /* empty; skip it. */
1498 /* XXX This happens to be unreachable, since if len==0, then *summary is
1499 * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
1503 memcpy(ent_buf
, summary
, len
);
1504 ent_buf
[len
] = '\0';
1506 if (tor_sscanf(ent_buf
, "%u-%u%c", &low
, &high
, &dummy
) == 2) {
1507 if (low
<1 || low
>65535 || high
<1 || high
>65535 || low
>high
) {
1508 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1509 "Found bad entry in policy summary %s", escaped(orig_summary
));
1512 } else if (tor_sscanf(ent_buf
, "%u%c", &low
, &dummy
) == 1) {
1513 if (low
<1 || low
>65535) {
1514 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1515 "Found bad entry in policy summary %s", escaped(orig_summary
));
1520 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,"Found bad entry in policy summary %s",
1521 escaped(orig_summary
));
1525 entries
[n_entries
].min_port
= low
;
1526 entries
[n_entries
].max_port
= high
;
1530 if (n_entries
== 0) {
1531 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1532 "Found no port-range entries in summary %s", escaped(orig_summary
));
1537 size_t size
= STRUCT_OFFSET(short_policy_t
, entries
) +
1538 sizeof(short_policy_entry_t
)*(n_entries
);
1539 result
= tor_malloc_zero(size
);
1541 tor_assert( (char*)&result
->entries
[n_entries
-1] < ((char*)result
)+size
);
1544 result
->is_accept
= is_accept
;
1545 result
->n_entries
= n_entries
;
1546 memcpy(result
->entries
, entries
, sizeof(short_policy_entry_t
)*n_entries
);
1550 /** Write <b>policy</b> back out into a string. Used only for unit tests
1553 write_short_policy(const short_policy_t
*policy
)
1557 smartlist_t
*sl
= smartlist_new();
1559 smartlist_add_asprintf(sl
, "%s", policy
->is_accept
? "accept " : "reject ");
1561 for (i
=0; i
< policy
->n_entries
; i
++) {
1562 const short_policy_entry_t
*e
= &policy
->entries
[i
];
1563 if (e
->min_port
== e
->max_port
) {
1564 smartlist_add_asprintf(sl
, "%d", e
->min_port
);
1566 smartlist_add_asprintf(sl
, "%d-%d", e
->min_port
, e
->max_port
);
1568 if (i
< policy
->n_entries
-1)
1569 smartlist_add(sl
, tor_strdup(","));
1571 answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1572 SMARTLIST_FOREACH(sl
, char *, a
, tor_free(a
));
1577 /** Release all storage held in <b>policy</b>. */
1579 short_policy_free(short_policy_t
*policy
)
1584 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
1585 * or rejected by the summarized policy <b>policy</b>. Return values are as
1586 * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
1587 * functions, requires the <b>port</b> be specified. */
1588 addr_policy_result_t
1589 compare_tor_addr_to_short_policy(const tor_addr_t
*addr
, uint16_t port
,
1590 const short_policy_t
*policy
)
1593 int found_match
= 0;
1596 tor_assert(port
!= 0);
1598 if (addr
&& tor_addr_is_null(addr
))
1599 addr
= NULL
; /* Unspec means 'no address at all,' in this context. */
1601 if (addr
&& get_options()->ClientRejectInternalAddresses
&&
1602 (tor_addr_is_internal(addr
, 0) || tor_addr_is_loopback(addr
)))
1603 return ADDR_POLICY_REJECTED
;
1605 for (i
=0; i
< policy
->n_entries
; ++i
) {
1606 const short_policy_entry_t
*e
= &policy
->entries
[i
];
1607 if (e
->min_port
<= port
&& port
<= e
->max_port
) {
1614 accept
= policy
->is_accept
;
1616 accept
= ! policy
->is_accept
;
1618 /* ???? are these right? -NM */
1619 /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
1620 * case here, because it would cause clients to believe that the node
1621 * allows exit enclaving. Trying it anyway would open up a cool attack
1622 * where the node refuses due to exitpolicy, the client reacts in
1623 * surprise by rewriting the node's exitpolicy to reject *:*, and then
1624 * a bad guy targets users by causing them to attempt such connections
1625 * to 98% of the exits.
1627 * Once microdescriptors can handle addresses in special cases (e.g. if
1628 * we ever solve ticket 1774), we can provide certainty here. -RD */
1630 return ADDR_POLICY_PROBABLY_ACCEPTED
;
1632 return ADDR_POLICY_REJECTED
;
1635 /** Return true iff <b>policy</b> seems reject all ports */
1637 short_policy_is_reject_star(const short_policy_t
*policy
)
1639 /* This doesn't need to be as much on the lookout as policy_is_reject_star,
1640 * since policy summaries are from the consensus or from consensus
1644 /* Check for an exact match of "reject 1-65535". */
1645 return (policy
->is_accept
== 0 && policy
->n_entries
== 1 &&
1646 policy
->entries
[0].min_port
== 1 &&
1647 policy
->entries
[0].max_port
== 65535);
1650 /** Decide whether addr:port is probably or definitely accepted or rejected by
1651 * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
1652 * interpretation. */
1653 addr_policy_result_t
1654 compare_tor_addr_to_node_policy(const tor_addr_t
*addr
, uint16_t port
,
1657 if (node
->rejects_all
)
1658 return ADDR_POLICY_REJECTED
;
1660 if (addr
&& tor_addr_family(addr
) == AF_INET6
) {
1661 const short_policy_t
*p
= NULL
;
1663 p
= node
->ri
->ipv6_exit_policy
;
1665 p
= node
->md
->ipv6_exit_policy
;
1667 return compare_tor_addr_to_short_policy(addr
, port
, p
);
1669 return ADDR_POLICY_REJECTED
;
1673 return compare_tor_addr_to_addr_policy(addr
, port
, node
->ri
->exit_policy
);
1674 } else if (node
->md
) {
1675 if (node
->md
->exit_policy
== NULL
)
1676 return ADDR_POLICY_REJECTED
;
1678 return compare_tor_addr_to_short_policy(addr
, port
,
1679 node
->md
->exit_policy
);
1681 return ADDR_POLICY_PROBABLY_REJECTED
;
1685 /** Implementation for GETINFO control command: knows the answer for questions
1686 * about "exit-policy/..." */
1688 getinfo_helper_policies(control_connection_t
*conn
,
1689 const char *question
, char **answer
,
1690 const char **errmsg
)
1694 if (!strcmp(question
, "exit-policy/default")) {
1695 *answer
= tor_strdup(DEFAULT_EXIT_POLICY
);
1696 } else if (!strcmpstart(question
, "exit-policy/")) {
1697 const routerinfo_t
*me
= router_get_my_routerinfo();
1699 int include_ipv4
= 0;
1700 int include_ipv6
= 0;
1702 if (!strcmp(question
, "exit-policy/ipv4")) {
1704 } else if (!strcmp(question
, "exit-policy/ipv6")) {
1706 } else if (!strcmp(question
, "exit-policy/full")) {
1707 include_ipv4
= include_ipv6
= 1;
1709 return 0; /* No such key. */
1713 *errmsg
= "router_get_my_routerinfo returned NULL";
1717 *answer
= router_dump_exit_policy_to_string(me
,include_ipv4
,include_ipv6
);
1722 /** Release all storage held by <b>p</b>. */
1724 addr_policy_list_free(smartlist_t
*lst
)
1728 SMARTLIST_FOREACH(lst
, addr_policy_t
*, policy
, addr_policy_free(policy
));
1729 smartlist_free(lst
);
1732 /** Release all storage held by <b>p</b>. */
1734 addr_policy_free(addr_policy_t
*p
)
1739 if (--p
->refcnt
<= 0) {
1740 if (p
->is_canonical
) {
1741 policy_map_ent_t search
, *found
;
1743 found
= HT_REMOVE(policy_map
, &policy_root
, &search
);
1745 tor_assert(p
== found
->policy
);
1753 /** Release all storage held by policy variables. */
1755 policies_free_all(void)
1757 addr_policy_list_free(reachable_or_addr_policy
);
1758 reachable_or_addr_policy
= NULL
;
1759 addr_policy_list_free(reachable_dir_addr_policy
);
1760 reachable_dir_addr_policy
= NULL
;
1761 addr_policy_list_free(socks_policy
);
1762 socks_policy
= NULL
;
1763 addr_policy_list_free(dir_policy
);
1765 addr_policy_list_free(authdir_reject_policy
);
1766 authdir_reject_policy
= NULL
;
1767 addr_policy_list_free(authdir_invalid_policy
);
1768 authdir_invalid_policy
= NULL
;
1769 addr_policy_list_free(authdir_baddir_policy
);
1770 authdir_baddir_policy
= NULL
;
1771 addr_policy_list_free(authdir_badexit_policy
);
1772 authdir_badexit_policy
= NULL
;
1774 if (!HT_EMPTY(&policy_root
)) {
1775 policy_map_ent_t
**ent
;
1777 char buf
[POLICY_BUF_LEN
];
1779 log_warn(LD_MM
, "Still had %d address policies cached at shutdown.",
1780 (int)HT_SIZE(&policy_root
));
1782 /* Note the first 10 cached policies to try to figure out where they
1783 * might be coming from. */
1784 HT_FOREACH(ent
, policy_map
, &policy_root
) {
1787 if (policy_write_item(buf
, sizeof(buf
), (*ent
)->policy
, 0) >= 0)
1788 log_warn(LD_MM
," %d [%d]: %s", n
, (*ent
)->policy
->refcnt
, buf
);
1791 HT_CLEAR(policy_map
, &policy_root
);