Merge branch 'maint-0.2.9'
[tor.git] / src / or / policies.c
blob2aa6373f3e9b9d5ed39aca3c93fdf31c10f92fb5
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file policies.c
8 * \brief Code to parse and use address policies and exit policies.
10 * We have two key kinds of address policy: full and compressed. A full
11 * policy is an array of accept/reject patterns, to be applied in order.
12 * A short policy is simply a list of ports. This module handles both
13 * kinds, including generic functions to apply them to addresses, and
14 * also including code to manage the global policies that we apply to
15 * incoming and outgoing connections.
16 **/
18 #define POLICIES_PRIVATE
20 #include "or.h"
21 #include "config.h"
22 #include "dirserv.h"
23 #include "microdesc.h"
24 #include "networkstatus.h"
25 #include "nodelist.h"
26 #include "policies.h"
27 #include "router.h"
28 #include "routerparse.h"
29 #include "geoip.h"
30 #include "ht.h"
32 /** Policy that addresses for incoming SOCKS connections must match. */
33 static smartlist_t *socks_policy = NULL;
34 /** Policy that addresses for incoming directory connections must match. */
35 static smartlist_t *dir_policy = NULL;
36 /** Policy that addresses for incoming router descriptors must match in order
37 * to be published by us. */
38 static smartlist_t *authdir_reject_policy = NULL;
39 /** Policy that addresses for incoming router descriptors must match in order
40 * to be marked as valid in our networkstatus. */
41 static smartlist_t *authdir_invalid_policy = NULL;
42 /** Policy that addresses for incoming router descriptors must <b>not</b>
43 * match in order to not be marked as BadExit. */
44 static smartlist_t *authdir_badexit_policy = NULL;
46 /** Parsed addr_policy_t describing which addresses we believe we can start
47 * circuits at. */
48 static smartlist_t *reachable_or_addr_policy = NULL;
49 /** Parsed addr_policy_t describing which addresses we believe we can connect
50 * to directories at. */
51 static smartlist_t *reachable_dir_addr_policy = NULL;
53 /** Element of an exit policy summary */
54 typedef struct policy_summary_item_t {
55 uint16_t prt_min; /**< Lowest port number to accept/reject. */
56 uint16_t prt_max; /**< Highest port number to accept/reject. */
57 uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
58 this port range. */
59 unsigned int accepted:1; /** Has this port already been accepted */
60 } policy_summary_item_t;
62 /** Private networks. This list is used in two places, once to expand the
63 * "private" keyword when parsing our own exit policy, secondly to ignore
64 * just such networks when building exit policy summaries. It is important
65 * that all authorities agree on that list when creating summaries, so don't
66 * just change this without a proper migration plan and a proposal and stuff.
68 static const char *private_nets[] = {
69 "0.0.0.0/8", "169.254.0.0/16",
70 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
71 "[::]/8",
72 "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
73 NULL
76 static int policies_parse_exit_policy_internal(
77 config_line_t *cfg,
78 smartlist_t **dest,
79 int ipv6_exit,
80 int rejectprivate,
81 const smartlist_t *configured_addresses,
82 int reject_interface_addresses,
83 int reject_configured_port_addresses,
84 int add_default_policy);
86 /** Replace all "private" entries in *<b>policy</b> with their expanded
87 * equivalents. */
88 void
89 policy_expand_private(smartlist_t **policy)
91 uint16_t port_min, port_max;
93 int i;
94 smartlist_t *tmp;
96 if (!*policy) /*XXXX disallow NULL policies? */
97 return;
99 tmp = smartlist_new();
101 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
102 if (! p->is_private) {
103 smartlist_add(tmp, p);
104 continue;
106 for (i = 0; private_nets[i]; ++i) {
107 addr_policy_t newpolicy;
108 memcpy(&newpolicy, p, sizeof(addr_policy_t));
109 newpolicy.is_private = 0;
110 newpolicy.is_canonical = 0;
111 if (tor_addr_parse_mask_ports(private_nets[i], 0,
112 &newpolicy.addr,
113 &newpolicy.maskbits, &port_min, &port_max)<0) {
114 tor_assert_unreached();
116 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
118 addr_policy_free(p);
119 } SMARTLIST_FOREACH_END(p);
121 smartlist_free(*policy);
122 *policy = tmp;
125 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
126 * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
127 * specific and one IPv6-specific. */
128 void
129 policy_expand_unspec(smartlist_t **policy)
131 smartlist_t *tmp;
132 if (!*policy)
133 return;
135 tmp = smartlist_new();
136 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
137 sa_family_t family = tor_addr_family(&p->addr);
138 if (family == AF_INET6 || family == AF_INET || p->is_private) {
139 smartlist_add(tmp, p);
140 } else if (family == AF_UNSPEC) {
141 addr_policy_t newpolicy_ipv4;
142 addr_policy_t newpolicy_ipv6;
143 memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
144 memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
145 newpolicy_ipv4.is_canonical = 0;
146 newpolicy_ipv6.is_canonical = 0;
147 if (p->maskbits != 0) {
148 log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
149 newpolicy_ipv4.maskbits = 0;
150 newpolicy_ipv6.maskbits = 0;
152 tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
153 tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
154 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
155 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
156 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
157 addr_policy_free(p);
158 } else {
159 log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
160 smartlist_add(tmp, p);
162 } SMARTLIST_FOREACH_END(p);
164 smartlist_free(*policy);
165 *policy = tmp;
169 * Given a linked list of config lines containing "accept[6]" and "reject[6]"
170 * tokens, parse them and append the result to <b>dest</b>. Return -1
171 * if any tokens are malformed (and don't append any), else return 0.
173 * If <b>assume_action</b> is nonnegative, then insert its action
174 * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
175 * action.
177 static int
178 parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
179 int assume_action)
181 smartlist_t *result;
182 smartlist_t *entries;
183 addr_policy_t *item;
184 int malformed_list;
185 int r = 0;
187 if (!cfg)
188 return 0;
190 result = smartlist_new();
191 entries = smartlist_new();
192 for (; cfg; cfg = cfg->next) {
193 smartlist_split_string(entries, cfg->value, ",",
194 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
195 SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
196 log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
197 malformed_list = 0;
198 item = router_parse_addr_policy_item_from_string(ent, assume_action,
199 &malformed_list);
200 if (item) {
201 smartlist_add(result, item);
202 } else if (malformed_list) {
203 /* the error is so severe the entire list should be discarded */
204 log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
205 "list.", ent);
206 r = -1;
207 } else {
208 /* the error is minor: don't add the item, but keep processing the
209 * rest of the policies in the list */
210 log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
211 "The remainder of the policy list will be used.",
212 ent);
214 } SMARTLIST_FOREACH_END(ent);
215 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
216 smartlist_clear(entries);
218 smartlist_free(entries);
219 if (r == -1) {
220 addr_policy_list_free(result);
221 } else {
222 policy_expand_private(&result);
223 policy_expand_unspec(&result);
225 if (*dest) {
226 smartlist_add_all(*dest, result);
227 smartlist_free(result);
228 } else {
229 *dest = result;
233 return r;
236 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
237 * reachable_(or|dir)_addr_policy. The options should already have
238 * been validated by validate_addr_policies.
240 static int
241 parse_reachable_addresses(void)
243 const or_options_t *options = get_options();
244 int ret = 0;
246 if (options->ReachableDirAddresses &&
247 options->ReachableORAddresses &&
248 options->ReachableAddresses) {
249 log_warn(LD_CONFIG,
250 "Both ReachableDirAddresses and ReachableORAddresses are set. "
251 "ReachableAddresses setting will be ignored.");
253 addr_policy_list_free(reachable_or_addr_policy);
254 reachable_or_addr_policy = NULL;
255 if (!options->ReachableORAddresses && options->ReachableAddresses)
256 log_info(LD_CONFIG,
257 "Using ReachableAddresses as ReachableORAddresses.");
258 if (parse_addr_policy(options->ReachableORAddresses ?
259 options->ReachableORAddresses :
260 options->ReachableAddresses,
261 &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
262 log_warn(LD_CONFIG,
263 "Error parsing Reachable%sAddresses entry; ignoring.",
264 options->ReachableORAddresses ? "OR" : "");
265 ret = -1;
268 addr_policy_list_free(reachable_dir_addr_policy);
269 reachable_dir_addr_policy = NULL;
270 if (!options->ReachableDirAddresses && options->ReachableAddresses)
271 log_info(LD_CONFIG,
272 "Using ReachableAddresses as ReachableDirAddresses");
273 if (parse_addr_policy(options->ReachableDirAddresses ?
274 options->ReachableDirAddresses :
275 options->ReachableAddresses,
276 &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
277 if (options->ReachableDirAddresses)
278 log_warn(LD_CONFIG,
279 "Error parsing ReachableDirAddresses entry; ignoring.");
280 ret = -1;
283 /* We ignore ReachableAddresses for relays */
284 if (!server_mode(options)) {
285 if (policy_is_reject_star(reachable_or_addr_policy, AF_UNSPEC, 0)
286 || policy_is_reject_star(reachable_dir_addr_policy, AF_UNSPEC,0)) {
287 log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
288 "ReachableAddresses, ReachableORAddresses, or "
289 "ReachableDirAddresses reject all addresses. Please accept "
290 "some addresses in these options.");
291 } else if (options->ClientUseIPv4 == 1
292 && (policy_is_reject_star(reachable_or_addr_policy, AF_INET, 0)
293 || policy_is_reject_star(reachable_dir_addr_policy, AF_INET, 0))) {
294 log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
295 "ReachableAddresses, ReachableORAddresses, or "
296 "ReachableDirAddresses reject all IPv4 addresses. "
297 "Tor will not connect using IPv4.");
298 } else if (fascist_firewall_use_ipv6(options)
299 && (policy_is_reject_star(reachable_or_addr_policy, AF_INET6, 0)
300 || policy_is_reject_star(reachable_dir_addr_policy, AF_INET6, 0))) {
301 log_warn(LD_CONFIG, "You have configured tor to use or prefer IPv6 "
302 "(or UseBridges 1), but "
303 "ReachableAddresses, ReachableORAddresses, or "
304 "ReachableDirAddresses reject all IPv6 addresses. "
305 "Tor will not connect using IPv6.");
309 return ret;
312 /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
313 * address:port combination. */
314 static int
315 firewall_is_fascist_impl(void)
317 const or_options_t *options = get_options();
318 /* Assume every non-bridge relay has an IPv4 address.
319 * Clients which use bridges may only know the IPv6 address of their
320 * bridge, but they will connect regardless of the ClientUseIPv6 setting. */
321 return options->ClientUseIPv4 == 0;
324 /** Return true iff the firewall options, including ClientUseIPv4 0 and
325 * ClientUseIPv6 0, might block any OR address:port combination.
326 * Address preferences may still change which address is selected even if
327 * this function returns false.
330 firewall_is_fascist_or(void)
332 return (reachable_or_addr_policy != NULL || firewall_is_fascist_impl());
335 /** Return true iff the firewall options, including ClientUseIPv4 0 and
336 * ClientUseIPv6 0, might block any Dir address:port combination.
337 * Address preferences may still change which address is selected even if
338 * this function returns false.
341 firewall_is_fascist_dir(void)
343 return (reachable_dir_addr_policy != NULL || firewall_is_fascist_impl());
346 /** Return true iff <b>policy</b> (possibly NULL) will allow a
347 * connection to <b>addr</b>:<b>port</b>.
349 static int
350 addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
351 smartlist_t *policy)
353 addr_policy_result_t p;
354 p = compare_tor_addr_to_addr_policy(addr, port, policy);
355 switch (p) {
356 case ADDR_POLICY_PROBABLY_ACCEPTED:
357 case ADDR_POLICY_ACCEPTED:
358 return 1;
359 case ADDR_POLICY_PROBABLY_REJECTED:
360 case ADDR_POLICY_REJECTED:
361 return 0;
362 default:
363 log_warn(LD_BUG, "Unexpected result: %d", (int)p);
364 return 0;
368 /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
369 * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
370 * order. */
371 /* XXXX deprecate when possible. */
372 static int
373 addr_policy_permits_address(uint32_t addr, uint16_t port,
374 smartlist_t *policy)
376 tor_addr_t a;
377 tor_addr_from_ipv4h(&a, addr);
378 return addr_policy_permits_tor_addr(&a, port, policy);
381 /** Return true iff we think our firewall will let us make a connection to
382 * addr:port.
384 * If we are configured as a server, ignore any address family preference and
385 * just use IPv4.
386 * Otherwise:
387 * - return false for all IPv4 addresses:
388 * - if ClientUseIPv4 is 0, or
389 * if pref_only and pref_ipv6 are both true;
390 * - return false for all IPv6 addresses:
391 * - if fascist_firewall_use_ipv6() is 0, or
392 * - if pref_only is true and pref_ipv6 is false.
394 * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
395 STATIC int
396 fascist_firewall_allows_address(const tor_addr_t *addr,
397 uint16_t port,
398 smartlist_t *firewall_policy,
399 int pref_only, int pref_ipv6)
401 const or_options_t *options = get_options();
402 const int client_mode = !server_mode(options);
404 if (!addr || tor_addr_is_null(addr) || !port) {
405 return 0;
408 /* Clients stop using IPv4 if it's disabled. In most cases, clients also
409 * stop using IPv4 if it's not preferred.
410 * Servers must have IPv4 enabled and preferred. */
411 if (tor_addr_family(addr) == AF_INET && client_mode &&
412 (!options->ClientUseIPv4 || (pref_only && pref_ipv6))) {
413 return 0;
416 /* Clients and Servers won't use IPv6 unless it's enabled (and in most
417 * cases, IPv6 must also be preferred before it will be used). */
418 if (tor_addr_family(addr) == AF_INET6 &&
419 (!fascist_firewall_use_ipv6(options) || (pref_only && !pref_ipv6))) {
420 return 0;
423 return addr_policy_permits_tor_addr(addr, port,
424 firewall_policy);
427 /** Is this client configured to use IPv6?
428 * Returns true if the client might use IPv6 for some of its connections
429 * (including dual-stack and IPv6-only clients), and false if it will never
430 * use IPv6 for any connections.
431 * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
432 * port: it supports bridge client per-node IPv6 preferences.
435 fascist_firewall_use_ipv6(const or_options_t *options)
437 /* Clients use IPv6 if it's set, or they use bridges, or they don't use
438 * IPv4, or they prefer it.
439 * ClientPreferIPv6DirPort is deprecated, but check it anyway. */
440 return (options->ClientUseIPv6 == 1 || options->ClientUseIPv4 == 0 ||
441 options->ClientPreferIPv6ORPort == 1 ||
442 options->ClientPreferIPv6DirPort == 1 || options->UseBridges == 1);
445 /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
446 * ClientPreferIPv6DirPort?
447 * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
449 static int
450 fascist_firewall_prefer_ipv6_impl(const or_options_t *options)
453 Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
454 If we're a server or IPv6 is disabled, use IPv4.
455 If IPv4 is disabled, use IPv6.
458 if (server_mode(options) || !fascist_firewall_use_ipv6(options)) {
459 return 0;
462 if (!options->ClientUseIPv4) {
463 return 1;
466 return -1;
469 /** Do we prefer to connect to IPv6 ORPorts?
470 * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
471 * per-node IPv6 preferences.
474 fascist_firewall_prefer_ipv6_orport(const or_options_t *options)
476 int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
478 if (pref_ipv6 >= 0) {
479 return pref_ipv6;
482 /* We can use both IPv4 and IPv6 - which do we prefer? */
483 if (options->ClientPreferIPv6ORPort == 1) {
484 return 1;
487 return 0;
490 /** Do we prefer to connect to IPv6 DirPorts?
492 * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
493 * preferences. There's no reason to use it instead of this function.)
496 fascist_firewall_prefer_ipv6_dirport(const or_options_t *options)
498 int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
500 if (pref_ipv6 >= 0) {
501 return pref_ipv6;
504 /* We can use both IPv4 and IPv6 - which do we prefer? */
505 if (options->ClientPreferIPv6DirPort == 1) {
506 return 1;
509 return 0;
512 /** Return true iff we think our firewall will let us make a connection to
513 * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
514 * fw_connection.
515 * If pref_only is true, return true if addr is in the client's preferred
516 * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
517 * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
520 fascist_firewall_allows_address_addr(const tor_addr_t *addr, uint16_t port,
521 firewall_connection_t fw_connection,
522 int pref_only, int pref_ipv6)
524 if (fw_connection == FIREWALL_OR_CONNECTION) {
525 return fascist_firewall_allows_address(addr, port,
526 reachable_or_addr_policy,
527 pref_only, pref_ipv6);
528 } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
529 return fascist_firewall_allows_address(addr, port,
530 reachable_dir_addr_policy,
531 pref_only, pref_ipv6);
532 } else {
533 log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
534 fw_connection);
535 return 0;
539 /** Return true iff we think our firewall will let us make a connection to
540 * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
541 * fw_connection.
542 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
544 static int
545 fascist_firewall_allows_address_ap(const tor_addr_port_t *ap,
546 firewall_connection_t fw_connection,
547 int pref_only, int pref_ipv6)
549 tor_assert(ap);
550 return fascist_firewall_allows_address_addr(&ap->addr, ap->port,
551 fw_connection, pref_only,
552 pref_ipv6);
555 /* Return true iff we think our firewall will let us make a connection to
556 * ipv4h_or_addr:ipv4_or_port. ipv4h_or_addr is interpreted in host order.
557 * Uses ReachableORAddresses or ReachableDirAddresses based on
558 * fw_connection.
559 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
561 static int
562 fascist_firewall_allows_address_ipv4h(uint32_t ipv4h_or_addr,
563 uint16_t ipv4_or_port,
564 firewall_connection_t fw_connection,
565 int pref_only, int pref_ipv6)
567 tor_addr_t ipv4_or_addr;
568 tor_addr_from_ipv4h(&ipv4_or_addr, ipv4h_or_addr);
569 return fascist_firewall_allows_address_addr(&ipv4_or_addr, ipv4_or_port,
570 fw_connection, pref_only,
571 pref_ipv6);
574 /** Return true iff we think our firewall will let us make a connection to
575 * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
576 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
577 * <b>fw_connection</b>.
578 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
580 static int
581 fascist_firewall_allows_base(uint32_t ipv4h_addr, uint16_t ipv4_orport,
582 uint16_t ipv4_dirport,
583 const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
584 uint16_t ipv6_dirport,
585 firewall_connection_t fw_connection,
586 int pref_only, int pref_ipv6)
588 if (fascist_firewall_allows_address_ipv4h(ipv4h_addr,
589 (fw_connection == FIREWALL_OR_CONNECTION
590 ? ipv4_orport
591 : ipv4_dirport),
592 fw_connection,
593 pref_only, pref_ipv6)) {
594 return 1;
597 if (fascist_firewall_allows_address_addr(ipv6_addr,
598 (fw_connection == FIREWALL_OR_CONNECTION
599 ? ipv6_orport
600 : ipv6_dirport),
601 fw_connection,
602 pref_only, pref_ipv6)) {
603 return 1;
606 return 0;
609 /** Like fascist_firewall_allows_base(), but takes ri. */
610 static int
611 fascist_firewall_allows_ri_impl(const routerinfo_t *ri,
612 firewall_connection_t fw_connection,
613 int pref_only, int pref_ipv6)
615 if (!ri) {
616 return 0;
619 /* Assume IPv4 and IPv6 DirPorts are the same */
620 return fascist_firewall_allows_base(ri->addr, ri->or_port, ri->dir_port,
621 &ri->ipv6_addr, ri->ipv6_orport,
622 ri->dir_port, fw_connection, pref_only,
623 pref_ipv6);
626 /** Like fascist_firewall_allows_rs, but takes pref_ipv6. */
627 static int
628 fascist_firewall_allows_rs_impl(const routerstatus_t *rs,
629 firewall_connection_t fw_connection,
630 int pref_only, int pref_ipv6)
632 if (!rs) {
633 return 0;
636 /* Assume IPv4 and IPv6 DirPorts are the same */
637 return fascist_firewall_allows_base(rs->addr, rs->or_port, rs->dir_port,
638 &rs->ipv6_addr, rs->ipv6_orport,
639 rs->dir_port, fw_connection, pref_only,
640 pref_ipv6);
643 /** Like fascist_firewall_allows_base(), but takes rs.
644 * When rs is a fake_status from a dir_server_t, it can have a reachable
645 * address, even when the corresponding node does not.
646 * nodes can be missing addresses when there's no consensus (IPv4 and IPv6),
647 * or when there is a microdescriptor consensus, but no microdescriptors
648 * (microdescriptors have IPv6, the microdesc consensus does not). */
650 fascist_firewall_allows_rs(const routerstatus_t *rs,
651 firewall_connection_t fw_connection, int pref_only)
653 if (!rs) {
654 return 0;
657 /* We don't have access to the node-specific IPv6 preference, so use the
658 * generic IPv6 preference instead. */
659 const or_options_t *options = get_options();
660 int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
661 ? fascist_firewall_prefer_ipv6_orport(options)
662 : fascist_firewall_prefer_ipv6_dirport(options));
664 return fascist_firewall_allows_rs_impl(rs, fw_connection, pref_only,
665 pref_ipv6);
668 /** Return true iff we think our firewall will let us make a connection to
669 * ipv6_addr:ipv6_orport based on ReachableORAddresses.
670 * If <b>fw_connection</b> is FIREWALL_DIR_CONNECTION, returns 0.
671 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
673 static int
674 fascist_firewall_allows_md_impl(const microdesc_t *md,
675 firewall_connection_t fw_connection,
676 int pref_only, int pref_ipv6)
678 if (!md) {
679 return 0;
682 /* Can't check dirport, it doesn't have one */
683 if (fw_connection == FIREWALL_DIR_CONNECTION) {
684 return 0;
687 /* Also can't check IPv4, doesn't have that either */
688 return fascist_firewall_allows_address_addr(&md->ipv6_addr, md->ipv6_orport,
689 fw_connection, pref_only,
690 pref_ipv6);
693 /** Like fascist_firewall_allows_base(), but takes node, and looks up pref_ipv6
694 * from node_ipv6_or/dir_preferred(). */
696 fascist_firewall_allows_node(const node_t *node,
697 firewall_connection_t fw_connection,
698 int pref_only)
700 if (!node) {
701 return 0;
704 node_assert_ok(node);
706 const int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
707 ? node_ipv6_or_preferred(node)
708 : node_ipv6_dir_preferred(node));
710 /* Sometimes, the rs is missing the IPv6 address info, and we need to go
711 * all the way to the md */
712 if (node->ri && fascist_firewall_allows_ri_impl(node->ri, fw_connection,
713 pref_only, pref_ipv6)) {
714 return 1;
715 } else if (node->rs && fascist_firewall_allows_rs_impl(node->rs,
716 fw_connection,
717 pref_only,
718 pref_ipv6)) {
719 return 1;
720 } else if (node->md && fascist_firewall_allows_md_impl(node->md,
721 fw_connection,
722 pref_only,
723 pref_ipv6)) {
724 return 1;
725 } else {
726 /* If we know nothing, assume it's unreachable, we'll never get an address
727 * to connect to. */
728 return 0;
732 /** Like fascist_firewall_allows_rs(), but takes ds. */
734 fascist_firewall_allows_dir_server(const dir_server_t *ds,
735 firewall_connection_t fw_connection,
736 int pref_only)
738 if (!ds) {
739 return 0;
742 /* A dir_server_t always has a fake_status. As long as it has the same
743 * addresses/ports in both fake_status and dir_server_t, this works fine.
744 * (See #17867.)
745 * fascist_firewall_allows_rs only checks the addresses in fake_status. */
746 return fascist_firewall_allows_rs(&ds->fake_status, fw_connection,
747 pref_only);
750 /** If a and b are both valid and allowed by fw_connection,
751 * choose one based on want_a and return it.
752 * Otherwise, return whichever is allowed.
753 * Otherwise, return NULL.
754 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
756 static const tor_addr_port_t *
757 fascist_firewall_choose_address_impl(const tor_addr_port_t *a,
758 const tor_addr_port_t *b,
759 int want_a,
760 firewall_connection_t fw_connection,
761 int pref_only, int pref_ipv6)
763 const tor_addr_port_t *use_a = NULL;
764 const tor_addr_port_t *use_b = NULL;
766 if (fascist_firewall_allows_address_ap(a, fw_connection, pref_only,
767 pref_ipv6)) {
768 use_a = a;
771 if (fascist_firewall_allows_address_ap(b, fw_connection, pref_only,
772 pref_ipv6)) {
773 use_b = b;
776 /* If both are allowed */
777 if (use_a && use_b) {
778 /* Choose a if we want it */
779 return (want_a ? use_a : use_b);
780 } else {
781 /* Choose a if we have it */
782 return (use_a ? use_a : use_b);
786 /** If a and b are both valid and preferred by fw_connection,
787 * choose one based on want_a and return it.
788 * Otherwise, return whichever is preferred.
789 * If neither are preferred, and pref_only is false:
790 * - If a and b are both allowed by fw_connection,
791 * choose one based on want_a and return it.
792 * - Otherwise, return whichever is preferred.
793 * Otherwise, return NULL. */
794 STATIC const tor_addr_port_t *
795 fascist_firewall_choose_address(const tor_addr_port_t *a,
796 const tor_addr_port_t *b,
797 int want_a,
798 firewall_connection_t fw_connection,
799 int pref_only, int pref_ipv6)
801 const tor_addr_port_t *pref = fascist_firewall_choose_address_impl(
802 a, b, want_a,
803 fw_connection,
804 1, pref_ipv6);
805 if (pref_only || pref) {
806 /* If there is a preferred address, use it. If we can only use preferred
807 * addresses, and neither address is preferred, pref will be NULL, and we
808 * want to return NULL, so return it. */
809 return pref;
810 } else {
811 /* If there's no preferred address, and we can return addresses that are
812 * not preferred, use an address that's allowed */
813 return fascist_firewall_choose_address_impl(a, b, want_a, fw_connection,
814 0, pref_ipv6);
818 /** Copy an address and port into <b>ap</b> that we think our firewall will
819 * let us connect to. Uses ipv4_addr/ipv6_addr and
820 * ipv4_orport/ipv6_orport/ReachableORAddresses or
821 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
822 * <b>fw_connection</b>.
823 * If pref_only, only choose preferred addresses. In either case, choose
824 * a preferred address before an address that's not preferred.
825 * If both addresses could be chosen (they are both preferred or both allowed)
826 * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4.
827 * If neither address is chosen, return 0, else return 1. */
828 static int
829 fascist_firewall_choose_address_base(const tor_addr_t *ipv4_addr,
830 uint16_t ipv4_orport,
831 uint16_t ipv4_dirport,
832 const tor_addr_t *ipv6_addr,
833 uint16_t ipv6_orport,
834 uint16_t ipv6_dirport,
835 firewall_connection_t fw_connection,
836 int pref_only,
837 int pref_ipv6,
838 tor_addr_port_t* ap)
840 const tor_addr_port_t *result = NULL;
841 const int want_ipv4 = !pref_ipv6;
843 tor_assert(ipv6_addr);
844 tor_assert(ap);
846 tor_addr_port_t ipv4_ap;
847 tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
848 ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
849 ? ipv4_orport
850 : ipv4_dirport);
852 tor_addr_port_t ipv6_ap;
853 tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
854 ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
855 ? ipv6_orport
856 : ipv6_dirport);
858 result = fascist_firewall_choose_address(&ipv4_ap, &ipv6_ap,
859 want_ipv4,
860 fw_connection, pref_only,
861 pref_ipv6);
863 if (result) {
864 tor_addr_copy(&ap->addr, &result->addr);
865 ap->port = result->port;
866 return 1;
867 } else {
868 return 0;
872 /** Like fascist_firewall_choose_address_base(), but takes a host-order IPv4
873 * address as the first parameter. */
874 static int
875 fascist_firewall_choose_address_ipv4h(uint32_t ipv4h_addr,
876 uint16_t ipv4_orport,
877 uint16_t ipv4_dirport,
878 const tor_addr_t *ipv6_addr,
879 uint16_t ipv6_orport,
880 uint16_t ipv6_dirport,
881 firewall_connection_t fw_connection,
882 int pref_only,
883 int pref_ipv6,
884 tor_addr_port_t* ap)
886 tor_addr_t ipv4_addr;
887 tor_addr_from_ipv4h(&ipv4_addr, ipv4h_addr);
888 return fascist_firewall_choose_address_base(&ipv4_addr, ipv4_orport,
889 ipv4_dirport, ipv6_addr,
890 ipv6_orport, ipv6_dirport,
891 fw_connection, pref_only,
892 pref_ipv6, ap);
895 /* The microdescriptor consensus has no IPv6 addresses in rs: they are in
896 * the microdescriptors. This means we can't rely on the node's IPv6 address
897 * until its microdescriptor is available (when using microdescs).
898 * But for bridges, rewrite_node_address_for_bridge() updates node->ri with
899 * the configured address, so we can trust bridge addresses.
900 * (Bridges could gain an IPv6 address if their microdescriptor arrives, but
901 * this will never be their preferred address: that is in the config.)
902 * Returns true if the node needs a microdescriptor for its IPv6 address, and
903 * false if the addresses in the node are already up-to-date.
905 static int
906 node_awaiting_ipv6(const or_options_t* options, const node_t *node)
908 tor_assert(node);
910 /* There's no point waiting for an IPv6 address if we'd never use it */
911 if (!fascist_firewall_use_ipv6(options)) {
912 return 0;
915 /* We are waiting if we_use_microdescriptors_for_circuits() and we have no
916 * md. Bridges have a ri based on their config. They would never use the
917 * address from their md, so there's no need to wait for it. */
918 return (!node->md && we_use_microdescriptors_for_circuits(options) &&
919 !node->ri);
922 /** Like fascist_firewall_choose_address_base(), but takes <b>rs</b>.
923 * Consults the corresponding node, then falls back to rs if node is NULL.
924 * This should only happen when there's no valid consensus, and rs doesn't
925 * correspond to a bridge client's bridge.
928 fascist_firewall_choose_address_rs(const routerstatus_t *rs,
929 firewall_connection_t fw_connection,
930 int pref_only, tor_addr_port_t* ap)
932 if (!rs) {
933 return 0;
936 tor_assert(ap);
938 const or_options_t *options = get_options();
939 const node_t *node = node_get_by_id(rs->identity_digest);
941 if (node && !node_awaiting_ipv6(options, node)) {
942 return fascist_firewall_choose_address_node(node, fw_connection, pref_only,
943 ap);
944 } else {
945 /* There's no node-specific IPv6 preference, so use the generic IPv6
946 * preference instead. */
947 int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
948 ? fascist_firewall_prefer_ipv6_orport(options)
949 : fascist_firewall_prefer_ipv6_dirport(options));
951 /* Assume IPv4 and IPv6 DirPorts are the same.
952 * Assume the IPv6 OR and Dir addresses are the same. */
953 return fascist_firewall_choose_address_ipv4h(rs->addr,
954 rs->or_port,
955 rs->dir_port,
956 &rs->ipv6_addr,
957 rs->ipv6_orport,
958 rs->dir_port,
959 fw_connection,
960 pref_only,
961 pref_ipv6,
962 ap);
966 /** Like fascist_firewall_choose_address_base(), but takes <b>node</b>, and
967 * looks up the node's IPv6 preference rather than taking an argument
968 * for pref_ipv6. */
970 fascist_firewall_choose_address_node(const node_t *node,
971 firewall_connection_t fw_connection,
972 int pref_only, tor_addr_port_t *ap)
974 if (!node) {
975 return 0;
978 node_assert_ok(node);
980 /* Calling fascist_firewall_choose_address_node() when the node is missing
981 * IPv6 information breaks IPv6-only clients.
982 * If the node is a hard-coded fallback directory or authority, call
983 * fascist_firewall_choose_address_rs() on the fake (hard-coded) routerstatus
984 * for the node.
985 * If it is not hard-coded, check that the node has a microdescriptor, full
986 * descriptor (routerinfo), or is one of our configured bridges before
987 * calling this function. */
988 if (BUG(node_awaiting_ipv6(get_options(), node))) {
989 return 0;
992 const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
993 ? node_ipv6_or_preferred(node)
994 : node_ipv6_dir_preferred(node));
996 tor_addr_port_t ipv4_or_ap;
997 node_get_prim_orport(node, &ipv4_or_ap);
998 tor_addr_port_t ipv4_dir_ap;
999 node_get_prim_dirport(node, &ipv4_dir_ap);
1001 tor_addr_port_t ipv6_or_ap;
1002 node_get_pref_ipv6_orport(node, &ipv6_or_ap);
1003 tor_addr_port_t ipv6_dir_ap;
1004 node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
1006 /* Assume the IPv6 OR and Dir addresses are the same. */
1007 return fascist_firewall_choose_address_base(&ipv4_or_ap.addr,
1008 ipv4_or_ap.port,
1009 ipv4_dir_ap.port,
1010 &ipv6_or_ap.addr,
1011 ipv6_or_ap.port,
1012 ipv6_dir_ap.port,
1013 fw_connection,
1014 pref_only,
1015 pref_ipv6_node,
1016 ap);
1019 /** Like fascist_firewall_choose_address_rs(), but takes <b>ds</b>. */
1021 fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
1022 firewall_connection_t fw_connection,
1023 int pref_only,
1024 tor_addr_port_t *ap)
1026 if (!ds) {
1027 return 0;
1030 /* A dir_server_t always has a fake_status. As long as it has the same
1031 * addresses/ports in both fake_status and dir_server_t, this works fine.
1032 * (See #17867.)
1033 * This function relies on fascist_firewall_choose_address_rs looking up the
1034 * node if it can, because that will get the latest info for the relay. */
1035 return fascist_firewall_choose_address_rs(&ds->fake_status, fw_connection,
1036 pref_only, ap);
1039 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
1040 * based on <b>dir_policy</b>. Else return 0.
1043 dir_policy_permits_address(const tor_addr_t *addr)
1045 return addr_policy_permits_tor_addr(addr, 1, dir_policy);
1048 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1049 * based on <b>socks_policy</b>. Else return 0.
1052 socks_policy_permits_address(const tor_addr_t *addr)
1054 return addr_policy_permits_tor_addr(addr, 1, socks_policy);
1057 /** Return true iff the address <b>addr</b> is in a country listed in the
1058 * case-insensitive list of country codes <b>cc_list</b>. */
1059 static int
1060 addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
1062 country_t country;
1063 const char *name;
1064 tor_addr_t tar;
1066 if (!cc_list)
1067 return 0;
1068 /* XXXXipv6 */
1069 tor_addr_from_ipv4h(&tar, addr);
1070 country = geoip_get_country_by_addr(&tar);
1071 name = geoip_get_country_name(country);
1072 return smartlist_contains_string_case(cc_list, name);
1075 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
1076 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
1079 authdir_policy_permits_address(uint32_t addr, uint16_t port)
1081 if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
1082 return 0;
1083 return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
1086 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
1087 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
1090 authdir_policy_valid_address(uint32_t addr, uint16_t port)
1092 if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
1093 return 0;
1094 return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
1097 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
1098 * based on <b>authdir_badexit_policy</b>. Else return 0.
1101 authdir_policy_badexit_address(uint32_t addr, uint16_t port)
1103 if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
1104 return 1;
1105 return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
1108 #define REJECT(arg) \
1109 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
1111 /** Config helper: If there's any problem with the policy configuration
1112 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
1113 * allocated description of the error. Else return 0. */
1115 validate_addr_policies(const or_options_t *options, char **msg)
1117 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
1118 * that the two can't go out of sync. */
1120 smartlist_t *addr_policy=NULL;
1121 *msg = NULL;
1123 if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
1124 REJECT("Error in ExitPolicy entry.");
1127 static int warned_about_exitrelay = 0;
1129 const int exitrelay_setting_is_auto = options->ExitRelay == -1;
1130 const int policy_accepts_something =
1131 ! (policy_is_reject_star(addr_policy, AF_INET, 1) &&
1132 policy_is_reject_star(addr_policy, AF_INET6, 1));
1134 if (server_mode(options) &&
1135 ! warned_about_exitrelay &&
1136 exitrelay_setting_is_auto &&
1137 policy_accepts_something) {
1138 /* Policy accepts something */
1139 warned_about_exitrelay = 1;
1140 log_warn(LD_CONFIG,
1141 "Tor is running as an exit relay%s. If you did not want this "
1142 "behavior, please set the ExitRelay option to 0. If you do "
1143 "want to run an exit Relay, please set the ExitRelay option "
1144 "to 1 to disable this warning, and for forward compatibility.",
1145 options->ExitPolicy == NULL ?
1146 " with the default exit policy" : "");
1147 if (options->ExitPolicy == NULL) {
1148 log_warn(LD_CONFIG,
1149 "In a future version of Tor, ExitRelay 0 may become the "
1150 "default when no ExitPolicy is given.");
1154 /* The rest of these calls *append* to addr_policy. So don't actually
1155 * use the results for anything other than checking if they parse! */
1156 if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
1157 REJECT("Error in DirPolicy entry.");
1158 if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
1159 REJECT("Error in SocksPolicy entry.");
1160 if (parse_addr_policy(options->AuthDirReject, &addr_policy,
1161 ADDR_POLICY_REJECT))
1162 REJECT("Error in AuthDirReject entry.");
1163 if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
1164 ADDR_POLICY_REJECT))
1165 REJECT("Error in AuthDirInvalid entry.");
1166 if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
1167 ADDR_POLICY_REJECT))
1168 REJECT("Error in AuthDirBadExit entry.");
1170 if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
1171 ADDR_POLICY_ACCEPT))
1172 REJECT("Error in ReachableAddresses entry.");
1173 if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
1174 ADDR_POLICY_ACCEPT))
1175 REJECT("Error in ReachableORAddresses entry.");
1176 if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
1177 ADDR_POLICY_ACCEPT))
1178 REJECT("Error in ReachableDirAddresses entry.");
1180 err:
1181 addr_policy_list_free(addr_policy);
1182 return *msg ? -1 : 0;
1183 #undef REJECT
1186 /** Parse <b>string</b> in the same way that the exit policy
1187 * is parsed, and put the processed version in *<b>policy</b>.
1188 * Ignore port specifiers.
1190 static int
1191 load_policy_from_option(config_line_t *config, const char *option_name,
1192 smartlist_t **policy,
1193 int assume_action)
1195 int r;
1196 int killed_any_ports = 0;
1197 addr_policy_list_free(*policy);
1198 *policy = NULL;
1199 r = parse_addr_policy(config, policy, assume_action);
1200 if (r < 0) {
1201 return -1;
1203 if (*policy) {
1204 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
1205 /* ports aren't used in these. */
1206 if (n->prt_min > 1 || n->prt_max != 65535) {
1207 addr_policy_t newp, *c;
1208 memcpy(&newp, n, sizeof(newp));
1209 newp.prt_min = 1;
1210 newp.prt_max = 65535;
1211 newp.is_canonical = 0;
1212 c = addr_policy_get_canonical_entry(&newp);
1213 SMARTLIST_REPLACE_CURRENT(*policy, n, c);
1214 addr_policy_free(n);
1215 killed_any_ports = 1;
1217 } SMARTLIST_FOREACH_END(n);
1219 if (killed_any_ports) {
1220 log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
1222 return 0;
1225 /** Set all policies based on <b>options</b>, which should have been validated
1226 * first by validate_addr_policies. */
1228 policies_parse_from_options(const or_options_t *options)
1230 int ret = 0;
1231 if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
1232 &socks_policy, -1) < 0)
1233 ret = -1;
1234 if (load_policy_from_option(options->DirPolicy, "DirPolicy",
1235 &dir_policy, -1) < 0)
1236 ret = -1;
1237 if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
1238 &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
1239 ret = -1;
1240 if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
1241 &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
1242 ret = -1;
1243 if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
1244 &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
1245 ret = -1;
1246 if (parse_reachable_addresses() < 0)
1247 ret = -1;
1248 return ret;
1251 /** Compare two provided address policy items, and renturn -1, 0, or 1
1252 * if the first is less than, equal to, or greater than the second. */
1253 static int
1254 single_addr_policy_eq(const addr_policy_t *a, const addr_policy_t *b)
1256 int r;
1257 #define CMP_FIELD(field) do { \
1258 if (a->field != b->field) { \
1259 return 0; \
1261 } while (0)
1262 CMP_FIELD(policy_type);
1263 CMP_FIELD(is_private);
1264 /* refcnt and is_canonical are irrelevant to equality,
1265 * they are hash table implementation details */
1266 if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
1267 return 0;
1268 CMP_FIELD(maskbits);
1269 CMP_FIELD(prt_min);
1270 CMP_FIELD(prt_max);
1271 #undef CMP_FIELD
1272 return 1;
1275 /** As single_addr_policy_eq, but compare every element of two policies.
1278 addr_policies_eq(const smartlist_t *a, const smartlist_t *b)
1280 int i;
1281 int len_a = a ? smartlist_len(a) : 0;
1282 int len_b = b ? smartlist_len(b) : 0;
1284 if (len_a != len_b)
1285 return 0;
1287 for (i = 0; i < len_a; ++i) {
1288 if (! single_addr_policy_eq(smartlist_get(a, i), smartlist_get(b, i)))
1289 return 0;
1292 return 1;
1295 /** Node in hashtable used to store address policy entries. */
1296 typedef struct policy_map_ent_t {
1297 HT_ENTRY(policy_map_ent_t) node;
1298 addr_policy_t *policy;
1299 } policy_map_ent_t;
1301 /* DOCDOC policy_root */
1302 static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
1304 /** Return true iff a and b are equal. */
1305 static inline int
1306 policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
1308 return single_addr_policy_eq(a->policy, b->policy);
1311 /** Return a hashcode for <b>ent</b> */
1312 static unsigned int
1313 policy_hash(const policy_map_ent_t *ent)
1315 const addr_policy_t *a = ent->policy;
1316 addr_policy_t aa;
1317 memset(&aa, 0, sizeof(aa));
1319 aa.prt_min = a->prt_min;
1320 aa.prt_max = a->prt_max;
1321 aa.maskbits = a->maskbits;
1322 aa.policy_type = a->policy_type;
1323 aa.is_private = a->is_private;
1325 if (a->is_private) {
1326 aa.is_private = 1;
1327 } else {
1328 tor_addr_copy_tight(&aa.addr, &a->addr);
1331 return (unsigned) siphash24g(&aa, sizeof(aa));
1334 HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
1335 policy_eq)
1336 HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
1337 policy_eq, 0.6, tor_reallocarray_, tor_free_)
1339 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
1340 * "canonical" copy of that addr_policy_t; the canonical copy is a single
1341 * reference-counted object. */
1342 addr_policy_t *
1343 addr_policy_get_canonical_entry(addr_policy_t *e)
1345 policy_map_ent_t search, *found;
1346 if (e->is_canonical)
1347 return e;
1349 search.policy = e;
1350 found = HT_FIND(policy_map, &policy_root, &search);
1351 if (!found) {
1352 found = tor_malloc_zero(sizeof(policy_map_ent_t));
1353 found->policy = tor_memdup(e, sizeof(addr_policy_t));
1354 found->policy->is_canonical = 1;
1355 found->policy->refcnt = 0;
1356 HT_INSERT(policy_map, &policy_root, found);
1359 tor_assert(single_addr_policy_eq(found->policy, e));
1360 ++found->policy->refcnt;
1361 return found->policy;
1364 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1365 * addr and port are both known. */
1366 static addr_policy_result_t
1367 compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
1368 const smartlist_t *policy)
1370 /* We know the address and port, and we know the policy, so we can just
1371 * compute an exact match. */
1372 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1373 if (tmpe->addr.family == AF_UNSPEC) {
1374 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1375 "matches other AF_UNSPEC addresses.");
1377 /* Address is known */
1378 if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1379 CMP_EXACT)) {
1380 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
1381 /* Exact match for the policy */
1382 return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
1383 ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
1386 } SMARTLIST_FOREACH_END(tmpe);
1388 /* accept all by default. */
1389 return ADDR_POLICY_ACCEPTED;
1392 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1393 * addr is known but port is not. */
1394 static addr_policy_result_t
1395 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
1396 const smartlist_t *policy)
1398 /* We look to see if there's a definite match. If so, we return that
1399 match's value, unless there's an intervening possible match that says
1400 something different. */
1401 int maybe_accept = 0, maybe_reject = 0;
1403 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1404 if (tmpe->addr.family == AF_UNSPEC) {
1405 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1406 "matches other AF_UNSPEC addresses.");
1408 if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1409 CMP_EXACT)) {
1410 if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
1411 /* Definitely matches, since it covers all ports. */
1412 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1413 /* If we already hit a clause that might trigger a 'reject', than we
1414 * can't be sure of this certain 'accept'.*/
1415 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1416 ADDR_POLICY_ACCEPTED;
1417 } else {
1418 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1419 ADDR_POLICY_REJECTED;
1421 } else {
1422 /* Might match. */
1423 if (tmpe->policy_type == ADDR_POLICY_REJECT)
1424 maybe_reject = 1;
1425 else
1426 maybe_accept = 1;
1429 } SMARTLIST_FOREACH_END(tmpe);
1431 /* accept all by default. */
1432 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1435 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1436 * port is known but address is not. */
1437 static addr_policy_result_t
1438 compare_unknown_tor_addr_to_addr_policy(uint16_t port,
1439 const smartlist_t *policy)
1441 /* We look to see if there's a definite match. If so, we return that
1442 match's value, unless there's an intervening possible match that says
1443 something different. */
1444 int maybe_accept = 0, maybe_reject = 0;
1446 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1447 if (tmpe->addr.family == AF_UNSPEC) {
1448 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1449 "matches other AF_UNSPEC addresses.");
1451 if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
1452 if (tmpe->maskbits == 0) {
1453 /* Definitely matches, since it covers all addresses. */
1454 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1455 /* If we already hit a clause that might trigger a 'reject', than we
1456 * can't be sure of this certain 'accept'.*/
1457 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1458 ADDR_POLICY_ACCEPTED;
1459 } else {
1460 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1461 ADDR_POLICY_REJECTED;
1463 } else {
1464 /* Might match. */
1465 if (tmpe->policy_type == ADDR_POLICY_REJECT)
1466 maybe_reject = 1;
1467 else
1468 maybe_accept = 1;
1471 } SMARTLIST_FOREACH_END(tmpe);
1473 /* accept all by default. */
1474 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1477 /** Decide whether a given addr:port is definitely accepted,
1478 * definitely rejected, probably accepted, or probably rejected by a
1479 * given policy. If <b>addr</b> is 0, we don't know the IP of the
1480 * target address. If <b>port</b> is 0, we don't know the port of the
1481 * target address. (At least one of <b>addr</b> and <b>port</b> must be
1482 * provided. If you want to know whether a policy would definitely reject
1483 * an unknown address:port, use policy_is_reject_star().)
1485 * We could do better by assuming that some ranges never match typical
1486 * addresses (127.0.0.1, and so on). But we'll try this for now.
1488 MOCK_IMPL(addr_policy_result_t,
1489 compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
1490 const smartlist_t *policy))
1492 if (!policy) {
1493 /* no policy? accept all. */
1494 return ADDR_POLICY_ACCEPTED;
1495 } else if (addr == NULL || tor_addr_is_null(addr)) {
1496 if (port == 0) {
1497 log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
1498 addr ? tor_addr_family(addr) : -1);
1499 return ADDR_POLICY_REJECTED;
1501 return compare_unknown_tor_addr_to_addr_policy(port, policy);
1502 } else if (port == 0) {
1503 return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
1504 } else {
1505 return compare_known_tor_addr_to_addr_policy(addr, port, policy);
1509 /** Return true iff the address policy <b>a</b> covers every case that
1510 * would be covered by <b>b</b>, so that a,b is redundant. */
1511 static int
1512 addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
1514 if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
1515 /* You can't cover a different family. */
1516 return 0;
1518 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
1519 * to "accept *:80". */
1520 if (a->maskbits > b->maskbits) {
1521 /* a has more fixed bits than b; it can't possibly cover b. */
1522 return 0;
1524 if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
1525 /* There's a fixed bit in a that's set differently in b. */
1526 return 0;
1528 return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
1531 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
1532 * that is, there exists an address/port that is covered by <b>a</b> that
1533 * is also covered by <b>b</b>.
1535 static int
1536 addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
1538 maskbits_t minbits;
1539 /* All the bits we care about are those that are set in both
1540 * netmasks. If they are equal in a and b's networkaddresses
1541 * then the networks intersect. If there is a difference,
1542 * then they do not. */
1543 if (a->maskbits < b->maskbits)
1544 minbits = a->maskbits;
1545 else
1546 minbits = b->maskbits;
1547 if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
1548 return 0;
1549 if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
1550 return 0;
1551 return 1;
1554 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
1556 STATIC void
1557 append_exit_policy_string(smartlist_t **policy, const char *more)
1559 config_line_t tmp;
1561 tmp.key = NULL;
1562 tmp.value = (char*) more;
1563 tmp.next = NULL;
1564 if (parse_addr_policy(&tmp, policy, -1)<0) {
1565 log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
1569 /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
1570 void
1571 addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
1573 tor_assert(dest);
1574 tor_assert(addr);
1576 addr_policy_t p, *add;
1577 memset(&p, 0, sizeof(p));
1578 p.policy_type = ADDR_POLICY_REJECT;
1579 p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
1580 tor_addr_copy(&p.addr, addr);
1581 p.prt_min = 1;
1582 p.prt_max = 65535;
1584 add = addr_policy_get_canonical_entry(&p);
1585 if (!*dest)
1586 *dest = smartlist_new();
1587 smartlist_add(*dest, add);
1588 log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
1589 fmt_addr(addr));
1592 /* Is addr public for the purposes of rejection? */
1593 static int
1594 tor_addr_is_public_for_reject(const tor_addr_t *addr)
1596 return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
1597 && !tor_addr_is_multicast(addr));
1600 /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
1601 * Filter the address, only adding an IPv4 reject rule if ipv4_rules
1602 * is true, and similarly for ipv6_rules. Check each address returns true for
1603 * tor_addr_is_public_for_reject before adding it.
1605 static void
1606 addr_policy_append_reject_addr_filter(smartlist_t **dest,
1607 const tor_addr_t *addr,
1608 int ipv4_rules,
1609 int ipv6_rules)
1611 tor_assert(dest);
1612 tor_assert(addr);
1614 /* Only reject IP addresses which are public */
1615 if (tor_addr_is_public_for_reject(addr)) {
1617 /* Reject IPv4 addresses and IPv6 addresses based on the filters */
1618 int is_ipv4 = tor_addr_is_v4(addr);
1619 if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
1620 addr_policy_append_reject_addr(dest, addr);
1625 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1626 * list as needed. */
1627 void
1628 addr_policy_append_reject_addr_list(smartlist_t **dest,
1629 const smartlist_t *addrs)
1631 tor_assert(dest);
1632 tor_assert(addrs);
1634 SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1635 addr_policy_append_reject_addr(dest, addr);
1636 } SMARTLIST_FOREACH_END(addr);
1639 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1640 * list as needed. Filter using */
1641 static void
1642 addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
1643 const smartlist_t *addrs,
1644 int ipv4_rules,
1645 int ipv6_rules)
1647 tor_assert(dest);
1648 tor_assert(addrs);
1650 SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1651 addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
1652 } SMARTLIST_FOREACH_END(addr);
1655 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
1656 static void
1657 exit_policy_remove_redundancies(smartlist_t *dest)
1659 addr_policy_t *ap, *tmp;
1660 int i, j;
1662 /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
1665 int kill_v4=0, kill_v6=0;
1666 for (i = 0; i < smartlist_len(dest); ++i) {
1667 sa_family_t family;
1668 ap = smartlist_get(dest, i);
1669 family = tor_addr_family(&ap->addr);
1670 if ((family == AF_INET && kill_v4) ||
1671 (family == AF_INET6 && kill_v6)) {
1672 smartlist_del_keeporder(dest, i--);
1673 addr_policy_free(ap);
1674 continue;
1677 if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
1678 /* This is a catch-all line -- later lines are unreachable. */
1679 if (family == AF_INET) {
1680 kill_v4 = 1;
1681 } else if (family == AF_INET6) {
1682 kill_v6 = 1;
1688 /* Step two: for every entry, see if there's a redundant entry
1689 * later on, and remove it. */
1690 for (i = 0; i < smartlist_len(dest)-1; ++i) {
1691 ap = smartlist_get(dest, i);
1692 for (j = i+1; j < smartlist_len(dest); ++j) {
1693 tmp = smartlist_get(dest, j);
1694 tor_assert(j > i);
1695 if (addr_policy_covers(ap, tmp)) {
1696 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1697 policy_write_item(p1, sizeof(p1), tmp, 0);
1698 policy_write_item(p2, sizeof(p2), ap, 0);
1699 log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
1700 "redundant by %s (%d).", p1, j, p2, i);
1701 smartlist_del_keeporder(dest, j--);
1702 addr_policy_free(tmp);
1707 /* Step three: for every entry A, see if there's an entry B making this one
1708 * redundant later on. This is the case if A and B are of the same type
1709 * (accept/reject), A is a subset of B, and there is no other entry of
1710 * different type in between those two that intersects with A.
1712 * Anybody want to double-check the logic here? XXX
1714 for (i = 0; i < smartlist_len(dest)-1; ++i) {
1715 ap = smartlist_get(dest, i);
1716 for (j = i+1; j < smartlist_len(dest); ++j) {
1717 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
1718 // // decreases.
1719 tmp = smartlist_get(dest, j);
1720 if (ap->policy_type != tmp->policy_type) {
1721 if (addr_policy_intersects(ap, tmp))
1722 break;
1723 } else { /* policy_types are equal. */
1724 if (addr_policy_covers(tmp, ap)) {
1725 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1726 policy_write_item(p1, sizeof(p1), ap, 0);
1727 policy_write_item(p2, sizeof(p2), tmp, 0);
1728 log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
1729 "covered by %s.", p1, p2);
1730 smartlist_del_keeporder(dest, i--);
1731 addr_policy_free(ap);
1732 break;
1739 /** Reject private helper for policies_parse_exit_policy_internal: rejects
1740 * publicly routable addresses on this exit relay.
1742 * Add reject entries to the linked list *<b>dest</b>:
1743 * <ul>
1744 * <li>if configured_addresses is non-NULL, add entries that reject each
1745 * tor_addr_t in the list as a destination.
1746 * <li>if reject_interface_addresses is true, add entries that reject each
1747 * public IPv4 and IPv6 address of each interface on this machine.
1748 * <li>if reject_configured_port_addresses is true, add entries that reject
1749 * each IPv4 and IPv6 address configured for a port.
1750 * </ul>
1752 * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
1753 * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
1754 * false.)
1756 * The list in <b>dest</b> is created as needed.
1758 void
1759 policies_parse_exit_policy_reject_private(
1760 smartlist_t **dest,
1761 int ipv6_exit,
1762 const smartlist_t *configured_addresses,
1763 int reject_interface_addresses,
1764 int reject_configured_port_addresses)
1766 tor_assert(dest);
1768 /* Reject configured addresses, if they are from public netblocks. */
1769 if (configured_addresses) {
1770 addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
1771 1, ipv6_exit);
1774 /* Reject configured port addresses, if they are from public netblocks. */
1775 if (reject_configured_port_addresses) {
1776 const smartlist_t *port_addrs = get_configured_ports();
1778 SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
1780 /* Only reject port IP addresses, not port unix sockets */
1781 if (!port->is_unix_addr) {
1782 addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
1784 } SMARTLIST_FOREACH_END(port);
1787 /* Reject local addresses from public netblocks on any interface. */
1788 if (reject_interface_addresses) {
1789 smartlist_t *public_addresses = NULL;
1791 /* Reject public IPv4 addresses on any interface */
1792 public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
1793 addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
1794 free_interface_address6_list(public_addresses);
1796 /* Don't look for IPv6 addresses if we're configured as IPv4-only */
1797 if (ipv6_exit) {
1798 /* Reject public IPv6 addresses on any interface */
1799 public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
1800 addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
1801 free_interface_address6_list(public_addresses);
1805 /* If addresses were added multiple times, remove all but one of them. */
1806 if (*dest) {
1807 exit_policy_remove_redundancies(*dest);
1812 * Iterate through <b>policy</b> looking for redundant entries. Log a
1813 * warning message with the first redundant entry, if any is found.
1815 static void
1816 policies_log_first_redundant_entry(const smartlist_t *policy)
1818 int found_final_effective_entry = 0;
1819 int first_redundant_entry = 0;
1820 tor_assert(policy);
1821 SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
1822 sa_family_t family;
1823 int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
1824 const int i = p_sl_idx;
1826 /* Look for accept/reject *[4|6|]:* entires */
1827 if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
1828 family = tor_addr_family(&p->addr);
1829 /* accept/reject *:* may have already been expanded into
1830 * accept/reject *4:*,accept/reject *6:*
1831 * But handle both forms.
1833 if (family == AF_INET || family == AF_UNSPEC) {
1834 found_ipv4_wildcard = 1;
1836 if (family == AF_INET6 || family == AF_UNSPEC) {
1837 found_ipv6_wildcard = 1;
1841 /* We also find accept *4:*,reject *6:* ; and
1842 * accept *4:*,<other policies>,accept *6:* ; and similar.
1843 * That's ok, because they make any subsequent entries redundant. */
1844 if (found_ipv4_wildcard && found_ipv6_wildcard) {
1845 found_final_effective_entry = 1;
1846 /* if we're not on the final entry in the list */
1847 if (i < smartlist_len(policy) - 1) {
1848 first_redundant_entry = i + 1;
1850 break;
1852 } SMARTLIST_FOREACH_END(p);
1854 /* Work out if there are redundant trailing entries in the policy list */
1855 if (found_final_effective_entry && first_redundant_entry > 0) {
1856 const addr_policy_t *p;
1857 /* Longest possible policy is
1858 * "accept6 ffff:ffff:..255/128:10000-65535",
1859 * which contains a max-length IPv6 address, plus 24 characters. */
1860 char line[TOR_ADDR_BUF_LEN + 32];
1862 tor_assert(first_redundant_entry < smartlist_len(policy));
1863 p = smartlist_get(policy, first_redundant_entry);
1864 /* since we've already parsed the policy into an addr_policy_t struct,
1865 * we might not log exactly what the user typed in */
1866 policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
1867 log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
1868 "redundant, as it follows accept/reject *:* rules for both "
1869 "IPv4 and IPv6. They will be removed from the exit policy. (Use "
1870 "accept/reject *:* as the last entry in any exit policy.)",
1871 line);
1875 #define DEFAULT_EXIT_POLICY \
1876 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
1877 "reject *:563,reject *:1214,reject *:4661-4666," \
1878 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
1880 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
1882 * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
1884 * If <b>configured_addresses</b> contains addresses:
1885 * - prepend entries that reject the addresses in this list. These may be the
1886 * advertised relay addresses and/or the outbound bind addresses,
1887 * depending on the ExitPolicyRejectPrivate and
1888 * ExitPolicyRejectLocalInterfaces settings.
1889 * If <b>rejectprivate</b> is true:
1890 * - prepend "reject private:*" to the policy.
1891 * If <b>reject_interface_addresses</b> is true:
1892 * - prepend entries that reject publicly routable interface addresses on
1893 * this exit relay by calling policies_parse_exit_policy_reject_private
1894 * If <b>reject_configured_port_addresses</b> is true:
1895 * - prepend entries that reject all configured port addresses
1897 * If cfg doesn't end in an absolute accept or reject and if
1898 * <b>add_default_policy</b> is true, add the default exit
1899 * policy afterwards.
1901 * Return -1 if we can't parse cfg, else return 0.
1903 * This function is used to parse the exit policy from our torrc. For
1904 * the functions used to parse the exit policy from a router descriptor,
1905 * see router_add_exit_policy.
1907 static int
1908 policies_parse_exit_policy_internal(config_line_t *cfg,
1909 smartlist_t **dest,
1910 int ipv6_exit,
1911 int rejectprivate,
1912 const smartlist_t *configured_addresses,
1913 int reject_interface_addresses,
1914 int reject_configured_port_addresses,
1915 int add_default_policy)
1917 if (!ipv6_exit) {
1918 append_exit_policy_string(dest, "reject *6:*");
1920 if (rejectprivate) {
1921 /* Reject IPv4 and IPv6 reserved private netblocks */
1922 append_exit_policy_string(dest, "reject private:*");
1925 /* Consider rejecting IPv4 and IPv6 advertised relay addresses, outbound bind
1926 * addresses, publicly routable addresses, and configured port addresses
1927 * on this exit relay */
1928 policies_parse_exit_policy_reject_private(dest, ipv6_exit,
1929 configured_addresses,
1930 reject_interface_addresses,
1931 reject_configured_port_addresses);
1933 if (parse_addr_policy(cfg, dest, -1))
1934 return -1;
1936 /* Before we add the default policy and final rejects, check to see if
1937 * there are any lines after accept *:* or reject *:*. These lines have no
1938 * effect, and are most likely an error. */
1939 policies_log_first_redundant_entry(*dest);
1941 if (add_default_policy) {
1942 append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
1943 } else {
1944 append_exit_policy_string(dest, "reject *4:*");
1945 append_exit_policy_string(dest, "reject *6:*");
1947 exit_policy_remove_redundancies(*dest);
1949 return 0;
1952 /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
1954 * Prepend an entry that rejects all IPv6 destinations unless
1955 * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
1957 * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
1958 * - prepend an entry that rejects all destinations in all netblocks
1959 * reserved for private use.
1960 * - prepend entries that reject the advertised relay addresses in
1961 * configured_addresses
1962 * If <b>EXIT_POLICY_REJECT_LOCAL_INTERFACES</b> bit is set in <b>options</b>:
1963 * - prepend entries that reject publicly routable addresses on this exit
1964 * relay by calling policies_parse_exit_policy_internal
1965 * - prepend entries that reject the outbound bind addresses in
1966 * configured_addresses
1967 * - prepend entries that reject all configured port addresses
1969 * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
1970 * default exit policy entries to <b>result</b> smartlist.
1973 policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
1974 exit_policy_parser_cfg_t options,
1975 const smartlist_t *configured_addresses)
1977 int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
1978 int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
1979 int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
1980 int reject_local_interfaces = (options &
1981 EXIT_POLICY_REJECT_LOCAL_INTERFACES) ? 1 : 0;
1983 return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
1984 reject_private,
1985 configured_addresses,
1986 reject_local_interfaces,
1987 reject_local_interfaces,
1988 add_default);
1991 /** Helper function that adds a copy of addr to a smartlist as long as it is
1992 * non-NULL and not tor_addr_is_null().
1994 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
1996 static void
1997 policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
1999 if (addr && !tor_addr_is_null(addr)) {
2000 tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
2001 tor_addr_copy(addr_copy, addr);
2002 smartlist_add(addr_list, addr_copy);
2006 /** Helper function that adds ipv4h_addr to a smartlist as a tor_addr_t *,
2007 * as long as it is not tor_addr_is_null(), by converting it to a tor_addr_t
2008 * and passing it to policies_add_addr_to_smartlist.
2010 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2012 static void
2013 policies_copy_ipv4h_to_smartlist(smartlist_t *addr_list, uint32_t ipv4h_addr)
2015 if (ipv4h_addr) {
2016 tor_addr_t ipv4_tor_addr;
2017 tor_addr_from_ipv4h(&ipv4_tor_addr, ipv4h_addr);
2018 policies_copy_addr_to_smartlist(addr_list, &ipv4_tor_addr);
2022 /** Helper function that adds copies of or_options->OutboundBindAddresses
2023 * to a smartlist as tor_addr_t *, as long as or_options is non-NULL, and
2024 * the addresses are not tor_addr_is_null(), by passing them to
2025 * policies_add_addr_to_smartlist.
2027 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2029 static void
2030 policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
2031 const or_options_t *or_options)
2033 if (or_options) {
2034 for (int i=0;i<OUTBOUND_ADDR_MAX;i++) {
2035 for (int j=0;j<2;j++) {
2036 if (!tor_addr_is_null(&or_options->OutboundBindAddresses[i][j])) {
2037 policies_copy_addr_to_smartlist(addr_list,
2038 &or_options->OutboundBindAddresses[i][j]);
2045 /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
2046 * smartlist.
2047 * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
2048 * rejects all IPv6 destinations.
2050 * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
2051 * - prepend an entry that rejects all destinations in all netblocks reserved
2052 * for private use.
2053 * - if local_address is non-zero, treat it as a host-order IPv4 address, and
2054 * add it to the list of configured addresses.
2055 * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
2056 * to the list of configured addresses.
2057 * If <b>or_options->ExitPolicyRejectLocalInterfaces</b> is true:
2058 * - if or_options->OutboundBindAddresses[][0] (=IPv4) is not the null
2059 * tor_addr_t, add it to the list of configured addresses.
2060 * - if or_options->OutboundBindAddresses[][1] (=IPv6) is not the null
2061 * tor_addr_t, add it to the list of configured addresses.
2063 * If <b>or_options->BridgeRelay</b> is false, append entries of default
2064 * Tor exit policy into <b>result</b> smartlist.
2066 * If or_options->ExitRelay is false, then make our exit policy into
2067 * "reject *:*" regardless.
2070 policies_parse_exit_policy_from_options(const or_options_t *or_options,
2071 uint32_t local_address,
2072 const tor_addr_t *ipv6_local_address,
2073 smartlist_t **result)
2075 exit_policy_parser_cfg_t parser_cfg = 0;
2076 smartlist_t *configured_addresses = NULL;
2077 int rv = 0;
2079 /* Short-circuit for non-exit relays */
2080 if (or_options->ExitRelay == 0) {
2081 append_exit_policy_string(result, "reject *4:*");
2082 append_exit_policy_string(result, "reject *6:*");
2083 return 0;
2086 configured_addresses = smartlist_new();
2088 /* Configure the parser */
2089 if (or_options->IPv6Exit) {
2090 parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
2093 if (or_options->ExitPolicyRejectPrivate) {
2094 parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
2097 if (!or_options->BridgeRelay) {
2098 parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
2101 if (or_options->ExitPolicyRejectLocalInterfaces) {
2102 parser_cfg |= EXIT_POLICY_REJECT_LOCAL_INTERFACES;
2105 /* Copy the configured addresses into the tor_addr_t* list */
2106 if (or_options->ExitPolicyRejectPrivate) {
2107 policies_copy_ipv4h_to_smartlist(configured_addresses, local_address);
2108 policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
2111 if (or_options->ExitPolicyRejectLocalInterfaces) {
2112 policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2113 or_options);
2116 rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
2117 configured_addresses);
2119 SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2120 smartlist_free(configured_addresses);
2122 return rv;
2125 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
2126 * *<b>dest</b> as needed. */
2127 void
2128 policies_exit_policy_append_reject_star(smartlist_t **dest)
2130 append_exit_policy_string(dest, "reject *4:*");
2131 append_exit_policy_string(dest, "reject *6:*");
2134 /** Replace the exit policy of <b>node</b> with reject *:* */
2135 void
2136 policies_set_node_exitpolicy_to_reject_all(node_t *node)
2138 node->rejects_all = 1;
2141 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
2142 * allows exiting to <b>port</b>. Otherwise, return 0. */
2143 static int
2144 exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
2146 uint32_t mask, ip, i;
2147 /* Is this /8 rejected (1), or undecided (0)? */
2148 char subnet_status[256];
2150 memset(subnet_status, 0, sizeof(subnet_status));
2151 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2152 if (tor_addr_family(&p->addr) != AF_INET)
2153 continue; /* IPv4 only for now */
2154 if (p->prt_min > port || p->prt_max < port)
2155 continue; /* Doesn't cover our port. */
2156 mask = 0;
2157 tor_assert(p->maskbits <= 32);
2159 if (p->maskbits)
2160 mask = UINT32_MAX<<(32-p->maskbits);
2161 ip = tor_addr_to_ipv4h(&p->addr);
2163 /* Calculate the first and last subnet that this exit policy touches
2164 * and set it as loop boundaries. */
2165 for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
2166 tor_addr_t addr;
2167 if (subnet_status[i] != 0)
2168 continue; /* We already reject some part of this /8 */
2169 tor_addr_from_ipv4h(&addr, i<<24);
2170 if (tor_addr_is_internal(&addr, 0) &&
2171 !get_options()->DirAllowPrivateAddresses) {
2172 continue; /* Local or non-routable addresses */
2174 if (p->policy_type == ADDR_POLICY_ACCEPT) {
2175 if (p->maskbits > 8)
2176 continue; /* Narrower than a /8. */
2177 /* We found an allowed subnet of at least size /8. Done
2178 * for this port! */
2179 return 1;
2180 } else if (p->policy_type == ADDR_POLICY_REJECT) {
2181 subnet_status[i] = 1;
2184 } SMARTLIST_FOREACH_END(p);
2185 return 0;
2188 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
2189 * it allows exit to at least one /8 address space for at least
2190 * two of ports 80, 443, and 6667. */
2192 exit_policy_is_general_exit(smartlist_t *policy)
2194 static const int ports[] = { 80, 443, 6667 };
2195 int n_allowed = 0;
2196 int i;
2197 if (!policy) /*XXXX disallow NULL policies? */
2198 return 0;
2200 for (i = 0; i < 3; ++i) {
2201 n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
2203 return n_allowed >= 2;
2206 /** Return false if <b>policy</b> might permit access to some addr:port;
2207 * otherwise if we are certain it rejects everything, return true. If no
2208 * part of <b>policy</b> matches, return <b>default_reject</b>.
2209 * NULL policies are allowed, and treated as empty. */
2211 policy_is_reject_star(const smartlist_t *policy, sa_family_t family,
2212 int default_reject)
2214 if (!policy)
2215 return default_reject;
2216 SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
2217 if (p->policy_type == ADDR_POLICY_ACCEPT &&
2218 (tor_addr_family(&p->addr) == family ||
2219 tor_addr_family(&p->addr) == AF_UNSPEC)) {
2220 return 0;
2221 } else if (p->policy_type == ADDR_POLICY_REJECT &&
2222 p->prt_min <= 1 && p->prt_max == 65535 &&
2223 p->maskbits == 0 &&
2224 (tor_addr_family(&p->addr) == family ||
2225 tor_addr_family(&p->addr) == AF_UNSPEC)) {
2226 return 1;
2228 } SMARTLIST_FOREACH_END(p);
2229 return default_reject;
2232 /** Write a single address policy to the buf_len byte buffer at buf. Return
2233 * the number of characters written, or -1 on failure. */
2235 policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
2236 int format_for_desc)
2238 size_t written = 0;
2239 char addrbuf[TOR_ADDR_BUF_LEN];
2240 const char *addrpart;
2241 int result;
2242 const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
2243 const sa_family_t family = tor_addr_family(&policy->addr);
2244 const int is_ip6 = (family == AF_INET6);
2246 tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
2248 /* write accept/reject 1.2.3.4 */
2249 if (policy->is_private) {
2250 addrpart = "private";
2251 } else if (policy->maskbits == 0) {
2252 if (format_for_desc)
2253 addrpart = "*";
2254 else if (family == AF_INET6)
2255 addrpart = "*6";
2256 else if (family == AF_INET)
2257 addrpart = "*4";
2258 else
2259 addrpart = "*";
2260 } else {
2261 addrpart = addrbuf;
2264 result = tor_snprintf(buf, buflen, "%s%s %s",
2265 is_accept ? "accept" : "reject",
2266 (is_ip6&&format_for_desc)?"6":"",
2267 addrpart);
2268 if (result < 0)
2269 return -1;
2270 written += strlen(buf);
2271 /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
2272 the mask is 0, we already wrote "*". */
2273 if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
2274 if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
2275 return -1;
2276 written += strlen(buf+written);
2278 if (policy->prt_min <= 1 && policy->prt_max == 65535) {
2279 /* There is no port set; write ":*" */
2280 if (written+4 > buflen)
2281 return -1;
2282 strlcat(buf+written, ":*", buflen-written);
2283 written += 2;
2284 } else if (policy->prt_min == policy->prt_max) {
2285 /* There is only one port; write ":80". */
2286 result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
2287 if (result<0)
2288 return -1;
2289 written += result;
2290 } else {
2291 /* There is a range of ports; write ":79-80". */
2292 result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
2293 policy->prt_min, policy->prt_max);
2294 if (result<0)
2295 return -1;
2296 written += result;
2298 if (written < buflen)
2299 buf[written] = '\0';
2300 else
2301 return -1;
2303 return (int)written;
2306 /** Create a new exit policy summary, initially only with a single
2307 * port 1-64k item */
2308 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
2309 * RB-tree if that turns out to matter. */
2310 static smartlist_t *
2311 policy_summary_create(void)
2313 smartlist_t *summary;
2314 policy_summary_item_t* item;
2316 item = tor_malloc_zero(sizeof(policy_summary_item_t));
2317 item->prt_min = 1;
2318 item->prt_max = 65535;
2319 item->reject_count = 0;
2320 item->accepted = 0;
2322 summary = smartlist_new();
2323 smartlist_add(summary, item);
2325 return summary;
2328 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
2329 * The current item is changed to end at new-starts - 1, the new item
2330 * copies reject_count and accepted from the old item,
2331 * starts at new_starts and ends at the port where the original item
2332 * previously ended.
2334 static policy_summary_item_t*
2335 policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
2337 policy_summary_item_t* new;
2339 new = tor_malloc_zero(sizeof(policy_summary_item_t));
2340 new->prt_min = new_starts;
2341 new->prt_max = old->prt_max;
2342 new->reject_count = old->reject_count;
2343 new->accepted = old->accepted;
2345 old->prt_max = new_starts-1;
2347 tor_assert(old->prt_min <= old->prt_max);
2348 tor_assert(new->prt_min <= new->prt_max);
2349 return new;
2352 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
2353 * my immortal soul, he can clean it up himself. */
2354 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
2356 #define IPV4_BITS (32)
2357 /* Every IPv4 address is counted as one rejection */
2358 #define REJECT_CUTOFF_SCALE_IPV4 (0)
2359 /* Ports are rejected in an IPv4 summary if they are rejected in more than two
2360 * IPv4 /8 address blocks */
2361 #define REJECT_CUTOFF_COUNT_IPV4 (U64_LITERAL(1) << \
2362 (IPV4_BITS - REJECT_CUTOFF_SCALE_IPV4 - 7))
2364 #define IPV6_BITS (128)
2365 /* IPv6 /64s are counted as one rejection, anything smaller is ignored */
2366 #define REJECT_CUTOFF_SCALE_IPV6 (64)
2367 /* Ports are rejected in an IPv6 summary if they are rejected in more than one
2368 * IPv6 /16 address block.
2369 * This is rougly equivalent to the IPv4 cutoff, as only five IPv6 /12s (and
2370 * some scattered smaller blocks) have been allocated to the RIRs.
2371 * Network providers are typically allocated one or more IPv6 /32s.
2373 #define REJECT_CUTOFF_COUNT_IPV6 (U64_LITERAL(1) << \
2374 (IPV6_BITS - REJECT_CUTOFF_SCALE_IPV6 - 16))
2376 /** Split an exit policy summary so that prt_min and prt_max
2377 * fall at exactly the start and end of an item respectively.
2379 static int
2380 policy_summary_split(smartlist_t *summary,
2381 uint16_t prt_min, uint16_t prt_max)
2383 int start_at_index;
2385 int i = 0;
2387 while (AT(i)->prt_max < prt_min)
2388 i++;
2389 if (AT(i)->prt_min != prt_min) {
2390 policy_summary_item_t* new_item;
2391 new_item = policy_summary_item_split(AT(i), prt_min);
2392 smartlist_insert(summary, i+1, new_item);
2393 i++;
2395 start_at_index = i;
2397 while (AT(i)->prt_max < prt_max)
2398 i++;
2399 if (AT(i)->prt_max != prt_max) {
2400 policy_summary_item_t* new_item;
2401 new_item = policy_summary_item_split(AT(i), prt_max+1);
2402 smartlist_insert(summary, i+1, new_item);
2405 return start_at_index;
2408 /** Mark port ranges as accepted if they are below the reject_count for family
2410 static void
2411 policy_summary_accept(smartlist_t *summary,
2412 uint16_t prt_min, uint16_t prt_max,
2413 sa_family_t family)
2415 tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2416 uint64_t family_reject_count = ((family == AF_INET) ?
2417 REJECT_CUTOFF_COUNT_IPV4 :
2418 REJECT_CUTOFF_COUNT_IPV6);
2420 int i = policy_summary_split(summary, prt_min, prt_max);
2421 while (i < smartlist_len(summary) &&
2422 AT(i)->prt_max <= prt_max) {
2423 if (!AT(i)->accepted &&
2424 AT(i)->reject_count <= family_reject_count)
2425 AT(i)->accepted = 1;
2426 i++;
2428 tor_assert(i < smartlist_len(summary) || prt_max==65535);
2431 /** Count the number of addresses in a network in family with prefixlen
2432 * maskbits against the given portrange. */
2433 static void
2434 policy_summary_reject(smartlist_t *summary,
2435 maskbits_t maskbits,
2436 uint16_t prt_min, uint16_t prt_max,
2437 sa_family_t family)
2439 tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2441 int i = policy_summary_split(summary, prt_min, prt_max);
2443 /* The length of a single address mask */
2444 int addrbits = (family == AF_INET) ? IPV4_BITS : IPV6_BITS;
2445 tor_assert_nonfatal_once(addrbits >= maskbits);
2447 /* We divide IPv6 address counts by (1 << scale) to keep them in a uint64_t
2449 int scale = ((family == AF_INET) ?
2450 REJECT_CUTOFF_SCALE_IPV4 :
2451 REJECT_CUTOFF_SCALE_IPV6);
2453 tor_assert_nonfatal_once(addrbits >= scale);
2454 if (maskbits > (addrbits - scale)) {
2455 tor_assert_nonfatal_once(family == AF_INET6);
2456 /* The address range is so small, we'd need billions of them to reach the
2457 * rejection limit. So we ignore this range in the reject count. */
2458 return;
2461 uint64_t count = 0;
2462 if (addrbits - scale - maskbits >= 64) {
2463 tor_assert_nonfatal_once(family == AF_INET6);
2464 /* The address range is so large, it's an automatic rejection for all ports
2465 * in the range. */
2466 count = UINT64_MAX;
2467 } else {
2468 count = (U64_LITERAL(1) << (addrbits - scale - maskbits));
2470 tor_assert_nonfatal_once(count > 0);
2471 while (i < smartlist_len(summary) &&
2472 AT(i)->prt_max <= prt_max) {
2473 if (AT(i)->reject_count <= UINT64_MAX - count) {
2474 AT(i)->reject_count += count;
2475 } else {
2476 /* IPv4 would require a 4-billion address redundant policy to get here,
2477 * but IPv6 just needs to have ::/0 */
2478 if (family == AF_INET) {
2479 tor_assert_nonfatal_unreached_once();
2481 /* If we do get here, use saturating arithmetic */
2482 AT(i)->reject_count = UINT64_MAX;
2484 i++;
2486 tor_assert(i < smartlist_len(summary) || prt_max==65535);
2489 /** Add a single exit policy item to our summary:
2491 * If it is an accept, ignore it unless it is for all IP addresses
2492 * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
2493 * policy_summary_accept().
2495 * If it is a reject, ignore it if it is about one of the private
2496 * networks. Otherwise call policy_summary_reject().
2498 static void
2499 policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
2501 if (p->policy_type == ADDR_POLICY_ACCEPT) {
2502 if (p->maskbits == 0) {
2503 policy_summary_accept(summary, p->prt_min, p->prt_max, p->addr.family);
2505 } else if (p->policy_type == ADDR_POLICY_REJECT) {
2507 int is_private = 0;
2508 int i;
2509 for (i = 0; private_nets[i]; ++i) {
2510 tor_addr_t addr;
2511 maskbits_t maskbits;
2512 if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
2513 &maskbits, NULL, NULL)<0) {
2514 tor_assert(0);
2516 if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
2517 p->maskbits == maskbits) {
2518 is_private = 1;
2519 break;
2523 if (!is_private) {
2524 policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max,
2525 p->addr.family);
2527 } else
2528 tor_assert(0);
2531 /** Create a string representing a summary for an exit policy.
2532 * The summary will either be an "accept" plus a comma-separated list of port
2533 * ranges or a "reject" plus port-ranges, depending on which is shorter.
2535 * If no exits are allowed at all then "reject 1-65535" is returned. If no
2536 * ports are blocked instead of "reject " we return "accept 1-65535". (These
2537 * are an exception to the shorter-representation-wins rule).
2539 char *
2540 policy_summarize(smartlist_t *policy, sa_family_t family)
2542 smartlist_t *summary = policy_summary_create();
2543 smartlist_t *accepts, *rejects;
2544 int i, last, start_prt;
2545 size_t accepts_len, rejects_len;
2546 char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
2547 const char *prefix;
2549 tor_assert(policy);
2551 /* Create the summary list */
2552 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2553 sa_family_t f = tor_addr_family(&p->addr);
2554 if (f != AF_INET && f != AF_INET6) {
2555 log_warn(LD_BUG, "Weird family when summarizing address policy");
2557 if (f != family)
2558 continue;
2559 policy_summary_add_item(summary, p);
2560 } SMARTLIST_FOREACH_END(p);
2562 /* Now create two lists of strings, one for accepted and one
2563 * for rejected ports. We take care to merge ranges so that
2564 * we avoid getting stuff like "1-4,5-9,10", instead we want
2565 * "1-10"
2567 i = 0;
2568 start_prt = 1;
2569 accepts = smartlist_new();
2570 rejects = smartlist_new();
2571 while (1) {
2572 last = i == smartlist_len(summary)-1;
2573 if (last ||
2574 AT(i)->accepted != AT(i+1)->accepted) {
2575 char buf[POLICY_BUF_LEN];
2577 if (start_prt == AT(i)->prt_max)
2578 tor_snprintf(buf, sizeof(buf), "%d", start_prt);
2579 else
2580 tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
2582 if (AT(i)->accepted)
2583 smartlist_add_strdup(accepts, buf);
2584 else
2585 smartlist_add_strdup(rejects, buf);
2587 if (last)
2588 break;
2590 start_prt = AT(i+1)->prt_min;
2592 i++;
2595 /* Figure out which of the two stringlists will be shorter and use
2596 * that to build the result
2598 if (smartlist_len(accepts) == 0) { /* no exits at all */
2599 result = tor_strdup("reject 1-65535");
2600 goto cleanup;
2602 if (smartlist_len(rejects) == 0) { /* no rejects at all */
2603 result = tor_strdup("accept 1-65535");
2604 goto cleanup;
2607 accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
2608 rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
2610 if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
2611 accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
2612 char *c;
2613 shorter_str = accepts_str;
2614 prefix = "accept";
2616 c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
2617 while (*c != ',' && c >= shorter_str)
2618 c--;
2619 tor_assert(c >= shorter_str);
2620 tor_assert(*c == ',');
2621 *c = '\0';
2623 } else if (rejects_len < accepts_len) {
2624 shorter_str = rejects_str;
2625 prefix = "reject";
2626 } else {
2627 shorter_str = accepts_str;
2628 prefix = "accept";
2631 tor_asprintf(&result, "%s %s", prefix, shorter_str);
2633 cleanup:
2634 /* cleanup */
2635 SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
2636 smartlist_free(summary);
2638 tor_free(accepts_str);
2639 SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
2640 smartlist_free(accepts);
2642 tor_free(rejects_str);
2643 SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
2644 smartlist_free(rejects);
2646 return result;
2649 /** Convert a summarized policy string into a short_policy_t. Return NULL
2650 * if the string is not well-formed. */
2651 short_policy_t *
2652 parse_short_policy(const char *summary)
2654 const char *orig_summary = summary;
2655 short_policy_t *result;
2656 int is_accept;
2657 int n_entries;
2658 short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
2659 const char *next;
2661 if (!strcmpstart(summary, "accept ")) {
2662 is_accept = 1;
2663 summary += strlen("accept ");
2664 } else if (!strcmpstart(summary, "reject ")) {
2665 is_accept = 0;
2666 summary += strlen("reject ");
2667 } else {
2668 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
2669 return NULL;
2672 n_entries = 0;
2673 for ( ; *summary; summary = next) {
2674 const char *comma = strchr(summary, ',');
2675 unsigned low, high;
2676 char dummy;
2677 char ent_buf[32];
2678 size_t len;
2680 next = comma ? comma+1 : strchr(summary, '\0');
2681 len = comma ? (size_t)(comma - summary) : strlen(summary);
2683 if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
2684 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
2685 escaped(orig_summary));
2686 return NULL;
2689 if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
2690 /* unrecognized entry format. skip it. */
2691 continue;
2693 if (len < 1) {
2694 /* empty; skip it. */
2695 /* XXX This happens to be unreachable, since if len==0, then *summary is
2696 * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
2697 continue;
2700 memcpy(ent_buf, summary, len);
2701 ent_buf[len] = '\0';
2703 if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
2704 if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
2705 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2706 "Found bad entry in policy summary %s", escaped(orig_summary));
2707 return NULL;
2709 } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
2710 if (low<1 || low>65535) {
2711 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2712 "Found bad entry in policy summary %s", escaped(orig_summary));
2713 return NULL;
2715 high = low;
2716 } else {
2717 log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
2718 escaped(orig_summary));
2719 return NULL;
2722 entries[n_entries].min_port = low;
2723 entries[n_entries].max_port = high;
2724 n_entries++;
2727 if (n_entries == 0) {
2728 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2729 "Found no port-range entries in summary %s", escaped(orig_summary));
2730 return NULL;
2734 size_t size = STRUCT_OFFSET(short_policy_t, entries) +
2735 sizeof(short_policy_entry_t)*(n_entries);
2736 result = tor_malloc_zero(size);
2738 tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
2741 result->is_accept = is_accept;
2742 result->n_entries = n_entries;
2743 memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
2744 return result;
2747 /** Write <b>policy</b> back out into a string. */
2748 char *
2749 write_short_policy(const short_policy_t *policy)
2751 int i;
2752 char *answer;
2753 smartlist_t *sl = smartlist_new();
2755 smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
2757 for (i=0; i < policy->n_entries; i++) {
2758 const short_policy_entry_t *e = &policy->entries[i];
2759 if (e->min_port == e->max_port) {
2760 smartlist_add_asprintf(sl, "%d", e->min_port);
2761 } else {
2762 smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
2764 if (i < policy->n_entries-1)
2765 smartlist_add_strdup(sl, ",");
2767 answer = smartlist_join_strings(sl, "", 0, NULL);
2768 SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
2769 smartlist_free(sl);
2770 return answer;
2773 /** Release all storage held in <b>policy</b>. */
2774 void
2775 short_policy_free(short_policy_t *policy)
2777 tor_free(policy);
2780 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
2781 * or rejected by the summarized policy <b>policy</b>. Return values are as
2782 * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
2783 * functions, requires the <b>port</b> be specified. */
2784 addr_policy_result_t
2785 compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
2786 const short_policy_t *policy)
2788 int i;
2789 int found_match = 0;
2790 int accept_;
2792 tor_assert(port != 0);
2794 if (addr && tor_addr_is_null(addr))
2795 addr = NULL; /* Unspec means 'no address at all,' in this context. */
2797 if (addr && get_options()->ClientRejectInternalAddresses &&
2798 (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
2799 return ADDR_POLICY_REJECTED;
2801 for (i=0; i < policy->n_entries; ++i) {
2802 const short_policy_entry_t *e = &policy->entries[i];
2803 if (e->min_port <= port && port <= e->max_port) {
2804 found_match = 1;
2805 break;
2809 if (found_match)
2810 accept_ = policy->is_accept;
2811 else
2812 accept_ = ! policy->is_accept;
2814 /* ???? are these right? -NM */
2815 /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
2816 * case here, because it would cause clients to believe that the node
2817 * allows exit enclaving. Trying it anyway would open up a cool attack
2818 * where the node refuses due to exitpolicy, the client reacts in
2819 * surprise by rewriting the node's exitpolicy to reject *:*, and then
2820 * an adversary targets users by causing them to attempt such connections
2821 * to 98% of the exits.
2823 * Once microdescriptors can handle addresses in special cases (e.g. if
2824 * we ever solve ticket 1774), we can provide certainty here. -RD */
2825 if (accept_)
2826 return ADDR_POLICY_PROBABLY_ACCEPTED;
2827 else
2828 return ADDR_POLICY_REJECTED;
2831 /** Return true iff <b>policy</b> seems reject all ports */
2833 short_policy_is_reject_star(const short_policy_t *policy)
2835 /* This doesn't need to be as much on the lookout as policy_is_reject_star,
2836 * since policy summaries are from the consensus or from consensus
2837 * microdescs.
2839 tor_assert(policy);
2840 /* Check for an exact match of "reject 1-65535". */
2841 return (policy->is_accept == 0 && policy->n_entries == 1 &&
2842 policy->entries[0].min_port == 1 &&
2843 policy->entries[0].max_port == 65535);
2846 /** Decide whether addr:port is probably or definitely accepted or rejected by
2847 * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
2848 * interpretation. */
2849 addr_policy_result_t
2850 compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
2851 const node_t *node)
2853 if (node->rejects_all)
2854 return ADDR_POLICY_REJECTED;
2856 if (addr && tor_addr_family(addr) == AF_INET6) {
2857 const short_policy_t *p = NULL;
2858 if (node->ri)
2859 p = node->ri->ipv6_exit_policy;
2860 else if (node->md)
2861 p = node->md->ipv6_exit_policy;
2862 if (p)
2863 return compare_tor_addr_to_short_policy(addr, port, p);
2864 else
2865 return ADDR_POLICY_REJECTED;
2868 if (node->ri) {
2869 return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
2870 } else if (node->md) {
2871 if (node->md->exit_policy == NULL)
2872 return ADDR_POLICY_REJECTED;
2873 else
2874 return compare_tor_addr_to_short_policy(addr, port,
2875 node->md->exit_policy);
2876 } else {
2877 return ADDR_POLICY_PROBABLY_REJECTED;
2882 * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
2883 * representation of the list.
2884 * If <b>include_ipv4</b> is true, include IPv4 entries.
2885 * If <b>include_ipv6</b> is true, include IPv6 entries.
2887 char *
2888 policy_dump_to_string(const smartlist_t *policy_list,
2889 int include_ipv4,
2890 int include_ipv6)
2892 smartlist_t *policy_string_list;
2893 char *policy_string = NULL;
2895 policy_string_list = smartlist_new();
2897 SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
2898 char *pbuf;
2899 int bytes_written_to_pbuf;
2900 if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2901 continue; /* Don't include IPv6 parts of address policy */
2903 if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2904 continue; /* Don't include IPv4 parts of address policy */
2907 pbuf = tor_malloc(POLICY_BUF_LEN);
2908 bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2910 if (bytes_written_to_pbuf < 0) {
2911 log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
2912 tor_free(pbuf);
2913 goto done;
2916 smartlist_add(policy_string_list,pbuf);
2917 } SMARTLIST_FOREACH_END(tmpe);
2919 policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
2921 done:
2922 SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
2923 smartlist_free(policy_string_list);
2925 return policy_string;
2928 /** Implementation for GETINFO control command: knows the answer for questions
2929 * about "exit-policy/..." */
2931 getinfo_helper_policies(control_connection_t *conn,
2932 const char *question, char **answer,
2933 const char **errmsg)
2935 (void) conn;
2936 (void) errmsg;
2937 if (!strcmp(question, "exit-policy/default")) {
2938 *answer = tor_strdup(DEFAULT_EXIT_POLICY);
2939 } else if (!strcmp(question, "exit-policy/reject-private/default")) {
2940 smartlist_t *private_policy_strings;
2941 const char **priv = private_nets;
2943 private_policy_strings = smartlist_new();
2945 while (*priv != NULL) {
2946 /* IPv6 addresses are in "[]" and contain ":",
2947 * IPv4 addresses are not in "[]" and contain "." */
2948 smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
2949 priv++;
2952 *answer = smartlist_join_strings(private_policy_strings,
2953 ",", 0, NULL);
2955 SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
2956 smartlist_free(private_policy_strings);
2957 } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
2958 const or_options_t *options = get_options();
2959 const routerinfo_t *me = router_get_my_routerinfo();
2961 if (!me) {
2962 *errmsg = "router_get_my_routerinfo returned NULL";
2963 return -1;
2966 if (!options->ExitPolicyRejectPrivate &&
2967 !options->ExitPolicyRejectLocalInterfaces) {
2968 *answer = tor_strdup("");
2969 return 0;
2972 smartlist_t *private_policy_list = smartlist_new();
2973 smartlist_t *configured_addresses = smartlist_new();
2975 /* Copy the configured addresses into the tor_addr_t* list */
2976 if (options->ExitPolicyRejectPrivate) {
2977 policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
2978 policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
2981 if (options->ExitPolicyRejectLocalInterfaces) {
2982 policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2983 options);
2986 policies_parse_exit_policy_reject_private(
2987 &private_policy_list,
2988 options->IPv6Exit,
2989 configured_addresses,
2990 options->ExitPolicyRejectLocalInterfaces,
2991 options->ExitPolicyRejectLocalInterfaces);
2992 *answer = policy_dump_to_string(private_policy_list, 1, 1);
2994 addr_policy_list_free(private_policy_list);
2995 SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2996 smartlist_free(configured_addresses);
2997 } else if (!strcmpstart(question, "exit-policy/")) {
2998 const routerinfo_t *me = router_get_my_routerinfo();
3000 int include_ipv4 = 0;
3001 int include_ipv6 = 0;
3003 if (!strcmp(question, "exit-policy/ipv4")) {
3004 include_ipv4 = 1;
3005 } else if (!strcmp(question, "exit-policy/ipv6")) {
3006 include_ipv6 = 1;
3007 } else if (!strcmp(question, "exit-policy/full")) {
3008 include_ipv4 = include_ipv6 = 1;
3009 } else {
3010 return 0; /* No such key. */
3013 if (!me) {
3014 *errmsg = "router_get_my_routerinfo returned NULL";
3015 return -1;
3018 *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
3020 return 0;
3023 /** Release all storage held by <b>p</b>. */
3024 void
3025 addr_policy_list_free(smartlist_t *lst)
3027 if (!lst)
3028 return;
3029 SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
3030 smartlist_free(lst);
3033 /** Release all storage held by <b>p</b>. */
3034 void
3035 addr_policy_free(addr_policy_t *p)
3037 if (!p)
3038 return;
3040 if (--p->refcnt <= 0) {
3041 if (p->is_canonical) {
3042 policy_map_ent_t search, *found;
3043 search.policy = p;
3044 found = HT_REMOVE(policy_map, &policy_root, &search);
3045 if (found) {
3046 tor_assert(p == found->policy);
3047 tor_free(found);
3050 tor_free(p);
3054 /** Release all storage held by policy variables. */
3055 void
3056 policies_free_all(void)
3058 addr_policy_list_free(reachable_or_addr_policy);
3059 reachable_or_addr_policy = NULL;
3060 addr_policy_list_free(reachable_dir_addr_policy);
3061 reachable_dir_addr_policy = NULL;
3062 addr_policy_list_free(socks_policy);
3063 socks_policy = NULL;
3064 addr_policy_list_free(dir_policy);
3065 dir_policy = NULL;
3066 addr_policy_list_free(authdir_reject_policy);
3067 authdir_reject_policy = NULL;
3068 addr_policy_list_free(authdir_invalid_policy);
3069 authdir_invalid_policy = NULL;
3070 addr_policy_list_free(authdir_badexit_policy);
3071 authdir_badexit_policy = NULL;
3073 if (!HT_EMPTY(&policy_root)) {
3074 policy_map_ent_t **ent;
3075 int n = 0;
3076 char buf[POLICY_BUF_LEN];
3078 log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
3079 (int)HT_SIZE(&policy_root));
3081 /* Note the first 10 cached policies to try to figure out where they
3082 * might be coming from. */
3083 HT_FOREACH(ent, policy_map, &policy_root) {
3084 if (++n > 10)
3085 break;
3086 if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
3087 log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
3090 HT_CLEAR(policy_map, &policy_root);