1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2012, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Code to parse and use address policies and exit policies.
16 #include "routerparse.h"
20 /** Policy that addresses for incoming SOCKS connections must match. */
21 static smartlist_t
*socks_policy
= NULL
;
22 /** Policy that addresses for incoming directory connections must match. */
23 static smartlist_t
*dir_policy
= NULL
;
24 /** Policy that addresses for incoming router descriptors must match in order
25 * to be published by us. */
26 static smartlist_t
*authdir_reject_policy
= NULL
;
27 /** Policy that addresses for incoming router descriptors must match in order
28 * to be marked as valid in our networkstatus. */
29 static smartlist_t
*authdir_invalid_policy
= NULL
;
30 /** Policy that addresses for incoming router descriptors must <b>not</b>
31 * match in order to not be marked as BadDirectory. */
32 static smartlist_t
*authdir_baddir_policy
= NULL
;
33 /** Policy that addresses for incoming router descriptors must <b>not</b>
34 * match in order to not be marked as BadExit. */
35 static smartlist_t
*authdir_badexit_policy
= NULL
;
37 /** Parsed addr_policy_t describing which addresses we believe we can start
39 static smartlist_t
*reachable_or_addr_policy
= NULL
;
40 /** Parsed addr_policy_t describing which addresses we believe we can connect
41 * to directories at. */
42 static smartlist_t
*reachable_dir_addr_policy
= NULL
;
44 /** Element of an exit policy summary */
45 typedef struct policy_summary_item_t
{
46 uint16_t prt_min
; /**< Lowest port number to accept/reject. */
47 uint16_t prt_max
; /**< Highest port number to accept/reject. */
48 uint64_t reject_count
; /**< Number of IP-Addresses that are rejected to
50 unsigned int accepted
:1; /** Has this port already been accepted */
51 } policy_summary_item_t
;
53 /** Private networks. This list is used in two places, once to expand the
54 * "private" keyword when parsing our own exit policy, secondly to ignore
55 * just such networks when building exit policy summaries. It is important
56 * that all authorities agree on that list when creating summaries, so don't
57 * just change this without a proper migration plan and a proposal and stuff.
59 static const char *private_nets
[] = {
60 "0.0.0.0/8", "169.254.0.0/16",
61 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
63 "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
67 /** Replace all "private" entries in *<b>policy</b> with their expanded
70 policy_expand_private(smartlist_t
**policy
)
72 uint16_t port_min
, port_max
;
77 if (!*policy
) /*XXXX disallow NULL policies? */
80 tmp
= smartlist_new();
82 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
83 if (! p
->is_private
) {
84 smartlist_add(tmp
, p
);
87 for (i
= 0; private_nets
[i
]; ++i
) {
88 addr_policy_t newpolicy
;
89 memcpy(&newpolicy
, p
, sizeof(addr_policy_t
));
90 newpolicy
.is_private
= 0;
91 newpolicy
.is_canonical
= 0;
92 if (tor_addr_parse_mask_ports(private_nets
[i
], 0,
94 &newpolicy
.maskbits
, &port_min
, &port_max
)<0) {
97 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy
));
100 } SMARTLIST_FOREACH_END(p
);
102 smartlist_free(*policy
);
106 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
107 * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
108 * specific and one IPv6-specific. */
110 policy_expand_unspec(smartlist_t
**policy
)
116 tmp
= smartlist_new();
117 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, p
) {
118 sa_family_t family
= tor_addr_family(&p
->addr
);
119 if (family
== AF_INET6
|| family
== AF_INET
|| p
->is_private
) {
120 smartlist_add(tmp
, p
);
121 } else if (family
== AF_UNSPEC
) {
122 addr_policy_t newpolicy_ipv4
;
123 addr_policy_t newpolicy_ipv6
;
124 memcpy(&newpolicy_ipv4
, p
, sizeof(addr_policy_t
));
125 memcpy(&newpolicy_ipv6
, p
, sizeof(addr_policy_t
));
126 newpolicy_ipv4
.is_canonical
= 0;
127 newpolicy_ipv6
.is_canonical
= 0;
128 if (p
->maskbits
!= 0) {
129 log_warn(LD_BUG
, "AF_UNSPEC policy with maskbits==%d", p
->maskbits
);
130 newpolicy_ipv4
.maskbits
= 0;
131 newpolicy_ipv6
.maskbits
= 0;
133 tor_addr_from_ipv4h(&newpolicy_ipv4
.addr
, 0);
134 tor_addr_from_ipv6_bytes(&newpolicy_ipv6
.addr
,
135 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
136 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv4
));
137 smartlist_add(tmp
, addr_policy_get_canonical_entry(&newpolicy_ipv6
));
140 log_warn(LD_BUG
, "Funny-looking address policy with family %d", family
);
141 smartlist_add(tmp
, p
);
143 } SMARTLIST_FOREACH_END(p
);
145 smartlist_free(*policy
);
150 * Given a linked list of config lines containing "allow" and "deny"
151 * tokens, parse them and append the result to <b>dest</b>. Return -1
152 * if any tokens are malformed (and don't append any), else return 0.
154 * If <b>assume_action</b> is nonnegative, then insert its action
155 * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
159 parse_addr_policy(config_line_t
*cfg
, smartlist_t
**dest
,
163 smartlist_t
*entries
;
170 result
= smartlist_new();
171 entries
= smartlist_new();
172 for (; cfg
; cfg
= cfg
->next
) {
173 smartlist_split_string(entries
, cfg
->value
, ",",
174 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
175 SMARTLIST_FOREACH_BEGIN(entries
, const char *, ent
) {
176 log_debug(LD_CONFIG
,"Adding new entry '%s'",ent
);
177 item
= router_parse_addr_policy_item_from_string(ent
, assume_action
);
179 smartlist_add(result
, item
);
181 log_warn(LD_CONFIG
,"Malformed policy '%s'.", ent
);
184 } SMARTLIST_FOREACH_END(ent
);
185 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
186 smartlist_clear(entries
);
188 smartlist_free(entries
);
190 addr_policy_list_free(result
);
192 policy_expand_private(&result
);
193 policy_expand_unspec(&result
);
196 smartlist_add_all(*dest
, result
);
197 smartlist_free(result
);
206 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
207 * reachable_(or|dir)_addr_policy. The options should already have
208 * been validated by validate_addr_policies.
211 parse_reachable_addresses(void)
213 const or_options_t
*options
= get_options();
216 if (options
->ReachableDirAddresses
&&
217 options
->ReachableORAddresses
&&
218 options
->ReachableAddresses
) {
220 "Both ReachableDirAddresses and ReachableORAddresses are set. "
221 "ReachableAddresses setting will be ignored.");
223 addr_policy_list_free(reachable_or_addr_policy
);
224 reachable_or_addr_policy
= NULL
;
225 if (!options
->ReachableORAddresses
&& options
->ReachableAddresses
)
227 "Using ReachableAddresses as ReachableORAddresses.");
228 if (parse_addr_policy(options
->ReachableORAddresses
?
229 options
->ReachableORAddresses
:
230 options
->ReachableAddresses
,
231 &reachable_or_addr_policy
, ADDR_POLICY_ACCEPT
)) {
233 "Error parsing Reachable%sAddresses entry; ignoring.",
234 options
->ReachableORAddresses
? "OR" : "");
238 addr_policy_list_free(reachable_dir_addr_policy
);
239 reachable_dir_addr_policy
= NULL
;
240 if (!options
->ReachableDirAddresses
&& options
->ReachableAddresses
)
242 "Using ReachableAddresses as ReachableDirAddresses");
243 if (parse_addr_policy(options
->ReachableDirAddresses
?
244 options
->ReachableDirAddresses
:
245 options
->ReachableAddresses
,
246 &reachable_dir_addr_policy
, ADDR_POLICY_ACCEPT
)) {
247 if (options
->ReachableDirAddresses
)
249 "Error parsing ReachableDirAddresses entry; ignoring.");
255 /** Return true iff the firewall options might block any address:port
259 firewall_is_fascist_or(void)
261 return reachable_or_addr_policy
!= NULL
;
264 /** Return true iff <b>policy</b> (possibly NULL) will allow a
265 * connection to <b>addr</b>:<b>port</b>.
268 addr_policy_permits_tor_addr(const tor_addr_t
*addr
, uint16_t port
,
271 addr_policy_result_t p
;
272 p
= compare_tor_addr_to_addr_policy(addr
, port
, policy
);
274 case ADDR_POLICY_PROBABLY_ACCEPTED
:
275 case ADDR_POLICY_ACCEPTED
:
277 case ADDR_POLICY_PROBABLY_REJECTED
:
278 case ADDR_POLICY_REJECTED
:
281 log_warn(LD_BUG
, "Unexpected result: %d", (int)p
);
286 /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
287 * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
289 /* XXXX deprecate when possible. */
291 addr_policy_permits_address(uint32_t addr
, uint16_t port
,
295 tor_addr_from_ipv4h(&a
, addr
);
296 return addr_policy_permits_tor_addr(&a
, port
, policy
);
299 /** Return true iff we think our firewall will let us make an OR connection to
302 fascist_firewall_allows_address_or(const tor_addr_t
*addr
, uint16_t port
)
304 return addr_policy_permits_tor_addr(addr
, port
,
305 reachable_or_addr_policy
);
308 /** Return true iff we think our firewall will let us make an OR connection to
311 fascist_firewall_allows_or(const routerinfo_t
*ri
)
313 /* XXXX proposal 118 */
315 tor_addr_from_ipv4h(&addr
, ri
->addr
);
316 return fascist_firewall_allows_address_or(&addr
, ri
->or_port
);
319 /** Return true iff we think our firewall will let us make an OR connection to
322 fascist_firewall_allows_node(const node_t
*node
)
325 return fascist_firewall_allows_or(node
->ri
);
326 } else if (node
->rs
) {
328 tor_addr_from_ipv4h(&addr
, node
->rs
->addr
);
329 return fascist_firewall_allows_address_or(&addr
, node
->rs
->or_port
);
335 /** Return true iff we think our firewall will let us make a directory
336 * connection to addr:port. */
338 fascist_firewall_allows_address_dir(const tor_addr_t
*addr
, uint16_t port
)
340 return addr_policy_permits_tor_addr(addr
, port
,
341 reachable_dir_addr_policy
);
344 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
345 * based on <b>dir_policy</b>. Else return 0.
348 dir_policy_permits_address(const tor_addr_t
*addr
)
350 return addr_policy_permits_tor_addr(addr
, 1, dir_policy
);
353 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
354 * based on <b>socks_policy</b>. Else return 0.
357 socks_policy_permits_address(const tor_addr_t
*addr
)
359 return addr_policy_permits_tor_addr(addr
, 1, socks_policy
);
362 /** Return true iff the address <b>addr</b> is in a country listed in the
363 * case-insensitive list of country codes <b>cc_list</b>. */
365 addr_is_in_cc_list(uint32_t addr
, const smartlist_t
*cc_list
)
374 tor_addr_from_ipv4h(&tar
, addr
);
375 country
= geoip_get_country_by_addr(&tar
);
376 name
= geoip_get_country_name(country
);
377 return smartlist_string_isin_case(cc_list
, name
);
380 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
381 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
384 authdir_policy_permits_address(uint32_t addr
, uint16_t port
)
386 if (! addr_policy_permits_address(addr
, port
, authdir_reject_policy
))
388 return !addr_is_in_cc_list(addr
, get_options()->AuthDirRejectCCs
);
391 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
392 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
395 authdir_policy_valid_address(uint32_t addr
, uint16_t port
)
397 if (! addr_policy_permits_address(addr
, port
, authdir_invalid_policy
))
399 return !addr_is_in_cc_list(addr
, get_options()->AuthDirInvalidCCs
);
402 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad dir,
403 * based on <b>authdir_baddir_policy</b>. Else return 0.
406 authdir_policy_baddir_address(uint32_t addr
, uint16_t port
)
408 if (! addr_policy_permits_address(addr
, port
, authdir_baddir_policy
))
410 return addr_is_in_cc_list(addr
, get_options()->AuthDirBadDirCCs
);
413 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
414 * based on <b>authdir_badexit_policy</b>. Else return 0.
417 authdir_policy_badexit_address(uint32_t addr
, uint16_t port
)
419 if (! addr_policy_permits_address(addr
, port
, authdir_badexit_policy
))
421 return addr_is_in_cc_list(addr
, get_options()->AuthDirBadExitCCs
);
424 #define REJECT(arg) \
425 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
427 /** Config helper: If there's any problem with the policy configuration
428 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
429 * allocated description of the error. Else return 0. */
431 validate_addr_policies(const or_options_t
*options
, char **msg
)
433 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
434 * that the two can't go out of sync. */
436 smartlist_t
*addr_policy
=NULL
;
439 if (policies_parse_exit_policy(options
->ExitPolicy
, &addr_policy
,
441 options
->ExitPolicyRejectPrivate
, NULL
,
442 !options
->BridgeRelay
))
443 REJECT("Error in ExitPolicy entry.");
445 /* The rest of these calls *append* to addr_policy. So don't actually
446 * use the results for anything other than checking if they parse! */
447 if (parse_addr_policy(options
->DirPolicy
, &addr_policy
, -1))
448 REJECT("Error in DirPolicy entry.");
449 if (parse_addr_policy(options
->SocksPolicy
, &addr_policy
, -1))
450 REJECT("Error in SocksPolicy entry.");
451 if (parse_addr_policy(options
->AuthDirReject
, &addr_policy
,
453 REJECT("Error in AuthDirReject entry.");
454 if (parse_addr_policy(options
->AuthDirInvalid
, &addr_policy
,
456 REJECT("Error in AuthDirInvalid entry.");
457 if (parse_addr_policy(options
->AuthDirBadDir
, &addr_policy
,
459 REJECT("Error in AuthDirBadDir entry.");
460 if (parse_addr_policy(options
->AuthDirBadExit
, &addr_policy
,
462 REJECT("Error in AuthDirBadExit entry.");
464 if (parse_addr_policy(options
->ReachableAddresses
, &addr_policy
,
466 REJECT("Error in ReachableAddresses entry.");
467 if (parse_addr_policy(options
->ReachableORAddresses
, &addr_policy
,
469 REJECT("Error in ReachableORAddresses entry.");
470 if (parse_addr_policy(options
->ReachableDirAddresses
, &addr_policy
,
472 REJECT("Error in ReachableDirAddresses entry.");
475 addr_policy_list_free(addr_policy
);
476 return *msg
? -1 : 0;
480 /** Parse <b>string</b> in the same way that the exit policy
481 * is parsed, and put the processed version in *<b>policy</b>.
482 * Ignore port specifiers.
485 load_policy_from_option(config_line_t
*config
, smartlist_t
**policy
,
489 addr_policy_list_free(*policy
);
491 r
= parse_addr_policy(config
, policy
, assume_action
);
496 SMARTLIST_FOREACH_BEGIN(*policy
, addr_policy_t
*, n
) {
497 /* ports aren't used in these. */
498 if (n
->prt_min
> 1 || n
->prt_max
!= 65535) {
499 addr_policy_t newp
, *c
;
500 memcpy(&newp
, n
, sizeof(newp
));
502 newp
.prt_max
= 65535;
503 newp
.is_canonical
= 0;
504 c
= addr_policy_get_canonical_entry(&newp
);
505 SMARTLIST_REPLACE_CURRENT(*policy
, n
, c
);
508 } SMARTLIST_FOREACH_END(n
);
513 /** Set all policies based on <b>options</b>, which should have been validated
514 * first by validate_addr_policies. */
516 policies_parse_from_options(const or_options_t
*options
)
519 if (load_policy_from_option(options
->SocksPolicy
, &socks_policy
, -1) < 0)
521 if (load_policy_from_option(options
->DirPolicy
, &dir_policy
, -1) < 0)
523 if (load_policy_from_option(options
->AuthDirReject
,
524 &authdir_reject_policy
, ADDR_POLICY_REJECT
) < 0)
526 if (load_policy_from_option(options
->AuthDirInvalid
,
527 &authdir_invalid_policy
, ADDR_POLICY_REJECT
) < 0)
529 if (load_policy_from_option(options
->AuthDirBadDir
,
530 &authdir_baddir_policy
, ADDR_POLICY_REJECT
) < 0)
532 if (load_policy_from_option(options
->AuthDirBadExit
,
533 &authdir_badexit_policy
, ADDR_POLICY_REJECT
) < 0)
535 if (parse_reachable_addresses() < 0)
540 /** Compare two provided address policy items, and return -1, 0, or 1
541 * if the first is less than, equal to, or greater than the second. */
543 cmp_single_addr_policy(addr_policy_t
*a
, addr_policy_t
*b
)
546 if ((r
=((int)a
->policy_type
- (int)b
->policy_type
)))
548 if ((r
=((int)a
->is_private
- (int)b
->is_private
)))
550 if ((r
=tor_addr_compare(&a
->addr
, &b
->addr
, CMP_EXACT
)))
552 if ((r
=((int)a
->maskbits
- (int)b
->maskbits
)))
554 if ((r
=((int)a
->prt_min
- (int)b
->prt_min
)))
556 if ((r
=((int)a
->prt_max
- (int)b
->prt_max
)))
561 /** Like cmp_single_addr_policy() above, but looks at the
562 * whole set of policies in each case. */
564 cmp_addr_policies(smartlist_t
*a
, smartlist_t
*b
)
567 int len_a
= a
? smartlist_len(a
) : 0;
568 int len_b
= b
? smartlist_len(b
) : 0;
570 for (i
= 0; i
< len_a
&& i
< len_b
; ++i
) {
571 if ((r
= cmp_single_addr_policy(smartlist_get(a
, i
), smartlist_get(b
, i
))))
574 if (i
== len_a
&& i
== len_b
)
582 /** Node in hashtable used to store address policy entries. */
583 typedef struct policy_map_ent_t
{
584 HT_ENTRY(policy_map_ent_t
) node
;
585 addr_policy_t
*policy
;
588 /* DOCDOC policy_root */
589 static HT_HEAD(policy_map
, policy_map_ent_t
) policy_root
= HT_INITIALIZER();
591 /** Return true iff a and b are equal. */
593 policy_eq(policy_map_ent_t
*a
, policy_map_ent_t
*b
)
595 return cmp_single_addr_policy(a
->policy
, b
->policy
) == 0;
598 /** Return a hashcode for <b>ent</b> */
600 policy_hash(policy_map_ent_t
*ent
)
602 addr_policy_t
*a
= ent
->policy
;
607 r
= tor_addr_hash(&a
->addr
);
608 r
+= a
->prt_min
<< 8;
609 r
+= a
->prt_max
<< 16;
611 if (a
->policy_type
== ADDR_POLICY_REJECT
)
617 HT_PROTOTYPE(policy_map
, policy_map_ent_t
, node
, policy_hash
,
619 HT_GENERATE(policy_map
, policy_map_ent_t
, node
, policy_hash
,
620 policy_eq
, 0.6, malloc
, realloc
, free
)
622 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
623 * "canonical" copy of that addr_policy_t; the canonical copy is a single
624 * reference-counted object. */
626 addr_policy_get_canonical_entry(addr_policy_t
*e
)
628 policy_map_ent_t search
, *found
;
633 found
= HT_FIND(policy_map
, &policy_root
, &search
);
635 found
= tor_malloc_zero(sizeof(policy_map_ent_t
));
636 found
->policy
= tor_memdup(e
, sizeof(addr_policy_t
));
637 found
->policy
->is_canonical
= 1;
638 found
->policy
->refcnt
= 0;
639 HT_INSERT(policy_map
, &policy_root
, found
);
642 tor_assert(!cmp_single_addr_policy(found
->policy
, e
));
643 ++found
->policy
->refcnt
;
644 return found
->policy
;
647 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
648 * addr and port are both known. */
649 static addr_policy_result_t
650 compare_known_tor_addr_to_addr_policy(const tor_addr_t
*addr
, uint16_t port
,
651 const smartlist_t
*policy
)
653 /* We know the address and port, and we know the policy, so we can just
654 * compute an exact match. */
655 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
656 /* Address is known */
657 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
659 if (port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) {
660 /* Exact match for the policy */
661 return tmpe
->policy_type
== ADDR_POLICY_ACCEPT
?
662 ADDR_POLICY_ACCEPTED
: ADDR_POLICY_REJECTED
;
665 } SMARTLIST_FOREACH_END(tmpe
);
667 /* accept all by default. */
668 return ADDR_POLICY_ACCEPTED
;
671 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
672 * addr is known but port is not. */
673 static addr_policy_result_t
674 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t
*addr
,
675 const smartlist_t
*policy
)
677 /* We look to see if there's a definite match. If so, we return that
678 match's value, unless there's an intervening possible match that says
679 something different. */
680 int maybe_accept
= 0, maybe_reject
= 0;
682 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
683 if (!tor_addr_compare_masked(addr
, &tmpe
->addr
, tmpe
->maskbits
,
685 if (tmpe
->prt_min
<= 1 && tmpe
->prt_max
>= 65535) {
686 /* Definitely matches, since it covers all ports. */
687 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
688 /* If we already hit a clause that might trigger a 'reject', than we
689 * can't be sure of this certain 'accept'.*/
690 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
691 ADDR_POLICY_ACCEPTED
;
693 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
694 ADDR_POLICY_REJECTED
;
698 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
704 } SMARTLIST_FOREACH_END(tmpe
);
706 /* accept all by default. */
707 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
710 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
711 * port is known but address is not. */
712 static addr_policy_result_t
713 compare_unknown_tor_addr_to_addr_policy(uint16_t port
,
714 const smartlist_t
*policy
)
716 /* We look to see if there's a definite match. If so, we return that
717 match's value, unless there's an intervening possible match that says
718 something different. */
719 int maybe_accept
= 0, maybe_reject
= 0;
721 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, tmpe
) {
722 if (tmpe
->prt_min
<= port
&& port
<= tmpe
->prt_max
) {
723 if (tmpe
->maskbits
== 0) {
724 /* Definitely matches, since it covers all addresses. */
725 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
726 /* If we already hit a clause that might trigger a 'reject', than we
727 * can't be sure of this certain 'accept'.*/
728 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
729 ADDR_POLICY_ACCEPTED
;
731 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
732 ADDR_POLICY_REJECTED
;
736 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
742 } SMARTLIST_FOREACH_END(tmpe
);
744 /* accept all by default. */
745 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
748 /** Decide whether a given addr:port is definitely accepted,
749 * definitely rejected, probably accepted, or probably rejected by a
750 * given policy. If <b>addr</b> is 0, we don't know the IP of the
751 * target address. If <b>port</b> is 0, we don't know the port of the
752 * target address. (At least one of <b>addr</b> and <b>port</b> must be
753 * provided. If you want to know whether a policy would definitely reject
754 * an unknown address:port, use policy_is_reject_star().)
756 * We could do better by assuming that some ranges never match typical
757 * addresses (127.0.0.1, and so on). But we'll try this for now.
760 compare_tor_addr_to_addr_policy(const tor_addr_t
*addr
, uint16_t port
,
761 const smartlist_t
*policy
)
764 /* no policy? accept all. */
765 return ADDR_POLICY_ACCEPTED
;
766 } else if (addr
== NULL
|| tor_addr_is_null(addr
)) {
768 log_info(LD_BUG
, "Rejecting null address with 0 port (family %d)",
769 addr
? tor_addr_family(addr
) : -1);
770 return ADDR_POLICY_REJECTED
;
772 return compare_unknown_tor_addr_to_addr_policy(port
, policy
);
773 } else if (port
== 0) {
774 return compare_known_tor_addr_to_addr_policy_noport(addr
, policy
);
776 return compare_known_tor_addr_to_addr_policy(addr
, port
, policy
);
780 /** Return true iff the address policy <b>a</b> covers every case that
781 * would be covered by <b>b</b>, so that a,b is redundant. */
783 addr_policy_covers(addr_policy_t
*a
, addr_policy_t
*b
)
785 if (tor_addr_family(&a
->addr
) != tor_addr_family(&b
->addr
)) {
786 /* You can't cover a different family. */
789 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
790 * to "accept *:80". */
791 if (a
->maskbits
> b
->maskbits
) {
792 /* a has more fixed bits than b; it can't possibly cover b. */
795 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, a
->maskbits
, CMP_EXACT
)) {
796 /* There's a fixed bit in a that's set differently in b. */
799 return (a
->prt_min
<= b
->prt_min
&& a
->prt_max
>= b
->prt_max
);
802 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
803 * that is, there exists an address/port that is covered by <b>a</b> that
804 * is also covered by <b>b</b>.
807 addr_policy_intersects(addr_policy_t
*a
, addr_policy_t
*b
)
810 /* All the bits we care about are those that are set in both
811 * netmasks. If they are equal in a and b's networkaddresses
812 * then the networks intersect. If there is a difference,
813 * then they do not. */
814 if (a
->maskbits
< b
->maskbits
)
815 minbits
= a
->maskbits
;
817 minbits
= b
->maskbits
;
818 if (tor_addr_compare_masked(&a
->addr
, &b
->addr
, minbits
, CMP_EXACT
))
820 if (a
->prt_max
< b
->prt_min
|| b
->prt_max
< a
->prt_min
)
825 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
828 append_exit_policy_string(smartlist_t
**policy
, const char *more
)
833 tmp
.value
= (char*) more
;
835 if (parse_addr_policy(&tmp
, policy
, -1)<0) {
836 log_warn(LD_BUG
, "Unable to parse internally generated policy %s",more
);
840 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
842 exit_policy_remove_redundancies(smartlist_t
*dest
)
844 addr_policy_t
*ap
, *tmp
;
847 /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
850 int kill_v4
=0, kill_v6
=0;
851 for (i
= 0; i
< smartlist_len(dest
); ++i
) {
853 ap
= smartlist_get(dest
, i
);
854 family
= tor_addr_family(&ap
->addr
);
855 if ((family
== AF_INET
&& kill_v4
) ||
856 (family
== AF_INET6
&& kill_v6
)) {
857 smartlist_del_keeporder(dest
, i
--);
858 addr_policy_free(ap
);
862 if (ap
->maskbits
== 0 && ap
->prt_min
<= 1 && ap
->prt_max
>= 65535) {
863 /* This is a catch-all line -- later lines are unreachable. */
864 if (family
== AF_INET
) {
866 } else if (family
== AF_INET6
) {
873 /* Step two: for every entry, see if there's a redundant entry
874 * later on, and remove it. */
875 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
876 ap
= smartlist_get(dest
, i
);
877 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
878 tmp
= smartlist_get(dest
, j
);
880 if (addr_policy_covers(ap
, tmp
)) {
881 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
882 policy_write_item(p1
, sizeof(p1
), tmp
, 0);
883 policy_write_item(p2
, sizeof(p2
), ap
, 0);
884 log(LOG_DEBUG
, LD_CONFIG
, "Removing exit policy %s (%d). It is made "
885 "redundant by %s (%d).", p1
, j
, p2
, i
);
886 smartlist_del_keeporder(dest
, j
--);
887 addr_policy_free(tmp
);
892 /* Step three: for every entry A, see if there's an entry B making this one
893 * redundant later on. This is the case if A and B are of the same type
894 * (accept/reject), A is a subset of B, and there is no other entry of
895 * different type in between those two that intersects with A.
897 * Anybody want to double-check the logic here? XXX
899 for (i
= 0; i
< smartlist_len(dest
)-1; ++i
) {
900 ap
= smartlist_get(dest
, i
);
901 for (j
= i
+1; j
< smartlist_len(dest
); ++j
) {
902 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
904 tmp
= smartlist_get(dest
, j
);
905 if (ap
->policy_type
!= tmp
->policy_type
) {
906 if (addr_policy_intersects(ap
, tmp
))
908 } else { /* policy_types are equal. */
909 if (addr_policy_covers(tmp
, ap
)) {
910 char p1
[POLICY_BUF_LEN
], p2
[POLICY_BUF_LEN
];
911 policy_write_item(p1
, sizeof(p1
), ap
, 0);
912 policy_write_item(p2
, sizeof(p2
), tmp
, 0);
913 log(LOG_DEBUG
, LD_CONFIG
, "Removing exit policy %s. It is already "
914 "covered by %s.", p1
, p2
);
915 smartlist_del_keeporder(dest
, i
--);
916 addr_policy_free(ap
);
924 #define DEFAULT_EXIT_POLICY \
925 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
926 "reject *:563,reject *:1214,reject *:4661-4666," \
927 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
929 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
930 * cfg doesn't end in an absolute accept or reject and if
931 * <b>add_default_policy</b> is true, add the default exit
932 * policy afterwards. If <b>rejectprivate</b> is true, prepend
933 * "reject private:*" to the policy. Return -1 if we can't parse cfg,
936 * This function is used to parse the exit policy from our torrc. For
937 * the functions used to parse the exit policy from a router descriptor,
938 * see router_add_exit_policy.
941 policies_parse_exit_policy(config_line_t
*cfg
, smartlist_t
**dest
,
943 int rejectprivate
, const char *local_address
,
944 int add_default_policy
)
947 append_exit_policy_string(dest
, "reject *6:*");
950 append_exit_policy_string(dest
, "reject private:*");
952 char buf
[POLICY_BUF_LEN
];
953 tor_snprintf(buf
, sizeof(buf
), "reject %s:*", local_address
);
954 append_exit_policy_string(dest
, buf
);
957 if (parse_addr_policy(cfg
, dest
, -1))
959 if (add_default_policy
) {
960 append_exit_policy_string(dest
, DEFAULT_EXIT_POLICY
);
962 append_exit_policy_string(dest
, "reject *4:*");
963 append_exit_policy_string(dest
, "reject *6:*");
965 exit_policy_remove_redundancies(*dest
);
970 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
971 * *<b>dest</b> as needed. */
973 policies_exit_policy_append_reject_star(smartlist_t
**dest
)
975 append_exit_policy_string(dest
, "reject *4:*");
976 append_exit_policy_string(dest
, "reject *6:*");
979 /** Replace the exit policy of <b>node</b> with reject *:* */
981 policies_set_node_exitpolicy_to_reject_all(node_t
*node
)
983 node
->rejects_all
= 1;
986 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
987 * allows exiting to <b>port</b>. Otherwise, return 0. */
989 exit_policy_is_general_exit_helper(smartlist_t
*policy
, int port
)
991 uint32_t mask
, ip
, i
;
992 /* Is this /8 rejected (1), or undecided (0)? */
993 char subnet_status
[256];
995 memset(subnet_status
, 0, sizeof(subnet_status
));
996 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
997 if (tor_addr_family(&p
->addr
) != AF_INET
)
998 continue; /* IPv4 only for now */
999 if (p
->prt_min
> port
|| p
->prt_max
< port
)
1000 continue; /* Doesn't cover our port. */
1002 tor_assert(p
->maskbits
<= 32);
1005 mask
= UINT32_MAX
<<(32-p
->maskbits
);
1006 ip
= tor_addr_to_ipv4h(&p
->addr
);
1008 /* Calculate the first and last subnet that this exit policy touches
1009 * and set it as loop boundaries. */
1010 for (i
= ((mask
& ip
)>>24); i
<= (~((mask
& ip
) ^ mask
)>>24); ++i
) {
1012 if (subnet_status
[i
] != 0)
1013 continue; /* We already reject some part of this /8 */
1014 tor_addr_from_ipv4h(&addr
, i
<<24);
1015 if (tor_addr_is_internal(&addr
, 0))
1016 continue; /* Local or non-routable addresses */
1017 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
1018 if (p
->maskbits
> 8)
1019 continue; /* Narrower than a /8. */
1020 /* We found an allowed subnet of at least size /8. Done
1023 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
1024 subnet_status
[i
] = 1;
1027 } SMARTLIST_FOREACH_END(p
);
1031 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
1032 * it allows exit to at least one /8 address space for at least
1033 * two of ports 80, 443, and 6667. */
1035 exit_policy_is_general_exit(smartlist_t
*policy
)
1037 static const int ports
[] = { 80, 443, 6667 };
1040 if (!policy
) /*XXXX disallow NULL policies? */
1043 for (i
= 0; i
< 3; ++i
) {
1044 n_allowed
+= exit_policy_is_general_exit_helper(policy
, ports
[i
]);
1046 return n_allowed
>= 2;
1049 /** Return false if <b>policy</b> might permit access to some addr:port;
1050 * otherwise if we are certain it rejects everything, return true. */
1052 policy_is_reject_star(const smartlist_t
*policy
, sa_family_t family
)
1054 if (!policy
) /*XXXX disallow NULL policies? */
1056 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
1057 if (p
->policy_type
== ADDR_POLICY_ACCEPT
&&
1058 (tor_addr_family(&p
->addr
) == family
||
1059 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
1061 } else if (p
->policy_type
== ADDR_POLICY_REJECT
&&
1062 p
->prt_min
<= 1 && p
->prt_max
== 65535 &&
1064 (tor_addr_family(&p
->addr
) == family
||
1065 tor_addr_family(&p
->addr
) == AF_UNSPEC
)) {
1068 } SMARTLIST_FOREACH_END(p
);
1072 /** Write a single address policy to the buf_len byte buffer at buf. Return
1073 * the number of characters written, or -1 on failure. */
1075 policy_write_item(char *buf
, size_t buflen
, addr_policy_t
*policy
,
1076 int format_for_desc
)
1079 char addrbuf
[TOR_ADDR_BUF_LEN
];
1080 const char *addrpart
;
1082 const int is_accept
= policy
->policy_type
== ADDR_POLICY_ACCEPT
;
1083 const sa_family_t family
= tor_addr_family(&policy
->addr
);
1084 const int is_ip6
= (family
== AF_INET6
);
1086 tor_addr_to_str(addrbuf
, &policy
->addr
, sizeof(addrbuf
), 1);
1088 /* write accept/reject 1.2.3.4 */
1089 if (policy
->is_private
) {
1090 addrpart
= "private";
1091 } else if (policy
->maskbits
== 0) {
1092 if (format_for_desc
)
1094 else if (family
== AF_INET6
)
1096 else if (family
== AF_INET
)
1104 result
= tor_snprintf(buf
, buflen
, "%s%s %s",
1105 is_accept
? "accept" : "reject",
1106 (is_ip6
&&format_for_desc
)?"6":"",
1110 written
+= strlen(buf
);
1111 /* If the maskbits is 32 we don't need to give it. If the mask is 0,
1112 * we already wrote "*". */
1113 if (policy
->maskbits
< 32 && policy
->maskbits
> 0) {
1114 if (tor_snprintf(buf
+written
, buflen
-written
, "/%d", policy
->maskbits
)<0)
1116 written
+= strlen(buf
+written
);
1118 if (policy
->prt_min
<= 1 && policy
->prt_max
== 65535) {
1119 /* There is no port set; write ":*" */
1120 if (written
+4 > buflen
)
1122 strlcat(buf
+written
, ":*", buflen
-written
);
1124 } else if (policy
->prt_min
== policy
->prt_max
) {
1125 /* There is only one port; write ":80". */
1126 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d", policy
->prt_min
);
1131 /* There is a range of ports; write ":79-80". */
1132 result
= tor_snprintf(buf
+written
, buflen
-written
, ":%d-%d",
1133 policy
->prt_min
, policy
->prt_max
);
1138 if (written
< buflen
)
1139 buf
[written
] = '\0';
1143 return (int)written
;
1146 /** Create a new exit policy summary, initially only with a single
1147 * port 1-64k item */
1148 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
1149 * RB-tree if that turns out to matter. */
1150 static smartlist_t
*
1151 policy_summary_create(void)
1153 smartlist_t
*summary
;
1154 policy_summary_item_t
* item
;
1156 item
= tor_malloc_zero(sizeof(policy_summary_item_t
));
1158 item
->prt_max
= 65535;
1159 item
->reject_count
= 0;
1162 summary
= smartlist_new();
1163 smartlist_add(summary
, item
);
1168 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
1169 * The current item is changed to end at new-starts - 1, the new item
1170 * copies reject_count and accepted from the old item,
1171 * starts at new_starts and ends at the port where the original item
1174 static policy_summary_item_t
*
1175 policy_summary_item_split(policy_summary_item_t
* old
, uint16_t new_starts
)
1177 policy_summary_item_t
* new;
1179 new = tor_malloc_zero(sizeof(policy_summary_item_t
));
1180 new->prt_min
= new_starts
;
1181 new->prt_max
= old
->prt_max
;
1182 new->reject_count
= old
->reject_count
;
1183 new->accepted
= old
->accepted
;
1185 old
->prt_max
= new_starts
-1;
1187 tor_assert(old
->prt_min
<= old
->prt_max
);
1188 tor_assert(new->prt_min
<= new->prt_max
);
1192 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
1193 * my immortal soul, he can clean it up himself. */
1194 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
1196 #define REJECT_CUTOFF_COUNT (1<<25)
1197 /** Split an exit policy summary so that prt_min and prt_max
1198 * fall at exactly the start and end of an item respectively.
1201 policy_summary_split(smartlist_t
*summary
,
1202 uint16_t prt_min
, uint16_t prt_max
)
1208 while (AT(i
)->prt_max
< prt_min
)
1210 if (AT(i
)->prt_min
!= prt_min
) {
1211 policy_summary_item_t
* new_item
;
1212 new_item
= policy_summary_item_split(AT(i
), prt_min
);
1213 smartlist_insert(summary
, i
+1, new_item
);
1218 while (AT(i
)->prt_max
< prt_max
)
1220 if (AT(i
)->prt_max
!= prt_max
) {
1221 policy_summary_item_t
* new_item
;
1222 new_item
= policy_summary_item_split(AT(i
), prt_max
+1);
1223 smartlist_insert(summary
, i
+1, new_item
);
1226 return start_at_index
;
1229 /** Mark port ranges as accepted if they are below the reject_count */
1231 policy_summary_accept(smartlist_t
*summary
,
1232 uint16_t prt_min
, uint16_t prt_max
)
1234 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
1235 while (i
< smartlist_len(summary
) &&
1236 AT(i
)->prt_max
<= prt_max
) {
1237 if (!AT(i
)->accepted
&&
1238 AT(i
)->reject_count
<= REJECT_CUTOFF_COUNT
)
1239 AT(i
)->accepted
= 1;
1242 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
1245 /** Count the number of addresses in a network with prefixlen maskbits
1246 * against the given portrange. */
1248 policy_summary_reject(smartlist_t
*summary
,
1249 maskbits_t maskbits
,
1250 uint16_t prt_min
, uint16_t prt_max
)
1252 int i
= policy_summary_split(summary
, prt_min
, prt_max
);
1253 /* XXX: ipv4 specific */
1254 uint64_t count
= (U64_LITERAL(1) << (32-maskbits
));
1255 while (i
< smartlist_len(summary
) &&
1256 AT(i
)->prt_max
<= prt_max
) {
1257 AT(i
)->reject_count
+= count
;
1260 tor_assert(i
< smartlist_len(summary
) || prt_max
==65535);
1263 /** Add a single exit policy item to our summary:
1264 * If it is an accept ignore it unless it is for all IP addresses
1265 * ("*"), i.e. it's prefixlen/maskbits is 0, else call
1266 * policy_summary_accept().
1267 * If it's a reject ignore it if it is about one of the private
1268 * networks, else call policy_summary_reject().
1271 policy_summary_add_item(smartlist_t
*summary
, addr_policy_t
*p
)
1273 if (p
->policy_type
== ADDR_POLICY_ACCEPT
) {
1274 if (p
->maskbits
== 0) {
1275 policy_summary_accept(summary
, p
->prt_min
, p
->prt_max
);
1277 } else if (p
->policy_type
== ADDR_POLICY_REJECT
) {
1281 for (i
= 0; private_nets
[i
]; ++i
) {
1283 maskbits_t maskbits
;
1284 if (tor_addr_parse_mask_ports(private_nets
[i
], 0, &addr
,
1285 &maskbits
, NULL
, NULL
)<0) {
1288 if (tor_addr_compare(&p
->addr
, &addr
, CMP_EXACT
) == 0 &&
1289 p
->maskbits
== maskbits
) {
1296 policy_summary_reject(summary
, p
->maskbits
, p
->prt_min
, p
->prt_max
);
1302 /** Create a string representing a summary for an exit policy.
1303 * The summary will either be an "accept" plus a comma-separated list of port
1304 * ranges or a "reject" plus port-ranges, depending on which is shorter.
1306 * If no exits are allowed at all then NULL is returned, if no ports
1307 * are blocked instead of "reject " we return "accept 1-65535" (this
1308 * is an exception to the shorter-representation-wins rule).
1311 policy_summarize(smartlist_t
*policy
, sa_family_t family
)
1313 smartlist_t
*summary
= policy_summary_create();
1314 smartlist_t
*accepts
, *rejects
;
1315 int i
, last
, start_prt
;
1316 size_t accepts_len
, rejects_len
;
1317 char *accepts_str
= NULL
, *rejects_str
= NULL
, *shorter_str
, *result
;
1322 /* Create the summary list */
1323 SMARTLIST_FOREACH_BEGIN(policy
, addr_policy_t
*, p
) {
1324 sa_family_t f
= tor_addr_family(&p
->addr
);
1325 if (f
!= AF_INET
&& f
!= AF_INET6
) {
1326 log_warn(LD_BUG
, "Weird family when summarizing address policy");
1330 /* XXXX-ipv6 More family work is needed */
1331 policy_summary_add_item(summary
, p
);
1332 } SMARTLIST_FOREACH_END(p
);
1334 /* Now create two lists of strings, one for accepted and one
1335 * for rejected ports. We take care to merge ranges so that
1336 * we avoid getting stuff like "1-4,5-9,10", instead we want
1341 accepts
= smartlist_new();
1342 rejects
= smartlist_new();
1344 last
= i
== smartlist_len(summary
)-1;
1346 AT(i
)->accepted
!= AT(i
+1)->accepted
) {
1347 char buf
[POLICY_BUF_LEN
];
1349 if (start_prt
== AT(i
)->prt_max
)
1350 tor_snprintf(buf
, sizeof(buf
), "%d", start_prt
);
1352 tor_snprintf(buf
, sizeof(buf
), "%d-%d", start_prt
, AT(i
)->prt_max
);
1354 if (AT(i
)->accepted
)
1355 smartlist_add(accepts
, tor_strdup(buf
));
1357 smartlist_add(rejects
, tor_strdup(buf
));
1362 start_prt
= AT(i
+1)->prt_min
;
1367 /* Figure out which of the two stringlists will be shorter and use
1368 * that to build the result
1370 if (smartlist_len(accepts
) == 0) { /* no exits at all */
1371 result
= tor_strdup("reject 1-65535");
1374 if (smartlist_len(rejects
) == 0) { /* no rejects at all */
1375 result
= tor_strdup("accept 1-65535");
1379 accepts_str
= smartlist_join_strings(accepts
, ",", 0, &accepts_len
);
1380 rejects_str
= smartlist_join_strings(rejects
, ",", 0, &rejects_len
);
1382 if (rejects_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("reject")-1 &&
1383 accepts_len
> MAX_EXITPOLICY_SUMMARY_LEN
-strlen("accept")-1) {
1385 shorter_str
= accepts_str
;
1388 c
= shorter_str
+ (MAX_EXITPOLICY_SUMMARY_LEN
-strlen(prefix
)-1);
1389 while (*c
!= ',' && c
>= shorter_str
)
1391 tor_assert(c
>= shorter_str
);
1392 tor_assert(*c
== ',');
1395 } else if (rejects_len
< accepts_len
) {
1396 shorter_str
= rejects_str
;
1399 shorter_str
= accepts_str
;
1403 tor_asprintf(&result
, "%s %s", prefix
, shorter_str
);
1407 SMARTLIST_FOREACH(summary
, policy_summary_item_t
*, s
, tor_free(s
));
1408 smartlist_free(summary
);
1410 tor_free(accepts_str
);
1411 SMARTLIST_FOREACH(accepts
, char *, s
, tor_free(s
));
1412 smartlist_free(accepts
);
1414 tor_free(rejects_str
);
1415 SMARTLIST_FOREACH(rejects
, char *, s
, tor_free(s
));
1416 smartlist_free(rejects
);
1421 /** Convert a summarized policy string into a short_policy_t. Return NULL
1422 * if the string is not well-formed. */
1424 parse_short_policy(const char *summary
)
1426 const char *orig_summary
= summary
;
1427 short_policy_t
*result
;
1430 short_policy_entry_t entries
[MAX_EXITPOLICY_SUMMARY_LEN
]; /* overkill */
1433 if (!strcmpstart(summary
, "accept ")) {
1435 summary
+= strlen("accept ");
1436 } else if (!strcmpstart(summary
, "reject ")) {
1438 summary
+= strlen("reject ");
1440 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Unrecognized policy summary keyword");
1445 for ( ; *summary
; summary
= next
) {
1446 const char *comma
= strchr(summary
, ',');
1452 next
= comma
? comma
+1 : strchr(summary
, '\0');
1453 len
= comma
? (size_t)(comma
- summary
) : strlen(summary
);
1455 if (n_entries
== MAX_EXITPOLICY_SUMMARY_LEN
) {
1456 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
, "Impossibly long policy summary %s",
1457 escaped(orig_summary
));
1461 if (! TOR_ISDIGIT(*summary
) || len
> (sizeof(ent_buf
)-1)) {
1462 /* unrecognized entry format. skip it. */
1466 /* empty; skip it. */
1467 /* XXX This happens to be unreachable, since if len==0, then *summary is
1468 * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
1472 memcpy(ent_buf
, summary
, len
);
1473 ent_buf
[len
] = '\0';
1475 if (tor_sscanf(ent_buf
, "%u-%u%c", &low
, &high
, &dummy
) == 2) {
1476 if (low
<1 || low
>65535 || high
<1 || high
>65535 || low
>high
) {
1477 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1478 "Found bad entry in policy summary %s", escaped(orig_summary
));
1481 } else if (tor_sscanf(ent_buf
, "%u%c", &low
, &dummy
) == 1) {
1482 if (low
<1 || low
>65535) {
1483 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1484 "Found bad entry in policy summary %s", escaped(orig_summary
));
1489 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,"Found bad entry in policy summary %s",
1490 escaped(orig_summary
));
1494 entries
[n_entries
].min_port
= low
;
1495 entries
[n_entries
].max_port
= high
;
1499 if (n_entries
== 0) {
1500 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1501 "Found no port-range entries in summary %s", escaped(orig_summary
));
1506 size_t size
= STRUCT_OFFSET(short_policy_t
, entries
) +
1507 sizeof(short_policy_entry_t
)*(n_entries
);
1508 result
= tor_malloc_zero(size
);
1510 tor_assert( (char*)&result
->entries
[n_entries
-1] < ((char*)result
)+size
);
1513 result
->is_accept
= is_accept
;
1514 result
->n_entries
= n_entries
;
1515 memcpy(result
->entries
, entries
, sizeof(short_policy_entry_t
)*n_entries
);
1519 /** Write <b>policy</b> back out into a string. Used only for unit tests
1522 write_short_policy(const short_policy_t
*policy
)
1526 smartlist_t
*sl
= smartlist_new();
1528 smartlist_add_asprintf(sl
, "%s", policy
->is_accept
? "accept " : "reject ");
1530 for (i
=0; i
< policy
->n_entries
; i
++) {
1531 const short_policy_entry_t
*e
= &policy
->entries
[i
];
1532 if (e
->min_port
== e
->max_port
) {
1533 smartlist_add_asprintf(sl
, "%d", e
->min_port
);
1535 smartlist_add_asprintf(sl
, "%d-%d", e
->min_port
, e
->max_port
);
1537 if (i
< policy
->n_entries
-1)
1538 smartlist_add(sl
, tor_strdup(","));
1540 answer
= smartlist_join_strings(sl
, "", 0, NULL
);
1541 SMARTLIST_FOREACH(sl
, char *, a
, tor_free(a
));
1546 /** Release all storage held in <b>policy</b>. */
1548 short_policy_free(short_policy_t
*policy
)
1553 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
1554 * or rejected by the summarized policy <b>policy</b>. Return values are as
1555 * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
1556 * functions, requires the <b>port</b> be specified. */
1557 addr_policy_result_t
1558 compare_tor_addr_to_short_policy(const tor_addr_t
*addr
, uint16_t port
,
1559 const short_policy_t
*policy
)
1562 int found_match
= 0;
1565 tor_assert(port
!= 0);
1567 if (addr
&& tor_addr_is_null(addr
))
1568 addr
= NULL
; /* Unspec means 'no address at all,' in this context. */
1570 if (addr
&& get_options()->ClientRejectInternalAddresses
&&
1571 (tor_addr_is_internal(addr
, 0) || tor_addr_is_loopback(addr
)))
1572 return ADDR_POLICY_REJECTED
;
1574 for (i
=0; i
< policy
->n_entries
; ++i
) {
1575 const short_policy_entry_t
*e
= &policy
->entries
[i
];
1576 if (e
->min_port
<= port
&& port
<= e
->max_port
) {
1583 accept
= policy
->is_accept
;
1585 accept
= ! policy
->is_accept
;
1587 /* ???? are these right? -NM */
1588 /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
1589 * case here, because it would cause clients to believe that the node
1590 * allows exit enclaving. Trying it anyway would open up a cool attack
1591 * where the node refuses due to exitpolicy, the client reacts in
1592 * surprise by rewriting the node's exitpolicy to reject *:*, and then
1593 * a bad guy targets users by causing them to attempt such connections
1594 * to 98% of the exits.
1596 * Once microdescriptors can handle addresses in special cases (e.g. if
1597 * we ever solve ticket 1774), we can provide certainty here. -RD */
1599 return ADDR_POLICY_PROBABLY_ACCEPTED
;
1601 return ADDR_POLICY_REJECTED
;
1604 /** Return true iff <b>policy</b> seems reject all ports */
1606 short_policy_is_reject_star(const short_policy_t
*policy
)
1608 /* This doesn't need to be as much on the lookout as policy_is_reject_star,
1609 * since policy summaries are from the consensus or from consensus
1613 /* Check for an exact match of "reject 1-65535". */
1614 return (policy
->is_accept
== 0 && policy
->n_entries
== 1 &&
1615 policy
->entries
[0].min_port
== 1 &&
1616 policy
->entries
[0].max_port
== 65535);
1619 /** Decide whether addr:port is probably or definitely accepted or rejected by
1620 * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
1621 * interpretation. */
1622 addr_policy_result_t
1623 compare_tor_addr_to_node_policy(const tor_addr_t
*addr
, uint16_t port
,
1626 if (node
->rejects_all
)
1627 return ADDR_POLICY_REJECTED
;
1629 if (addr
&& tor_addr_family(addr
) == AF_INET6
) {
1630 const short_policy_t
*p
= NULL
;
1632 p
= node
->ri
->ipv6_exit_policy
;
1634 p
= node
->md
->ipv6_exit_policy
;
1636 return compare_tor_addr_to_short_policy(addr
, port
, p
);
1638 return ADDR_POLICY_REJECTED
;
1642 return compare_tor_addr_to_addr_policy(addr
, port
, node
->ri
->exit_policy
);
1643 } else if (node
->md
) {
1644 if (node
->md
->exit_policy
== NULL
)
1645 return ADDR_POLICY_REJECTED
;
1647 return compare_tor_addr_to_short_policy(addr
, port
,
1648 node
->md
->exit_policy
);
1650 return ADDR_POLICY_PROBABLY_REJECTED
;
1654 /** Implementation for GETINFO control command: knows the answer for questions
1655 * about "exit-policy/..." */
1657 getinfo_helper_policies(control_connection_t
*conn
,
1658 const char *question
, char **answer
,
1659 const char **errmsg
)
1663 if (!strcmp(question
, "exit-policy/default")) {
1664 *answer
= tor_strdup(DEFAULT_EXIT_POLICY
);
1669 /** Release all storage held by <b>p</b>. */
1671 addr_policy_list_free(smartlist_t
*lst
)
1675 SMARTLIST_FOREACH(lst
, addr_policy_t
*, policy
, addr_policy_free(policy
));
1676 smartlist_free(lst
);
1679 /** Release all storage held by <b>p</b>. */
1681 addr_policy_free(addr_policy_t
*p
)
1686 if (--p
->refcnt
<= 0) {
1687 if (p
->is_canonical
) {
1688 policy_map_ent_t search
, *found
;
1690 found
= HT_REMOVE(policy_map
, &policy_root
, &search
);
1692 tor_assert(p
== found
->policy
);
1700 /** Release all storage held by policy variables. */
1702 policies_free_all(void)
1704 addr_policy_list_free(reachable_or_addr_policy
);
1705 reachable_or_addr_policy
= NULL
;
1706 addr_policy_list_free(reachable_dir_addr_policy
);
1707 reachable_dir_addr_policy
= NULL
;
1708 addr_policy_list_free(socks_policy
);
1709 socks_policy
= NULL
;
1710 addr_policy_list_free(dir_policy
);
1712 addr_policy_list_free(authdir_reject_policy
);
1713 authdir_reject_policy
= NULL
;
1714 addr_policy_list_free(authdir_invalid_policy
);
1715 authdir_invalid_policy
= NULL
;
1716 addr_policy_list_free(authdir_baddir_policy
);
1717 authdir_baddir_policy
= NULL
;
1718 addr_policy_list_free(authdir_badexit_policy
);
1719 authdir_badexit_policy
= NULL
;
1721 if (!HT_EMPTY(&policy_root
)) {
1722 policy_map_ent_t
**ent
;
1724 char buf
[POLICY_BUF_LEN
];
1726 log_warn(LD_MM
, "Still had %d address policies cached at shutdown.",
1727 (int)HT_SIZE(&policy_root
));
1729 /* Note the first 10 cached policies to try to figure out where they
1730 * might be coming from. */
1731 HT_FOREACH(ent
, policy_map
, &policy_root
) {
1734 if (policy_write_item(buf
, sizeof(buf
), (*ent
)->policy
, 0) >= 0)
1735 log_warn(LD_MM
," %d [%d]: %s", n
, (*ent
)->policy
->refcnt
, buf
);
1738 HT_CLEAR(policy_map
, &policy_root
);