fix typo
[tor.git] / src / or / policies.c
blob2703d7edefd0c94ff656693ac3722e7f871996cb
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.
9 **/
11 #define POLICIES_PRIVATE
13 #include "or.h"
14 #include "config.h"
15 #include "dirserv.h"
16 #include "networkstatus.h"
17 #include "nodelist.h"
18 #include "policies.h"
19 #include "router.h"
20 #include "routerparse.h"
21 #include "geoip.h"
22 #include "ht.h"
24 /** Policy that addresses for incoming SOCKS connections must match. */
25 static smartlist_t *socks_policy = NULL;
26 /** Policy that addresses for incoming directory connections must match. */
27 static smartlist_t *dir_policy = NULL;
28 /** Policy that addresses for incoming router descriptors must match in order
29 * to be published by us. */
30 static smartlist_t *authdir_reject_policy = NULL;
31 /** Policy that addresses for incoming router descriptors must match in order
32 * to be marked as valid in our networkstatus. */
33 static smartlist_t *authdir_invalid_policy = NULL;
34 /** Policy that addresses for incoming router descriptors must <b>not</b>
35 * match in order to not be marked as BadExit. */
36 static smartlist_t *authdir_badexit_policy = NULL;
38 /** Parsed addr_policy_t describing which addresses we believe we can start
39 * circuits at. */
40 static smartlist_t *reachable_or_addr_policy = NULL;
41 /** Parsed addr_policy_t describing which addresses we believe we can connect
42 * to directories at. */
43 static smartlist_t *reachable_dir_addr_policy = NULL;
45 /** Element of an exit policy summary */
46 typedef struct policy_summary_item_t {
47 uint16_t prt_min; /**< Lowest port number to accept/reject. */
48 uint16_t prt_max; /**< Highest port number to accept/reject. */
49 uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
50 this port range. */
51 unsigned int accepted:1; /** Has this port already been accepted */
52 } policy_summary_item_t;
54 /** Private networks. This list is used in two places, once to expand the
55 * "private" keyword when parsing our own exit policy, secondly to ignore
56 * just such networks when building exit policy summaries. It is important
57 * that all authorities agree on that list when creating summaries, so don't
58 * just change this without a proper migration plan and a proposal and stuff.
60 static const char *private_nets[] = {
61 "0.0.0.0/8", "169.254.0.0/16",
62 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
63 "[::]/8",
64 "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
65 NULL
68 static int policies_parse_exit_policy_internal(
69 config_line_t *cfg,
70 smartlist_t **dest,
71 int ipv6_exit,
72 int rejectprivate,
73 const smartlist_t *configured_addresses,
74 int reject_interface_addresses,
75 int reject_configured_port_addresses,
76 int add_default_policy);
78 /** Replace all "private" entries in *<b>policy</b> with their expanded
79 * equivalents. */
80 void
81 policy_expand_private(smartlist_t **policy)
83 uint16_t port_min, port_max;
85 int i;
86 smartlist_t *tmp;
88 if (!*policy) /*XXXX disallow NULL policies? */
89 return;
91 tmp = smartlist_new();
93 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
94 if (! p->is_private) {
95 smartlist_add(tmp, p);
96 continue;
98 for (i = 0; private_nets[i]; ++i) {
99 addr_policy_t newpolicy;
100 memcpy(&newpolicy, p, sizeof(addr_policy_t));
101 newpolicy.is_private = 0;
102 newpolicy.is_canonical = 0;
103 if (tor_addr_parse_mask_ports(private_nets[i], 0,
104 &newpolicy.addr,
105 &newpolicy.maskbits, &port_min, &port_max)<0) {
106 tor_assert_unreached();
108 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
110 addr_policy_free(p);
111 } SMARTLIST_FOREACH_END(p);
113 smartlist_free(*policy);
114 *policy = tmp;
117 /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
118 * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
119 * specific and one IPv6-specific. */
120 void
121 policy_expand_unspec(smartlist_t **policy)
123 smartlist_t *tmp;
124 if (!*policy)
125 return;
127 tmp = smartlist_new();
128 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
129 sa_family_t family = tor_addr_family(&p->addr);
130 if (family == AF_INET6 || family == AF_INET || p->is_private) {
131 smartlist_add(tmp, p);
132 } else if (family == AF_UNSPEC) {
133 addr_policy_t newpolicy_ipv4;
134 addr_policy_t newpolicy_ipv6;
135 memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
136 memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
137 newpolicy_ipv4.is_canonical = 0;
138 newpolicy_ipv6.is_canonical = 0;
139 if (p->maskbits != 0) {
140 log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
141 newpolicy_ipv4.maskbits = 0;
142 newpolicy_ipv6.maskbits = 0;
144 tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
145 tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
146 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
147 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
148 smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
149 addr_policy_free(p);
150 } else {
151 log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
152 smartlist_add(tmp, p);
154 } SMARTLIST_FOREACH_END(p);
156 smartlist_free(*policy);
157 *policy = tmp;
161 * Given a linked list of config lines containing "accept[6]" and "reject[6]"
162 * tokens, parse them and append the result to <b>dest</b>. Return -1
163 * if any tokens are malformed (and don't append any), else return 0.
165 * If <b>assume_action</b> is nonnegative, then insert its action
166 * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
167 * action.
169 static int
170 parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
171 int assume_action)
173 smartlist_t *result;
174 smartlist_t *entries;
175 addr_policy_t *item;
176 int malformed_list;
177 int r = 0;
179 if (!cfg)
180 return 0;
182 result = smartlist_new();
183 entries = smartlist_new();
184 for (; cfg; cfg = cfg->next) {
185 smartlist_split_string(entries, cfg->value, ",",
186 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
187 SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
188 log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
189 malformed_list = 0;
190 item = router_parse_addr_policy_item_from_string(ent, assume_action,
191 &malformed_list);
192 if (item) {
193 smartlist_add(result, item);
194 } else if (malformed_list) {
195 /* the error is so severe the entire list should be discarded */
196 log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
197 "list.", ent);
198 r = -1;
199 } else {
200 /* the error is minor: don't add the item, but keep processing the
201 * rest of the policies in the list */
202 log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
203 "The remainder of the policy list will be used.",
204 ent);
206 } SMARTLIST_FOREACH_END(ent);
207 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
208 smartlist_clear(entries);
210 smartlist_free(entries);
211 if (r == -1) {
212 addr_policy_list_free(result);
213 } else {
214 policy_expand_private(&result);
215 policy_expand_unspec(&result);
217 if (*dest) {
218 smartlist_add_all(*dest, result);
219 smartlist_free(result);
220 } else {
221 *dest = result;
225 return r;
228 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
229 * reachable_(or|dir)_addr_policy. The options should already have
230 * been validated by validate_addr_policies.
232 static int
233 parse_reachable_addresses(void)
235 const or_options_t *options = get_options();
236 int ret = 0;
238 if (options->ReachableDirAddresses &&
239 options->ReachableORAddresses &&
240 options->ReachableAddresses) {
241 log_warn(LD_CONFIG,
242 "Both ReachableDirAddresses and ReachableORAddresses are set. "
243 "ReachableAddresses setting will be ignored.");
245 addr_policy_list_free(reachable_or_addr_policy);
246 reachable_or_addr_policy = NULL;
247 if (!options->ReachableORAddresses && options->ReachableAddresses)
248 log_info(LD_CONFIG,
249 "Using ReachableAddresses as ReachableORAddresses.");
250 if (parse_addr_policy(options->ReachableORAddresses ?
251 options->ReachableORAddresses :
252 options->ReachableAddresses,
253 &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
254 log_warn(LD_CONFIG,
255 "Error parsing Reachable%sAddresses entry; ignoring.",
256 options->ReachableORAddresses ? "OR" : "");
257 ret = -1;
260 addr_policy_list_free(reachable_dir_addr_policy);
261 reachable_dir_addr_policy = NULL;
262 if (!options->ReachableDirAddresses && options->ReachableAddresses)
263 log_info(LD_CONFIG,
264 "Using ReachableAddresses as ReachableDirAddresses");
265 if (parse_addr_policy(options->ReachableDirAddresses ?
266 options->ReachableDirAddresses :
267 options->ReachableAddresses,
268 &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
269 if (options->ReachableDirAddresses)
270 log_warn(LD_CONFIG,
271 "Error parsing ReachableDirAddresses entry; ignoring.");
272 ret = -1;
275 /* We ignore ReachableAddresses for relays */
276 if (!server_mode(options)) {
277 if ((reachable_or_addr_policy
278 && policy_is_reject_star(reachable_or_addr_policy, AF_UNSPEC))
279 || (reachable_dir_addr_policy
280 && policy_is_reject_star(reachable_dir_addr_policy, AF_UNSPEC))) {
281 log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
282 "ReachableAddresses, ReachableORAddresses, or "
283 "ReachableDirAddresses reject all addresses. Please accept "
284 "some addresses in these options.");
285 } else if (options->ClientUseIPv4 == 1
286 && ((reachable_or_addr_policy
287 && policy_is_reject_star(reachable_or_addr_policy, AF_INET))
288 || (reachable_dir_addr_policy
289 && policy_is_reject_star(reachable_dir_addr_policy, AF_INET)))) {
290 log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
291 "ReachableAddresses, ReachableORAddresses, or "
292 "ReachableDirAddresses reject all IPv4 addresses. "
293 "Tor will not connect using IPv4.");
294 } else if (fascist_firewall_use_ipv6(options)
295 && ((reachable_or_addr_policy
296 && policy_is_reject_star(reachable_or_addr_policy, AF_INET6))
297 || (reachable_dir_addr_policy
298 && policy_is_reject_star(reachable_dir_addr_policy, AF_INET6)))) {
299 log_warn(LD_CONFIG, "You have configured tor to use IPv6 "
300 "(ClientUseIPv6 1 or UseBridges 1), but "
301 "ReachableAddresses, ReachableORAddresses, or "
302 "ReachableDirAddresses reject all IPv6 addresses. "
303 "Tor will not connect using IPv6.");
307 return ret;
310 /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
311 * address:port combination. */
312 static int
313 firewall_is_fascist_impl(void)
315 const or_options_t *options = get_options();
316 /* Assume every non-bridge relay has an IPv4 address.
317 * Clients which use bridges may only know the IPv6 address of their
318 * bridge. */
319 return (options->ClientUseIPv4 == 0
320 || (!fascist_firewall_use_ipv6(options)
321 && options->UseBridges == 1));
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 * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
429 * port: it supports bridge client per-node IPv6 preferences.
432 fascist_firewall_use_ipv6(const or_options_t *options)
434 /* Clients use IPv6 if it's set, or they use bridges, or they don't use
435 * IPv4 */
436 return (options->ClientUseIPv6 == 1 || options->UseBridges == 1
437 || options->ClientUseIPv4 == 0);
440 /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
441 * ClientPreferIPv6DirPort?
442 * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
444 static int
445 fascist_firewall_prefer_ipv6_impl(const or_options_t *options)
448 Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
449 If we're a server or IPv6 is disabled, use IPv4.
450 If IPv4 is disabled, use IPv6.
453 if (server_mode(options) || !fascist_firewall_use_ipv6(options)) {
454 return 0;
457 if (!options->ClientUseIPv4) {
458 return 1;
461 return -1;
464 /** Do we prefer to connect to IPv6 ORPorts?
465 * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
466 * per-node IPv6 preferences.
469 fascist_firewall_prefer_ipv6_orport(const or_options_t *options)
471 int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
473 if (pref_ipv6 >= 0) {
474 return pref_ipv6;
477 /* We can use both IPv4 and IPv6 - which do we prefer? */
478 if (options->ClientPreferIPv6ORPort == 1) {
479 return 1;
482 return 0;
485 /** Do we prefer to connect to IPv6 DirPorts?
487 * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
488 * preferences. There's no reason to use it instead of this function.)
491 fascist_firewall_prefer_ipv6_dirport(const or_options_t *options)
493 int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
495 if (pref_ipv6 >= 0) {
496 return pref_ipv6;
499 /* We can use both IPv4 and IPv6 - which do we prefer? */
500 if (options->ClientPreferIPv6DirPort == 1) {
501 return 1;
504 return 0;
507 /** Return true iff we think our firewall will let us make a connection to
508 * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
509 * fw_connection.
510 * If pref_only is true, return true if addr is in the client's preferred
511 * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
512 * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
515 fascist_firewall_allows_address_addr(const tor_addr_t *addr, uint16_t port,
516 firewall_connection_t fw_connection,
517 int pref_only, int pref_ipv6)
519 if (fw_connection == FIREWALL_OR_CONNECTION) {
520 return fascist_firewall_allows_address(addr, port,
521 reachable_or_addr_policy,
522 pref_only, pref_ipv6);
523 } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
524 return fascist_firewall_allows_address(addr, port,
525 reachable_dir_addr_policy,
526 pref_only, pref_ipv6);
527 } else {
528 log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
529 fw_connection);
530 return 0;
534 /** Return true iff we think our firewall will let us make a connection to
535 * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
536 * fw_connection.
537 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
539 static int
540 fascist_firewall_allows_address_ap(const tor_addr_port_t *ap,
541 firewall_connection_t fw_connection,
542 int pref_only, int pref_ipv6)
544 tor_assert(ap);
545 return fascist_firewall_allows_address_addr(&ap->addr, ap->port,
546 fw_connection, pref_only,
547 pref_ipv6);
550 /* Return true iff we think our firewall will let us make a connection to
551 * ipv4h_or_addr:ipv4_or_port. ipv4h_or_addr is interpreted in host order.
552 * Uses ReachableORAddresses or ReachableDirAddresses based on
553 * fw_connection.
554 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
556 static int
557 fascist_firewall_allows_address_ipv4h(uint32_t ipv4h_or_addr,
558 uint16_t ipv4_or_port,
559 firewall_connection_t fw_connection,
560 int pref_only, int pref_ipv6)
562 tor_addr_t ipv4_or_addr;
563 tor_addr_from_ipv4h(&ipv4_or_addr, ipv4h_or_addr);
564 return fascist_firewall_allows_address_addr(&ipv4_or_addr, ipv4_or_port,
565 fw_connection, pref_only,
566 pref_ipv6);
569 /** Return true iff we think our firewall will let us make a connection to
570 * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
571 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
572 * <b>fw_connection</b>.
573 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
575 static int
576 fascist_firewall_allows_base(uint32_t ipv4h_addr, uint16_t ipv4_orport,
577 uint16_t ipv4_dirport,
578 const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
579 uint16_t ipv6_dirport,
580 firewall_connection_t fw_connection,
581 int pref_only, int pref_ipv6)
583 if (fascist_firewall_allows_address_ipv4h(ipv4h_addr,
584 (fw_connection == FIREWALL_OR_CONNECTION
585 ? ipv4_orport
586 : ipv4_dirport),
587 fw_connection,
588 pref_only, pref_ipv6)) {
589 return 1;
592 if (fascist_firewall_allows_address_addr(ipv6_addr,
593 (fw_connection == FIREWALL_OR_CONNECTION
594 ? ipv6_orport
595 : ipv6_dirport),
596 fw_connection,
597 pref_only, pref_ipv6)) {
598 return 1;
601 return 0;
604 /** Like fascist_firewall_allows_base(), but takes ri. */
605 static int
606 fascist_firewall_allows_ri_impl(const routerinfo_t *ri,
607 firewall_connection_t fw_connection,
608 int pref_only, int pref_ipv6)
610 if (!ri) {
611 return 0;
614 /* Assume IPv4 and IPv6 DirPorts are the same */
615 return fascist_firewall_allows_base(ri->addr, ri->or_port, ri->dir_port,
616 &ri->ipv6_addr, ri->ipv6_orport,
617 ri->dir_port, fw_connection, pref_only,
618 pref_ipv6);
621 /** Like fascist_firewall_allows_rs, but doesn't consult the node. */
622 static int
623 fascist_firewall_allows_rs_impl(const routerstatus_t *rs,
624 firewall_connection_t fw_connection,
625 int pref_only, int pref_ipv6)
627 if (!rs) {
628 return 0;
631 /* Assume IPv4 and IPv6 DirPorts are the same */
632 return fascist_firewall_allows_base(rs->addr, rs->or_port, rs->dir_port,
633 &rs->ipv6_addr, rs->ipv6_orport,
634 rs->dir_port, fw_connection, pref_only,
635 pref_ipv6);
638 /** Like fascist_firewall_allows_base(), but takes rs.
639 * Consults the corresponding node, then falls back to rs if node is NULL.
640 * This should only happen when there's no valid consensus, and rs doesn't
641 * correspond to a bridge client's bridge.
644 fascist_firewall_allows_rs(const routerstatus_t *rs,
645 firewall_connection_t fw_connection, int pref_only)
647 if (!rs) {
648 return 0;
651 const node_t *node = node_get_by_id(rs->identity_digest);
653 if (node) {
654 return fascist_firewall_allows_node(node, fw_connection, pref_only);
655 } else {
656 /* There's no node-specific IPv6 preference, so use the generic IPv6
657 * preference instead. */
658 const or_options_t *options = get_options();
659 int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
660 ? fascist_firewall_prefer_ipv6_orport(options)
661 : fascist_firewall_prefer_ipv6_dirport(options));
663 return fascist_firewall_allows_rs_impl(rs, fw_connection, pref_only,
664 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 * This function relies on fascist_firewall_choose_address_rs looking up the
746 * node if it can, because that will get the latest info for the relay. */
747 return fascist_firewall_allows_rs(&ds->fake_status, fw_connection,
748 pref_only);
751 /** If a and b are both valid and allowed by fw_connection,
752 * choose one based on want_a and return it.
753 * Otherwise, return whichever is allowed.
754 * Otherwise, return NULL.
755 * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
757 static const tor_addr_port_t *
758 fascist_firewall_choose_address_impl(const tor_addr_port_t *a,
759 const tor_addr_port_t *b,
760 int want_a,
761 firewall_connection_t fw_connection,
762 int pref_only, int pref_ipv6)
764 const tor_addr_port_t *use_a = NULL;
765 const tor_addr_port_t *use_b = NULL;
767 if (fascist_firewall_allows_address_ap(a, fw_connection, pref_only,
768 pref_ipv6)) {
769 use_a = a;
772 if (fascist_firewall_allows_address_ap(b, fw_connection, pref_only,
773 pref_ipv6)) {
774 use_b = b;
777 /* If both are allowed */
778 if (use_a && use_b) {
779 /* Choose a if we want it */
780 return (want_a ? use_a : use_b);
781 } else {
782 /* Choose a if we have it */
783 return (use_a ? use_a : use_b);
787 /** If a and b are both valid and preferred by fw_connection,
788 * choose one based on want_a and return it.
789 * Otherwise, return whichever is preferred.
790 * If neither are preferred, and pref_only is false:
791 * - If a and b are both allowed by fw_connection,
792 * choose one based on want_a and return it.
793 * - Otherwise, return whichever is preferred.
794 * Otherwise, return NULL. */
795 STATIC const tor_addr_port_t *
796 fascist_firewall_choose_address(const tor_addr_port_t *a,
797 const tor_addr_port_t *b,
798 int want_a,
799 firewall_connection_t fw_connection,
800 int pref_only, int pref_ipv6)
802 const tor_addr_port_t *pref = fascist_firewall_choose_address_impl(
803 a, b, want_a,
804 fw_connection,
805 1, pref_ipv6);
806 if (pref_only || pref) {
807 /* If there is a preferred address, use it. If we can only use preferred
808 * addresses, and neither address is preferred, pref will be NULL, and we
809 * want to return NULL, so return it. */
810 return pref;
811 } else {
812 /* If there's no preferred address, and we can return addresses that are
813 * not preferred, use an address that's allowed */
814 return fascist_firewall_choose_address_impl(a, b, want_a, fw_connection,
815 0, pref_ipv6);
819 /** Copy an address and port into <b>ap</b> that we think our firewall will
820 * let us connect to. Uses ipv4_addr/ipv6_addr and
821 * ipv4_orport/ipv6_orport/ReachableORAddresses or
822 * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
823 * <b>fw_connection</b>.
824 * If pref_only, only choose preferred addresses. In either case, choose
825 * a preferred address before an address that's not preferred.
826 * If both addresses could be chosen (they are both preferred or both allowed)
827 * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4.
828 * If neither address is chosen, return 0, else return 1. */
829 static int
830 fascist_firewall_choose_address_base(const tor_addr_t *ipv4_addr,
831 uint16_t ipv4_orport,
832 uint16_t ipv4_dirport,
833 const tor_addr_t *ipv6_addr,
834 uint16_t ipv6_orport,
835 uint16_t ipv6_dirport,
836 firewall_connection_t fw_connection,
837 int pref_only,
838 int pref_ipv6,
839 tor_addr_port_t* ap)
841 const tor_addr_port_t *result = NULL;
842 const int want_ipv4 = !pref_ipv6;
844 tor_assert(ipv6_addr);
845 tor_assert(ap);
847 tor_addr_port_t ipv4_ap;
848 tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
849 ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
850 ? ipv4_orport
851 : ipv4_dirport);
853 tor_addr_port_t ipv6_ap;
854 tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
855 ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
856 ? ipv6_orport
857 : ipv6_dirport);
859 result = fascist_firewall_choose_address(&ipv4_ap, &ipv6_ap,
860 want_ipv4,
861 fw_connection, pref_only,
862 pref_ipv6);
864 if (result) {
865 tor_addr_copy(&ap->addr, &result->addr);
866 ap->port = result->port;
867 return 1;
868 } else {
869 return 0;
873 /** Like fascist_firewall_choose_address_base(), but takes a host-order IPv4
874 * address as the first parameter. */
875 static int
876 fascist_firewall_choose_address_ipv4h(uint32_t ipv4h_addr,
877 uint16_t ipv4_orport,
878 uint16_t ipv4_dirport,
879 const tor_addr_t *ipv6_addr,
880 uint16_t ipv6_orport,
881 uint16_t ipv6_dirport,
882 firewall_connection_t fw_connection,
883 int pref_only,
884 int pref_ipv6,
885 tor_addr_port_t* ap)
887 tor_addr_t ipv4_addr;
888 tor_addr_from_ipv4h(&ipv4_addr, ipv4h_addr);
889 return fascist_firewall_choose_address_base(&ipv4_addr, ipv4_orport,
890 ipv4_dirport, ipv6_addr,
891 ipv6_orport, ipv6_dirport,
892 fw_connection, pref_only,
893 pref_ipv6, ap);
896 /** Like fascist_firewall_choose_address_base(), but takes <b>rs</b>.
897 * Consults the corresponding node, then falls back to rs if node is NULL.
898 * This should only happen when there's no valid consensus, and rs doesn't
899 * correspond to a bridge client's bridge.
902 fascist_firewall_choose_address_rs(const routerstatus_t *rs,
903 firewall_connection_t fw_connection,
904 int pref_only, tor_addr_port_t* ap)
906 if (!rs) {
907 return 0;
910 tor_assert(ap);
912 const node_t *node = node_get_by_id(rs->identity_digest);
914 if (node) {
915 return fascist_firewall_choose_address_node(node, fw_connection, pref_only,
916 ap);
917 } else {
918 /* There's no node-specific IPv6 preference, so use the generic IPv6
919 * preference instead. */
920 const or_options_t *options = get_options();
921 int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
922 ? fascist_firewall_prefer_ipv6_orport(options)
923 : fascist_firewall_prefer_ipv6_dirport(options));
925 /* Assume IPv4 and IPv6 DirPorts are the same.
926 * Assume the IPv6 OR and Dir addresses are the same. */
927 return fascist_firewall_choose_address_ipv4h(rs->addr,
928 rs->or_port,
929 rs->dir_port,
930 &rs->ipv6_addr,
931 rs->ipv6_orport,
932 rs->dir_port,
933 fw_connection,
934 pref_only,
935 pref_ipv6,
936 ap);
940 /** Like fascist_firewall_choose_address_base(), but takes <b>node</b>, and
941 * looks up the node's IPv6 preference rather than taking an argument
942 * for pref_ipv6. */
944 fascist_firewall_choose_address_node(const node_t *node,
945 firewall_connection_t fw_connection,
946 int pref_only, tor_addr_port_t *ap)
948 if (!node) {
949 return 0;
952 node_assert_ok(node);
954 const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
955 ? node_ipv6_or_preferred(node)
956 : node_ipv6_dir_preferred(node));
958 tor_addr_port_t ipv4_or_ap;
959 node_get_prim_orport(node, &ipv4_or_ap);
960 tor_addr_port_t ipv4_dir_ap;
961 node_get_prim_dirport(node, &ipv4_dir_ap);
963 tor_addr_port_t ipv6_or_ap;
964 node_get_pref_ipv6_orport(node, &ipv6_or_ap);
965 tor_addr_port_t ipv6_dir_ap;
966 node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
968 /* Assume the IPv6 OR and Dir addresses are the same. */
969 return fascist_firewall_choose_address_base(&ipv4_or_ap.addr,
970 ipv4_or_ap.port,
971 ipv4_dir_ap.port,
972 &ipv6_or_ap.addr,
973 ipv6_or_ap.port,
974 ipv6_dir_ap.port,
975 fw_connection,
976 pref_only,
977 pref_ipv6_node,
978 ap);
981 /** Like fascist_firewall_choose_address_rs(), but takes <b>ds</b>. */
983 fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
984 firewall_connection_t fw_connection,
985 int pref_only,
986 tor_addr_port_t *ap)
988 if (!ds) {
989 return 0;
992 /* A dir_server_t always has a fake_status. As long as it has the same
993 * addresses/ports in both fake_status and dir_server_t, this works fine.
994 * (See #17867.)
995 * This function relies on fascist_firewall_choose_address_rs looking up the
996 * node if it can, because that will get the latest info for the relay. */
997 return fascist_firewall_choose_address_rs(&ds->fake_status, fw_connection,
998 pref_only, ap);
1001 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
1002 * based on <b>dir_policy</b>. Else return 0.
1005 dir_policy_permits_address(const tor_addr_t *addr)
1007 return addr_policy_permits_tor_addr(addr, 1, dir_policy);
1010 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1011 * based on <b>socks_policy</b>. Else return 0.
1014 socks_policy_permits_address(const tor_addr_t *addr)
1016 return addr_policy_permits_tor_addr(addr, 1, socks_policy);
1019 /** Return true iff the address <b>addr</b> is in a country listed in the
1020 * case-insensitive list of country codes <b>cc_list</b>. */
1021 static int
1022 addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
1024 country_t country;
1025 const char *name;
1026 tor_addr_t tar;
1028 if (!cc_list)
1029 return 0;
1030 /* XXXXipv6 */
1031 tor_addr_from_ipv4h(&tar, addr);
1032 country = geoip_get_country_by_addr(&tar);
1033 name = geoip_get_country_name(country);
1034 return smartlist_contains_string_case(cc_list, name);
1037 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
1038 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
1041 authdir_policy_permits_address(uint32_t addr, uint16_t port)
1043 if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
1044 return 0;
1045 return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
1048 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
1049 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
1052 authdir_policy_valid_address(uint32_t addr, uint16_t port)
1054 if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
1055 return 0;
1056 return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
1059 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
1060 * based on <b>authdir_badexit_policy</b>. Else return 0.
1063 authdir_policy_badexit_address(uint32_t addr, uint16_t port)
1065 if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
1066 return 1;
1067 return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
1070 #define REJECT(arg) \
1071 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
1073 /** Config helper: If there's any problem with the policy configuration
1074 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
1075 * allocated description of the error. Else return 0. */
1077 validate_addr_policies(const or_options_t *options, char **msg)
1079 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
1080 * that the two can't go out of sync. */
1082 smartlist_t *addr_policy=NULL;
1083 *msg = NULL;
1085 if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
1086 REJECT("Error in ExitPolicy entry.");
1089 static int warned_about_exitrelay = 0;
1091 const int exitrelay_setting_is_auto = options->ExitRelay == -1;
1092 const int policy_accepts_something =
1093 ! (policy_is_reject_star(addr_policy, AF_INET) &&
1094 policy_is_reject_star(addr_policy, AF_INET6));
1096 if (server_mode(options) &&
1097 ! warned_about_exitrelay &&
1098 exitrelay_setting_is_auto &&
1099 policy_accepts_something) {
1100 /* Policy accepts something */
1101 warned_about_exitrelay = 1;
1102 log_warn(LD_CONFIG,
1103 "Tor is running as an exit relay%s. If you did not want this "
1104 "behavior, please set the ExitRelay option to 0. If you do "
1105 "want to run an exit Relay, please set the ExitRelay option "
1106 "to 1 to disable this warning, and for forward compatibility.",
1107 options->ExitPolicy == NULL ?
1108 " with the default exit policy" : "");
1109 if (options->ExitPolicy == NULL) {
1110 log_warn(LD_CONFIG,
1111 "In a future version of Tor, ExitRelay 0 may become the "
1112 "default when no ExitPolicy is given.");
1116 /* The rest of these calls *append* to addr_policy. So don't actually
1117 * use the results for anything other than checking if they parse! */
1118 if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
1119 REJECT("Error in DirPolicy entry.");
1120 if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
1121 REJECT("Error in SocksPolicy entry.");
1122 if (parse_addr_policy(options->AuthDirReject, &addr_policy,
1123 ADDR_POLICY_REJECT))
1124 REJECT("Error in AuthDirReject entry.");
1125 if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
1126 ADDR_POLICY_REJECT))
1127 REJECT("Error in AuthDirInvalid entry.");
1128 if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
1129 ADDR_POLICY_REJECT))
1130 REJECT("Error in AuthDirBadExit entry.");
1132 if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
1133 ADDR_POLICY_ACCEPT))
1134 REJECT("Error in ReachableAddresses entry.");
1135 if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
1136 ADDR_POLICY_ACCEPT))
1137 REJECT("Error in ReachableORAddresses entry.");
1138 if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
1139 ADDR_POLICY_ACCEPT))
1140 REJECT("Error in ReachableDirAddresses entry.");
1142 err:
1143 addr_policy_list_free(addr_policy);
1144 return *msg ? -1 : 0;
1145 #undef REJECT
1148 /** Parse <b>string</b> in the same way that the exit policy
1149 * is parsed, and put the processed version in *<b>policy</b>.
1150 * Ignore port specifiers.
1152 static int
1153 load_policy_from_option(config_line_t *config, const char *option_name,
1154 smartlist_t **policy,
1155 int assume_action)
1157 int r;
1158 int killed_any_ports = 0;
1159 addr_policy_list_free(*policy);
1160 *policy = NULL;
1161 r = parse_addr_policy(config, policy, assume_action);
1162 if (r < 0) {
1163 return -1;
1165 if (*policy) {
1166 SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
1167 /* ports aren't used in these. */
1168 if (n->prt_min > 1 || n->prt_max != 65535) {
1169 addr_policy_t newp, *c;
1170 memcpy(&newp, n, sizeof(newp));
1171 newp.prt_min = 1;
1172 newp.prt_max = 65535;
1173 newp.is_canonical = 0;
1174 c = addr_policy_get_canonical_entry(&newp);
1175 SMARTLIST_REPLACE_CURRENT(*policy, n, c);
1176 addr_policy_free(n);
1177 killed_any_ports = 1;
1179 } SMARTLIST_FOREACH_END(n);
1181 if (killed_any_ports) {
1182 log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
1184 return 0;
1187 /** Set all policies based on <b>options</b>, which should have been validated
1188 * first by validate_addr_policies. */
1190 policies_parse_from_options(const or_options_t *options)
1192 int ret = 0;
1193 if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
1194 &socks_policy, -1) < 0)
1195 ret = -1;
1196 if (load_policy_from_option(options->DirPolicy, "DirPolicy",
1197 &dir_policy, -1) < 0)
1198 ret = -1;
1199 if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
1200 &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
1201 ret = -1;
1202 if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
1203 &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
1204 ret = -1;
1205 if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
1206 &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
1207 ret = -1;
1208 if (parse_reachable_addresses() < 0)
1209 ret = -1;
1210 return ret;
1213 /** Compare two provided address policy items, and return -1, 0, or 1
1214 * if the first is less than, equal to, or greater than the second. */
1215 static int
1216 cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
1218 int r;
1219 if ((r=((int)a->policy_type - (int)b->policy_type)))
1220 return r;
1221 if ((r=((int)a->is_private - (int)b->is_private)))
1222 return r;
1223 /* refcnt and is_canonical are irrelevant to equality,
1224 * they are hash table implementation details */
1225 if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
1226 return r;
1227 if ((r=((int)a->maskbits - (int)b->maskbits)))
1228 return r;
1229 if ((r=((int)a->prt_min - (int)b->prt_min)))
1230 return r;
1231 if ((r=((int)a->prt_max - (int)b->prt_max)))
1232 return r;
1233 return 0;
1236 /** Like cmp_single_addr_policy() above, but looks at the
1237 * whole set of policies in each case. */
1239 cmp_addr_policies(smartlist_t *a, smartlist_t *b)
1241 int r, i;
1242 int len_a = a ? smartlist_len(a) : 0;
1243 int len_b = b ? smartlist_len(b) : 0;
1245 for (i = 0; i < len_a && i < len_b; ++i) {
1246 if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
1247 return r;
1249 if (i == len_a && i == len_b)
1250 return 0;
1251 if (i < len_a)
1252 return -1;
1253 else
1254 return 1;
1257 /** Node in hashtable used to store address policy entries. */
1258 typedef struct policy_map_ent_t {
1259 HT_ENTRY(policy_map_ent_t) node;
1260 addr_policy_t *policy;
1261 } policy_map_ent_t;
1263 /* DOCDOC policy_root */
1264 static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
1266 /** Return true iff a and b are equal. */
1267 static inline int
1268 policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
1270 return cmp_single_addr_policy(a->policy, b->policy) == 0;
1273 /** Return a hashcode for <b>ent</b> */
1274 static unsigned int
1275 policy_hash(const policy_map_ent_t *ent)
1277 const addr_policy_t *a = ent->policy;
1278 addr_policy_t aa;
1279 memset(&aa, 0, sizeof(aa));
1281 aa.prt_min = a->prt_min;
1282 aa.prt_max = a->prt_max;
1283 aa.maskbits = a->maskbits;
1284 aa.policy_type = a->policy_type;
1285 aa.is_private = a->is_private;
1287 if (a->is_private) {
1288 aa.is_private = 1;
1289 } else {
1290 tor_addr_copy_tight(&aa.addr, &a->addr);
1293 return (unsigned) siphash24g(&aa, sizeof(aa));
1296 HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
1297 policy_eq)
1298 HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
1299 policy_eq, 0.6, tor_reallocarray_, tor_free_)
1301 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
1302 * "canonical" copy of that addr_policy_t; the canonical copy is a single
1303 * reference-counted object. */
1304 addr_policy_t *
1305 addr_policy_get_canonical_entry(addr_policy_t *e)
1307 policy_map_ent_t search, *found;
1308 if (e->is_canonical)
1309 return e;
1311 search.policy = e;
1312 found = HT_FIND(policy_map, &policy_root, &search);
1313 if (!found) {
1314 found = tor_malloc_zero(sizeof(policy_map_ent_t));
1315 found->policy = tor_memdup(e, sizeof(addr_policy_t));
1316 found->policy->is_canonical = 1;
1317 found->policy->refcnt = 0;
1318 HT_INSERT(policy_map, &policy_root, found);
1321 tor_assert(!cmp_single_addr_policy(found->policy, e));
1322 ++found->policy->refcnt;
1323 return found->policy;
1326 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1327 * addr and port are both known. */
1328 static addr_policy_result_t
1329 compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
1330 const smartlist_t *policy)
1332 /* We know the address and port, and we know the policy, so we can just
1333 * compute an exact match. */
1334 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1335 if (tmpe->addr.family == AF_UNSPEC) {
1336 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1337 "matches other AF_UNSPEC addresses.");
1339 /* Address is known */
1340 if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1341 CMP_EXACT)) {
1342 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
1343 /* Exact match for the policy */
1344 return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
1345 ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
1348 } SMARTLIST_FOREACH_END(tmpe);
1350 /* accept all by default. */
1351 return ADDR_POLICY_ACCEPTED;
1354 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1355 * addr is known but port is not. */
1356 static addr_policy_result_t
1357 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
1358 const smartlist_t *policy)
1360 /* We look to see if there's a definite match. If so, we return that
1361 match's value, unless there's an intervening possible match that says
1362 something different. */
1363 int maybe_accept = 0, maybe_reject = 0;
1365 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1366 if (tmpe->addr.family == AF_UNSPEC) {
1367 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1368 "matches other AF_UNSPEC addresses.");
1370 if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1371 CMP_EXACT)) {
1372 if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
1373 /* Definitely matches, since it covers all ports. */
1374 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1375 /* If we already hit a clause that might trigger a 'reject', than we
1376 * can't be sure of this certain 'accept'.*/
1377 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1378 ADDR_POLICY_ACCEPTED;
1379 } else {
1380 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1381 ADDR_POLICY_REJECTED;
1383 } else {
1384 /* Might match. */
1385 if (tmpe->policy_type == ADDR_POLICY_REJECT)
1386 maybe_reject = 1;
1387 else
1388 maybe_accept = 1;
1391 } SMARTLIST_FOREACH_END(tmpe);
1393 /* accept all by default. */
1394 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1397 /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1398 * port is known but address is not. */
1399 static addr_policy_result_t
1400 compare_unknown_tor_addr_to_addr_policy(uint16_t port,
1401 const smartlist_t *policy)
1403 /* We look to see if there's a definite match. If so, we return that
1404 match's value, unless there's an intervening possible match that says
1405 something different. */
1406 int maybe_accept = 0, maybe_reject = 0;
1408 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1409 if (tmpe->addr.family == AF_UNSPEC) {
1410 log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1411 "matches other AF_UNSPEC addresses.");
1413 if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
1414 if (tmpe->maskbits == 0) {
1415 /* Definitely matches, since it covers all addresses. */
1416 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1417 /* If we already hit a clause that might trigger a 'reject', than we
1418 * can't be sure of this certain 'accept'.*/
1419 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1420 ADDR_POLICY_ACCEPTED;
1421 } else {
1422 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1423 ADDR_POLICY_REJECTED;
1425 } else {
1426 /* Might match. */
1427 if (tmpe->policy_type == ADDR_POLICY_REJECT)
1428 maybe_reject = 1;
1429 else
1430 maybe_accept = 1;
1433 } SMARTLIST_FOREACH_END(tmpe);
1435 /* accept all by default. */
1436 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1439 /** Decide whether a given addr:port is definitely accepted,
1440 * definitely rejected, probably accepted, or probably rejected by a
1441 * given policy. If <b>addr</b> is 0, we don't know the IP of the
1442 * target address. If <b>port</b> is 0, we don't know the port of the
1443 * target address. (At least one of <b>addr</b> and <b>port</b> must be
1444 * provided. If you want to know whether a policy would definitely reject
1445 * an unknown address:port, use policy_is_reject_star().)
1447 * We could do better by assuming that some ranges never match typical
1448 * addresses (127.0.0.1, and so on). But we'll try this for now.
1450 MOCK_IMPL(addr_policy_result_t,
1451 compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
1452 const smartlist_t *policy))
1454 if (!policy) {
1455 /* no policy? accept all. */
1456 return ADDR_POLICY_ACCEPTED;
1457 } else if (addr == NULL || tor_addr_is_null(addr)) {
1458 if (port == 0) {
1459 log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
1460 addr ? tor_addr_family(addr) : -1);
1461 return ADDR_POLICY_REJECTED;
1463 return compare_unknown_tor_addr_to_addr_policy(port, policy);
1464 } else if (port == 0) {
1465 return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
1466 } else {
1467 return compare_known_tor_addr_to_addr_policy(addr, port, policy);
1471 /** Return true iff the address policy <b>a</b> covers every case that
1472 * would be covered by <b>b</b>, so that a,b is redundant. */
1473 static int
1474 addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
1476 if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
1477 /* You can't cover a different family. */
1478 return 0;
1480 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
1481 * to "accept *:80". */
1482 if (a->maskbits > b->maskbits) {
1483 /* a has more fixed bits than b; it can't possibly cover b. */
1484 return 0;
1486 if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
1487 /* There's a fixed bit in a that's set differently in b. */
1488 return 0;
1490 return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
1493 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
1494 * that is, there exists an address/port that is covered by <b>a</b> that
1495 * is also covered by <b>b</b>.
1497 static int
1498 addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
1500 maskbits_t minbits;
1501 /* All the bits we care about are those that are set in both
1502 * netmasks. If they are equal in a and b's networkaddresses
1503 * then the networks intersect. If there is a difference,
1504 * then they do not. */
1505 if (a->maskbits < b->maskbits)
1506 minbits = a->maskbits;
1507 else
1508 minbits = b->maskbits;
1509 if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
1510 return 0;
1511 if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
1512 return 0;
1513 return 1;
1516 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
1518 STATIC void
1519 append_exit_policy_string(smartlist_t **policy, const char *more)
1521 config_line_t tmp;
1523 tmp.key = NULL;
1524 tmp.value = (char*) more;
1525 tmp.next = NULL;
1526 if (parse_addr_policy(&tmp, policy, -1)<0) {
1527 log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
1531 /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
1532 void
1533 addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
1535 tor_assert(dest);
1536 tor_assert(addr);
1538 addr_policy_t p, *add;
1539 memset(&p, 0, sizeof(p));
1540 p.policy_type = ADDR_POLICY_REJECT;
1541 p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
1542 tor_addr_copy(&p.addr, addr);
1543 p.prt_min = 1;
1544 p.prt_max = 65535;
1546 add = addr_policy_get_canonical_entry(&p);
1547 if (!*dest)
1548 *dest = smartlist_new();
1549 smartlist_add(*dest, add);
1550 log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
1551 fmt_addr(addr));
1554 /* Is addr public for the purposes of rejection? */
1555 static int
1556 tor_addr_is_public_for_reject(const tor_addr_t *addr)
1558 return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
1559 && !tor_addr_is_multicast(addr));
1562 /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
1563 * Filter the address, only adding an IPv4 reject rule if ipv4_rules
1564 * is true, and similarly for ipv6_rules. Check each address returns true for
1565 * tor_addr_is_public_for_reject before adding it.
1567 static void
1568 addr_policy_append_reject_addr_filter(smartlist_t **dest,
1569 const tor_addr_t *addr,
1570 int ipv4_rules,
1571 int ipv6_rules)
1573 tor_assert(dest);
1574 tor_assert(addr);
1576 /* Only reject IP addresses which are public */
1577 if (tor_addr_is_public_for_reject(addr)) {
1579 /* Reject IPv4 addresses and IPv6 addresses based on the filters */
1580 int is_ipv4 = tor_addr_is_v4(addr);
1581 if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
1582 addr_policy_append_reject_addr(dest, addr);
1587 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1588 * list as needed. */
1589 void
1590 addr_policy_append_reject_addr_list(smartlist_t **dest,
1591 const smartlist_t *addrs)
1593 tor_assert(dest);
1594 tor_assert(addrs);
1596 SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1597 addr_policy_append_reject_addr(dest, addr);
1598 } SMARTLIST_FOREACH_END(addr);
1601 /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1602 * list as needed. Filter using */
1603 static void
1604 addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
1605 const smartlist_t *addrs,
1606 int ipv4_rules,
1607 int ipv6_rules)
1609 tor_assert(dest);
1610 tor_assert(addrs);
1612 SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1613 addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
1614 } SMARTLIST_FOREACH_END(addr);
1617 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
1618 static void
1619 exit_policy_remove_redundancies(smartlist_t *dest)
1621 addr_policy_t *ap, *tmp;
1622 int i, j;
1624 /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
1627 int kill_v4=0, kill_v6=0;
1628 for (i = 0; i < smartlist_len(dest); ++i) {
1629 sa_family_t family;
1630 ap = smartlist_get(dest, i);
1631 family = tor_addr_family(&ap->addr);
1632 if ((family == AF_INET && kill_v4) ||
1633 (family == AF_INET6 && kill_v6)) {
1634 smartlist_del_keeporder(dest, i--);
1635 addr_policy_free(ap);
1636 continue;
1639 if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
1640 /* This is a catch-all line -- later lines are unreachable. */
1641 if (family == AF_INET) {
1642 kill_v4 = 1;
1643 } else if (family == AF_INET6) {
1644 kill_v6 = 1;
1650 /* Step two: for every entry, see if there's a redundant entry
1651 * later on, and remove it. */
1652 for (i = 0; i < smartlist_len(dest)-1; ++i) {
1653 ap = smartlist_get(dest, i);
1654 for (j = i+1; j < smartlist_len(dest); ++j) {
1655 tmp = smartlist_get(dest, j);
1656 tor_assert(j > i);
1657 if (addr_policy_covers(ap, tmp)) {
1658 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1659 policy_write_item(p1, sizeof(p1), tmp, 0);
1660 policy_write_item(p2, sizeof(p2), ap, 0);
1661 log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
1662 "redundant by %s (%d).", p1, j, p2, i);
1663 smartlist_del_keeporder(dest, j--);
1664 addr_policy_free(tmp);
1669 /* Step three: for every entry A, see if there's an entry B making this one
1670 * redundant later on. This is the case if A and B are of the same type
1671 * (accept/reject), A is a subset of B, and there is no other entry of
1672 * different type in between those two that intersects with A.
1674 * Anybody want to double-check the logic here? XXX
1676 for (i = 0; i < smartlist_len(dest)-1; ++i) {
1677 ap = smartlist_get(dest, i);
1678 for (j = i+1; j < smartlist_len(dest); ++j) {
1679 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
1680 // // decreases.
1681 tmp = smartlist_get(dest, j);
1682 if (ap->policy_type != tmp->policy_type) {
1683 if (addr_policy_intersects(ap, tmp))
1684 break;
1685 } else { /* policy_types are equal. */
1686 if (addr_policy_covers(tmp, ap)) {
1687 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1688 policy_write_item(p1, sizeof(p1), ap, 0);
1689 policy_write_item(p2, sizeof(p2), tmp, 0);
1690 log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
1691 "covered by %s.", p1, p2);
1692 smartlist_del_keeporder(dest, i--);
1693 addr_policy_free(ap);
1694 break;
1701 /** Reject private helper for policies_parse_exit_policy_internal: rejects
1702 * publicly routable addresses on this exit relay.
1704 * Add reject entries to the linked list *<b>dest</b>:
1705 * <ul>
1706 * <li>if configured_addresses is non-NULL, add entries that reject each
1707 * tor_addr_t in the list as a destination.
1708 * <li>if reject_interface_addresses is true, add entries that reject each
1709 * public IPv4 and IPv6 address of each interface on this machine.
1710 * <li>if reject_configured_port_addresses is true, add entries that reject
1711 * each IPv4 and IPv6 address configured for a port.
1712 * </ul>
1714 * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
1715 * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
1716 * false.)
1718 * The list in <b>dest</b> is created as needed.
1720 void
1721 policies_parse_exit_policy_reject_private(
1722 smartlist_t **dest,
1723 int ipv6_exit,
1724 const smartlist_t *configured_addresses,
1725 int reject_interface_addresses,
1726 int reject_configured_port_addresses)
1728 tor_assert(dest);
1730 /* Reject configured addresses, if they are from public netblocks. */
1731 if (configured_addresses) {
1732 addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
1733 1, ipv6_exit);
1736 /* Reject configured port addresses, if they are from public netblocks. */
1737 if (reject_configured_port_addresses) {
1738 const smartlist_t *port_addrs = get_configured_ports();
1740 SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
1742 /* Only reject port IP addresses, not port unix sockets */
1743 if (!port->is_unix_addr) {
1744 addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
1746 } SMARTLIST_FOREACH_END(port);
1749 /* Reject local addresses from public netblocks on any interface. */
1750 if (reject_interface_addresses) {
1751 smartlist_t *public_addresses = NULL;
1753 /* Reject public IPv4 addresses on any interface */
1754 public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
1755 addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
1756 free_interface_address6_list(public_addresses);
1758 /* Don't look for IPv6 addresses if we're configured as IPv4-only */
1759 if (ipv6_exit) {
1760 /* Reject public IPv6 addresses on any interface */
1761 public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
1762 addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
1763 free_interface_address6_list(public_addresses);
1767 /* If addresses were added multiple times, remove all but one of them. */
1768 if (*dest) {
1769 exit_policy_remove_redundancies(*dest);
1774 * Iterate through <b>policy</b> looking for redundant entries. Log a
1775 * warning message with the first redundant entry, if any is found.
1777 static void
1778 policies_log_first_redundant_entry(const smartlist_t *policy)
1780 int found_final_effective_entry = 0;
1781 int first_redundant_entry = 0;
1782 tor_assert(policy);
1783 SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
1784 sa_family_t family;
1785 int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
1786 const int i = p_sl_idx;
1788 /* Look for accept/reject *[4|6|]:* entires */
1789 if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
1790 family = tor_addr_family(&p->addr);
1791 /* accept/reject *:* may have already been expanded into
1792 * accept/reject *4:*,accept/reject *6:*
1793 * But handle both forms.
1795 if (family == AF_INET || family == AF_UNSPEC) {
1796 found_ipv4_wildcard = 1;
1798 if (family == AF_INET6 || family == AF_UNSPEC) {
1799 found_ipv6_wildcard = 1;
1803 /* We also find accept *4:*,reject *6:* ; and
1804 * accept *4:*,<other policies>,accept *6:* ; and similar.
1805 * That's ok, because they make any subsequent entries redundant. */
1806 if (found_ipv4_wildcard && found_ipv6_wildcard) {
1807 found_final_effective_entry = 1;
1808 /* if we're not on the final entry in the list */
1809 if (i < smartlist_len(policy) - 1) {
1810 first_redundant_entry = i + 1;
1812 break;
1814 } SMARTLIST_FOREACH_END(p);
1816 /* Work out if there are redundant trailing entries in the policy list */
1817 if (found_final_effective_entry && first_redundant_entry > 0) {
1818 const addr_policy_t *p;
1819 /* Longest possible policy is
1820 * "accept6 ffff:ffff:..255/128:10000-65535",
1821 * which contains a max-length IPv6 address, plus 24 characters. */
1822 char line[TOR_ADDR_BUF_LEN + 32];
1824 tor_assert(first_redundant_entry < smartlist_len(policy));
1825 p = smartlist_get(policy, first_redundant_entry);
1826 /* since we've already parsed the policy into an addr_policy_t struct,
1827 * we might not log exactly what the user typed in */
1828 policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
1829 log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
1830 "redundant, as it follows accept/reject *:* rules for both "
1831 "IPv4 and IPv6. They will be removed from the exit policy. (Use "
1832 "accept/reject *:* as the last entry in any exit policy.)",
1833 line);
1837 #define DEFAULT_EXIT_POLICY \
1838 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
1839 "reject *:563,reject *:1214,reject *:4661-4666," \
1840 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
1842 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
1844 * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
1846 * If <b>rejectprivate</b> is true:
1847 * - prepend "reject private:*" to the policy.
1848 * - prepend entries that reject publicly routable addresses on this exit
1849 * relay by calling policies_parse_exit_policy_reject_private
1851 * If cfg doesn't end in an absolute accept or reject and if
1852 * <b>add_default_policy</b> is true, add the default exit
1853 * policy afterwards.
1855 * Return -1 if we can't parse cfg, else return 0.
1857 * This function is used to parse the exit policy from our torrc. For
1858 * the functions used to parse the exit policy from a router descriptor,
1859 * see router_add_exit_policy.
1861 static int
1862 policies_parse_exit_policy_internal(config_line_t *cfg,
1863 smartlist_t **dest,
1864 int ipv6_exit,
1865 int rejectprivate,
1866 const smartlist_t *configured_addresses,
1867 int reject_interface_addresses,
1868 int reject_configured_port_addresses,
1869 int add_default_policy)
1871 if (!ipv6_exit) {
1872 append_exit_policy_string(dest, "reject *6:*");
1874 if (rejectprivate) {
1875 /* Reject IPv4 and IPv6 reserved private netblocks */
1876 append_exit_policy_string(dest, "reject private:*");
1877 /* Reject IPv4 and IPv6 publicly routable addresses on this exit relay */
1878 policies_parse_exit_policy_reject_private(
1879 dest, ipv6_exit,
1880 configured_addresses,
1881 reject_interface_addresses,
1882 reject_configured_port_addresses);
1884 if (parse_addr_policy(cfg, dest, -1))
1885 return -1;
1887 /* Before we add the default policy and final rejects, check to see if
1888 * there are any lines after accept *:* or reject *:*. These lines have no
1889 * effect, and are most likely an error. */
1890 policies_log_first_redundant_entry(*dest);
1892 if (add_default_policy) {
1893 append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
1894 } else {
1895 append_exit_policy_string(dest, "reject *4:*");
1896 append_exit_policy_string(dest, "reject *6:*");
1898 exit_policy_remove_redundancies(*dest);
1900 return 0;
1903 /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
1905 * Prepend an entry that rejects all IPv6 destinations unless
1906 * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
1908 * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
1909 * - prepend an entry that rejects all destinations in all netblocks
1910 * reserved for private use.
1911 * - prepend entries that reject publicly routable addresses on this exit
1912 * relay by calling policies_parse_exit_policy_internal
1914 * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
1915 * default exit policy entries to <b>result</b> smartlist.
1918 policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
1919 exit_policy_parser_cfg_t options,
1920 const smartlist_t *configured_addresses)
1922 int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
1923 int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
1924 int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
1926 return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
1927 reject_private,
1928 configured_addresses,
1929 reject_private,
1930 reject_private,
1931 add_default);
1934 /** Helper function that adds a copy of addr to a smartlist as long as it is
1935 * non-NULL and not tor_addr_is_null().
1937 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
1939 static void
1940 policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
1942 if (addr && !tor_addr_is_null(addr)) {
1943 tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
1944 tor_addr_copy(addr_copy, addr);
1945 smartlist_add(addr_list, addr_copy);
1949 /** Helper function that adds ipv4h_addr to a smartlist as a tor_addr_t *,
1950 * as long as it is not tor_addr_is_null(), by converting it to a tor_addr_t
1951 * and passing it to policies_add_addr_to_smartlist.
1953 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
1955 static void
1956 policies_copy_ipv4h_to_smartlist(smartlist_t *addr_list, uint32_t ipv4h_addr)
1958 if (ipv4h_addr) {
1959 tor_addr_t ipv4_tor_addr;
1960 tor_addr_from_ipv4h(&ipv4_tor_addr, ipv4h_addr);
1961 policies_copy_addr_to_smartlist(addr_list, &ipv4_tor_addr);
1965 /** Helper function that adds copies of
1966 * or_options->OutboundBindAddressIPv[4|6]_ to a smartlist as tor_addr_t *, as
1967 * long as or_options is non-NULL, and the addresses are not
1968 * tor_addr_is_null(), by passing them to policies_add_addr_to_smartlist.
1970 * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
1972 static void
1973 policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
1974 const or_options_t *or_options)
1976 if (or_options) {
1977 policies_copy_addr_to_smartlist(addr_list,
1978 &or_options->OutboundBindAddressIPv4_);
1979 policies_copy_addr_to_smartlist(addr_list,
1980 &or_options->OutboundBindAddressIPv6_);
1984 /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
1985 * smartlist.
1986 * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
1987 * rejects all IPv6 destinations.
1989 * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
1990 * - prepend an entry that rejects all destinations in all netblocks reserved
1991 * for private use.
1992 * - if local_address is non-zero, treat it as a host-order IPv4 address, and
1993 * add it to the list of configured addresses.
1994 * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
1995 * to the list of configured addresses.
1996 * - if or_options->OutboundBindAddressIPv4_ is not the null tor_addr_t, add
1997 * it to the list of configured addresses.
1998 * - if or_options->OutboundBindAddressIPv6_ is not the null tor_addr_t, add
1999 * it to the list of configured addresses.
2001 * If <b>or_options->BridgeRelay</b> is false, append entries of default
2002 * Tor exit policy into <b>result</b> smartlist.
2004 * If or_options->ExitRelay is false, then make our exit policy into
2005 * "reject *:*" regardless.
2008 policies_parse_exit_policy_from_options(const or_options_t *or_options,
2009 uint32_t local_address,
2010 const tor_addr_t *ipv6_local_address,
2011 smartlist_t **result)
2013 exit_policy_parser_cfg_t parser_cfg = 0;
2014 smartlist_t *configured_addresses = NULL;
2015 int rv = 0;
2017 /* Short-circuit for non-exit relays */
2018 if (or_options->ExitRelay == 0) {
2019 append_exit_policy_string(result, "reject *4:*");
2020 append_exit_policy_string(result, "reject *6:*");
2021 return 0;
2024 configured_addresses = smartlist_new();
2026 /* Configure the parser */
2027 if (or_options->IPv6Exit) {
2028 parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
2031 if (or_options->ExitPolicyRejectPrivate) {
2032 parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
2035 if (!or_options->BridgeRelay) {
2036 parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
2039 /* Copy the configured addresses into the tor_addr_t* list */
2040 policies_copy_ipv4h_to_smartlist(configured_addresses, local_address);
2041 policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
2042 policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2043 or_options);
2045 rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
2046 configured_addresses);
2048 SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2049 smartlist_free(configured_addresses);
2051 return rv;
2054 /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
2055 * *<b>dest</b> as needed. */
2056 void
2057 policies_exit_policy_append_reject_star(smartlist_t **dest)
2059 append_exit_policy_string(dest, "reject *4:*");
2060 append_exit_policy_string(dest, "reject *6:*");
2063 /** Replace the exit policy of <b>node</b> with reject *:* */
2064 void
2065 policies_set_node_exitpolicy_to_reject_all(node_t *node)
2067 node->rejects_all = 1;
2070 /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
2071 * allows exiting to <b>port</b>. Otherwise, return 0. */
2072 static int
2073 exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
2075 uint32_t mask, ip, i;
2076 /* Is this /8 rejected (1), or undecided (0)? */
2077 char subnet_status[256];
2079 memset(subnet_status, 0, sizeof(subnet_status));
2080 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2081 if (tor_addr_family(&p->addr) != AF_INET)
2082 continue; /* IPv4 only for now */
2083 if (p->prt_min > port || p->prt_max < port)
2084 continue; /* Doesn't cover our port. */
2085 mask = 0;
2086 tor_assert(p->maskbits <= 32);
2088 if (p->maskbits)
2089 mask = UINT32_MAX<<(32-p->maskbits);
2090 ip = tor_addr_to_ipv4h(&p->addr);
2092 /* Calculate the first and last subnet that this exit policy touches
2093 * and set it as loop boundaries. */
2094 for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
2095 tor_addr_t addr;
2096 if (subnet_status[i] != 0)
2097 continue; /* We already reject some part of this /8 */
2098 tor_addr_from_ipv4h(&addr, i<<24);
2099 if (tor_addr_is_internal(&addr, 0))
2100 continue; /* Local or non-routable addresses */
2101 if (p->policy_type == ADDR_POLICY_ACCEPT) {
2102 if (p->maskbits > 8)
2103 continue; /* Narrower than a /8. */
2104 /* We found an allowed subnet of at least size /8. Done
2105 * for this port! */
2106 return 1;
2107 } else if (p->policy_type == ADDR_POLICY_REJECT) {
2108 subnet_status[i] = 1;
2111 } SMARTLIST_FOREACH_END(p);
2112 return 0;
2115 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
2116 * it allows exit to at least one /8 address space for at least
2117 * two of ports 80, 443, and 6667. */
2119 exit_policy_is_general_exit(smartlist_t *policy)
2121 static const int ports[] = { 80, 443, 6667 };
2122 int n_allowed = 0;
2123 int i;
2124 if (!policy) /*XXXX disallow NULL policies? */
2125 return 0;
2127 for (i = 0; i < 3; ++i) {
2128 n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
2130 return n_allowed >= 2;
2133 /** Return false if <b>policy</b> might permit access to some addr:port;
2134 * otherwise if we are certain it rejects everything, return true. */
2136 policy_is_reject_star(const smartlist_t *policy, sa_family_t family)
2138 if (!policy) /*XXXX disallow NULL policies? */
2139 return 1;
2140 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2141 if (p->policy_type == ADDR_POLICY_ACCEPT &&
2142 (tor_addr_family(&p->addr) == family ||
2143 tor_addr_family(&p->addr) == AF_UNSPEC)) {
2144 return 0;
2145 } else if (p->policy_type == ADDR_POLICY_REJECT &&
2146 p->prt_min <= 1 && p->prt_max == 65535 &&
2147 p->maskbits == 0 &&
2148 (tor_addr_family(&p->addr) == family ||
2149 tor_addr_family(&p->addr) == AF_UNSPEC)) {
2150 return 1;
2152 } SMARTLIST_FOREACH_END(p);
2153 return 1;
2156 /** Write a single address policy to the buf_len byte buffer at buf. Return
2157 * the number of characters written, or -1 on failure. */
2159 policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
2160 int format_for_desc)
2162 size_t written = 0;
2163 char addrbuf[TOR_ADDR_BUF_LEN];
2164 const char *addrpart;
2165 int result;
2166 const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
2167 const sa_family_t family = tor_addr_family(&policy->addr);
2168 const int is_ip6 = (family == AF_INET6);
2170 tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
2172 /* write accept/reject 1.2.3.4 */
2173 if (policy->is_private) {
2174 addrpart = "private";
2175 } else if (policy->maskbits == 0) {
2176 if (format_for_desc)
2177 addrpart = "*";
2178 else if (family == AF_INET6)
2179 addrpart = "*6";
2180 else if (family == AF_INET)
2181 addrpart = "*4";
2182 else
2183 addrpart = "*";
2184 } else {
2185 addrpart = addrbuf;
2188 result = tor_snprintf(buf, buflen, "%s%s %s",
2189 is_accept ? "accept" : "reject",
2190 (is_ip6&&format_for_desc)?"6":"",
2191 addrpart);
2192 if (result < 0)
2193 return -1;
2194 written += strlen(buf);
2195 /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
2196 the mask is 0, we already wrote "*". */
2197 if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
2198 if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
2199 return -1;
2200 written += strlen(buf+written);
2202 if (policy->prt_min <= 1 && policy->prt_max == 65535) {
2203 /* There is no port set; write ":*" */
2204 if (written+4 > buflen)
2205 return -1;
2206 strlcat(buf+written, ":*", buflen-written);
2207 written += 2;
2208 } else if (policy->prt_min == policy->prt_max) {
2209 /* There is only one port; write ":80". */
2210 result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
2211 if (result<0)
2212 return -1;
2213 written += result;
2214 } else {
2215 /* There is a range of ports; write ":79-80". */
2216 result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
2217 policy->prt_min, policy->prt_max);
2218 if (result<0)
2219 return -1;
2220 written += result;
2222 if (written < buflen)
2223 buf[written] = '\0';
2224 else
2225 return -1;
2227 return (int)written;
2230 /** Create a new exit policy summary, initially only with a single
2231 * port 1-64k item */
2232 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
2233 * RB-tree if that turns out to matter. */
2234 static smartlist_t *
2235 policy_summary_create(void)
2237 smartlist_t *summary;
2238 policy_summary_item_t* item;
2240 item = tor_malloc_zero(sizeof(policy_summary_item_t));
2241 item->prt_min = 1;
2242 item->prt_max = 65535;
2243 item->reject_count = 0;
2244 item->accepted = 0;
2246 summary = smartlist_new();
2247 smartlist_add(summary, item);
2249 return summary;
2252 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
2253 * The current item is changed to end at new-starts - 1, the new item
2254 * copies reject_count and accepted from the old item,
2255 * starts at new_starts and ends at the port where the original item
2256 * previously ended.
2258 static policy_summary_item_t*
2259 policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
2261 policy_summary_item_t* new;
2263 new = tor_malloc_zero(sizeof(policy_summary_item_t));
2264 new->prt_min = new_starts;
2265 new->prt_max = old->prt_max;
2266 new->reject_count = old->reject_count;
2267 new->accepted = old->accepted;
2269 old->prt_max = new_starts-1;
2271 tor_assert(old->prt_min <= old->prt_max);
2272 tor_assert(new->prt_min <= new->prt_max);
2273 return new;
2276 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
2277 * my immortal soul, he can clean it up himself. */
2278 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
2280 #define REJECT_CUTOFF_COUNT (1<<25)
2281 /** Split an exit policy summary so that prt_min and prt_max
2282 * fall at exactly the start and end of an item respectively.
2284 static int
2285 policy_summary_split(smartlist_t *summary,
2286 uint16_t prt_min, uint16_t prt_max)
2288 int start_at_index;
2290 int i = 0;
2292 while (AT(i)->prt_max < prt_min)
2293 i++;
2294 if (AT(i)->prt_min != prt_min) {
2295 policy_summary_item_t* new_item;
2296 new_item = policy_summary_item_split(AT(i), prt_min);
2297 smartlist_insert(summary, i+1, new_item);
2298 i++;
2300 start_at_index = i;
2302 while (AT(i)->prt_max < prt_max)
2303 i++;
2304 if (AT(i)->prt_max != prt_max) {
2305 policy_summary_item_t* new_item;
2306 new_item = policy_summary_item_split(AT(i), prt_max+1);
2307 smartlist_insert(summary, i+1, new_item);
2310 return start_at_index;
2313 /** Mark port ranges as accepted if they are below the reject_count */
2314 static void
2315 policy_summary_accept(smartlist_t *summary,
2316 uint16_t prt_min, uint16_t prt_max)
2318 int i = policy_summary_split(summary, prt_min, prt_max);
2319 while (i < smartlist_len(summary) &&
2320 AT(i)->prt_max <= prt_max) {
2321 if (!AT(i)->accepted &&
2322 AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
2323 AT(i)->accepted = 1;
2324 i++;
2326 tor_assert(i < smartlist_len(summary) || prt_max==65535);
2329 /** Count the number of addresses in a network with prefixlen maskbits
2330 * against the given portrange. */
2331 static void
2332 policy_summary_reject(smartlist_t *summary,
2333 maskbits_t maskbits,
2334 uint16_t prt_min, uint16_t prt_max)
2336 int i = policy_summary_split(summary, prt_min, prt_max);
2337 /* XXX: ipv4 specific */
2338 uint64_t count = (U64_LITERAL(1) << (32-maskbits));
2339 while (i < smartlist_len(summary) &&
2340 AT(i)->prt_max <= prt_max) {
2341 AT(i)->reject_count += count;
2342 i++;
2344 tor_assert(i < smartlist_len(summary) || prt_max==65535);
2347 /** Add a single exit policy item to our summary:
2348 * If it is an accept ignore it unless it is for all IP addresses
2349 * ("*"), i.e. it's prefixlen/maskbits is 0, else call
2350 * policy_summary_accept().
2351 * If it's a reject ignore it if it is about one of the private
2352 * networks, else call policy_summary_reject().
2354 static void
2355 policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
2357 if (p->policy_type == ADDR_POLICY_ACCEPT) {
2358 if (p->maskbits == 0) {
2359 policy_summary_accept(summary, p->prt_min, p->prt_max);
2361 } else if (p->policy_type == ADDR_POLICY_REJECT) {
2363 int is_private = 0;
2364 int i;
2365 for (i = 0; private_nets[i]; ++i) {
2366 tor_addr_t addr;
2367 maskbits_t maskbits;
2368 if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
2369 &maskbits, NULL, NULL)<0) {
2370 tor_assert(0);
2372 if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
2373 p->maskbits == maskbits) {
2374 is_private = 1;
2375 break;
2379 if (!is_private) {
2380 policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
2382 } else
2383 tor_assert(0);
2386 /** Create a string representing a summary for an exit policy.
2387 * The summary will either be an "accept" plus a comma-separated list of port
2388 * ranges or a "reject" plus port-ranges, depending on which is shorter.
2390 * If no exits are allowed at all then "reject 1-65535" is returned. If no
2391 * ports are blocked instead of "reject " we return "accept 1-65535". (These
2392 * are an exception to the shorter-representation-wins rule).
2394 char *
2395 policy_summarize(smartlist_t *policy, sa_family_t family)
2397 smartlist_t *summary = policy_summary_create();
2398 smartlist_t *accepts, *rejects;
2399 int i, last, start_prt;
2400 size_t accepts_len, rejects_len;
2401 char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
2402 const char *prefix;
2404 tor_assert(policy);
2406 /* Create the summary list */
2407 SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2408 sa_family_t f = tor_addr_family(&p->addr);
2409 if (f != AF_INET && f != AF_INET6) {
2410 log_warn(LD_BUG, "Weird family when summarizing address policy");
2412 if (f != family)
2413 continue;
2414 /* XXXX-ipv6 More family work is needed */
2415 policy_summary_add_item(summary, p);
2416 } SMARTLIST_FOREACH_END(p);
2418 /* Now create two lists of strings, one for accepted and one
2419 * for rejected ports. We take care to merge ranges so that
2420 * we avoid getting stuff like "1-4,5-9,10", instead we want
2421 * "1-10"
2423 i = 0;
2424 start_prt = 1;
2425 accepts = smartlist_new();
2426 rejects = smartlist_new();
2427 while (1) {
2428 last = i == smartlist_len(summary)-1;
2429 if (last ||
2430 AT(i)->accepted != AT(i+1)->accepted) {
2431 char buf[POLICY_BUF_LEN];
2433 if (start_prt == AT(i)->prt_max)
2434 tor_snprintf(buf, sizeof(buf), "%d", start_prt);
2435 else
2436 tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
2438 if (AT(i)->accepted)
2439 smartlist_add(accepts, tor_strdup(buf));
2440 else
2441 smartlist_add(rejects, tor_strdup(buf));
2443 if (last)
2444 break;
2446 start_prt = AT(i+1)->prt_min;
2448 i++;
2451 /* Figure out which of the two stringlists will be shorter and use
2452 * that to build the result
2454 if (smartlist_len(accepts) == 0) { /* no exits at all */
2455 result = tor_strdup("reject 1-65535");
2456 goto cleanup;
2458 if (smartlist_len(rejects) == 0) { /* no rejects at all */
2459 result = tor_strdup("accept 1-65535");
2460 goto cleanup;
2463 accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
2464 rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
2466 if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
2467 accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
2468 char *c;
2469 shorter_str = accepts_str;
2470 prefix = "accept";
2472 c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
2473 while (*c != ',' && c >= shorter_str)
2474 c--;
2475 tor_assert(c >= shorter_str);
2476 tor_assert(*c == ',');
2477 *c = '\0';
2479 } else if (rejects_len < accepts_len) {
2480 shorter_str = rejects_str;
2481 prefix = "reject";
2482 } else {
2483 shorter_str = accepts_str;
2484 prefix = "accept";
2487 tor_asprintf(&result, "%s %s", prefix, shorter_str);
2489 cleanup:
2490 /* cleanup */
2491 SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
2492 smartlist_free(summary);
2494 tor_free(accepts_str);
2495 SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
2496 smartlist_free(accepts);
2498 tor_free(rejects_str);
2499 SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
2500 smartlist_free(rejects);
2502 return result;
2505 /** Convert a summarized policy string into a short_policy_t. Return NULL
2506 * if the string is not well-formed. */
2507 short_policy_t *
2508 parse_short_policy(const char *summary)
2510 const char *orig_summary = summary;
2511 short_policy_t *result;
2512 int is_accept;
2513 int n_entries;
2514 short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
2515 const char *next;
2517 if (!strcmpstart(summary, "accept ")) {
2518 is_accept = 1;
2519 summary += strlen("accept ");
2520 } else if (!strcmpstart(summary, "reject ")) {
2521 is_accept = 0;
2522 summary += strlen("reject ");
2523 } else {
2524 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
2525 return NULL;
2528 n_entries = 0;
2529 for ( ; *summary; summary = next) {
2530 const char *comma = strchr(summary, ',');
2531 unsigned low, high;
2532 char dummy;
2533 char ent_buf[32];
2534 size_t len;
2536 next = comma ? comma+1 : strchr(summary, '\0');
2537 len = comma ? (size_t)(comma - summary) : strlen(summary);
2539 if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
2540 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
2541 escaped(orig_summary));
2542 return NULL;
2545 if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
2546 /* unrecognized entry format. skip it. */
2547 continue;
2549 if (len < 1) {
2550 /* empty; skip it. */
2551 /* XXX This happens to be unreachable, since if len==0, then *summary is
2552 * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
2553 continue;
2556 memcpy(ent_buf, summary, len);
2557 ent_buf[len] = '\0';
2559 if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
2560 if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
2561 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2562 "Found bad entry in policy summary %s", escaped(orig_summary));
2563 return NULL;
2565 } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
2566 if (low<1 || low>65535) {
2567 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2568 "Found bad entry in policy summary %s", escaped(orig_summary));
2569 return NULL;
2571 high = low;
2572 } else {
2573 log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
2574 escaped(orig_summary));
2575 return NULL;
2578 entries[n_entries].min_port = low;
2579 entries[n_entries].max_port = high;
2580 n_entries++;
2583 if (n_entries == 0) {
2584 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2585 "Found no port-range entries in summary %s", escaped(orig_summary));
2586 return NULL;
2590 size_t size = STRUCT_OFFSET(short_policy_t, entries) +
2591 sizeof(short_policy_entry_t)*(n_entries);
2592 result = tor_malloc_zero(size);
2594 tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
2597 result->is_accept = is_accept;
2598 result->n_entries = n_entries;
2599 memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
2600 return result;
2603 /** Write <b>policy</b> back out into a string. Used only for unit tests
2604 * currently. */
2605 char *
2606 write_short_policy(const short_policy_t *policy)
2608 int i;
2609 char *answer;
2610 smartlist_t *sl = smartlist_new();
2612 smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
2614 for (i=0; i < policy->n_entries; i++) {
2615 const short_policy_entry_t *e = &policy->entries[i];
2616 if (e->min_port == e->max_port) {
2617 smartlist_add_asprintf(sl, "%d", e->min_port);
2618 } else {
2619 smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
2621 if (i < policy->n_entries-1)
2622 smartlist_add(sl, tor_strdup(","));
2624 answer = smartlist_join_strings(sl, "", 0, NULL);
2625 SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
2626 smartlist_free(sl);
2627 return answer;
2630 /** Release all storage held in <b>policy</b>. */
2631 void
2632 short_policy_free(short_policy_t *policy)
2634 tor_free(policy);
2637 /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
2638 * or rejected by the summarized policy <b>policy</b>. Return values are as
2639 * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
2640 * functions, requires the <b>port</b> be specified. */
2641 addr_policy_result_t
2642 compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
2643 const short_policy_t *policy)
2645 int i;
2646 int found_match = 0;
2647 int accept;
2649 tor_assert(port != 0);
2651 if (addr && tor_addr_is_null(addr))
2652 addr = NULL; /* Unspec means 'no address at all,' in this context. */
2654 if (addr && get_options()->ClientRejectInternalAddresses &&
2655 (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
2656 return ADDR_POLICY_REJECTED;
2658 for (i=0; i < policy->n_entries; ++i) {
2659 const short_policy_entry_t *e = &policy->entries[i];
2660 if (e->min_port <= port && port <= e->max_port) {
2661 found_match = 1;
2662 break;
2666 if (found_match)
2667 accept = policy->is_accept;
2668 else
2669 accept = ! policy->is_accept;
2671 /* ???? are these right? -NM */
2672 /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
2673 * case here, because it would cause clients to believe that the node
2674 * allows exit enclaving. Trying it anyway would open up a cool attack
2675 * where the node refuses due to exitpolicy, the client reacts in
2676 * surprise by rewriting the node's exitpolicy to reject *:*, and then
2677 * an adversary targets users by causing them to attempt such connections
2678 * to 98% of the exits.
2680 * Once microdescriptors can handle addresses in special cases (e.g. if
2681 * we ever solve ticket 1774), we can provide certainty here. -RD */
2682 if (accept)
2683 return ADDR_POLICY_PROBABLY_ACCEPTED;
2684 else
2685 return ADDR_POLICY_REJECTED;
2688 /** Return true iff <b>policy</b> seems reject all ports */
2690 short_policy_is_reject_star(const short_policy_t *policy)
2692 /* This doesn't need to be as much on the lookout as policy_is_reject_star,
2693 * since policy summaries are from the consensus or from consensus
2694 * microdescs.
2696 tor_assert(policy);
2697 /* Check for an exact match of "reject 1-65535". */
2698 return (policy->is_accept == 0 && policy->n_entries == 1 &&
2699 policy->entries[0].min_port == 1 &&
2700 policy->entries[0].max_port == 65535);
2703 /** Decide whether addr:port is probably or definitely accepted or rejected by
2704 * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
2705 * interpretation. */
2706 addr_policy_result_t
2707 compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
2708 const node_t *node)
2710 if (node->rejects_all)
2711 return ADDR_POLICY_REJECTED;
2713 if (addr && tor_addr_family(addr) == AF_INET6) {
2714 const short_policy_t *p = NULL;
2715 if (node->ri)
2716 p = node->ri->ipv6_exit_policy;
2717 else if (node->md)
2718 p = node->md->ipv6_exit_policy;
2719 if (p)
2720 return compare_tor_addr_to_short_policy(addr, port, p);
2721 else
2722 return ADDR_POLICY_REJECTED;
2725 if (node->ri) {
2726 return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
2727 } else if (node->md) {
2728 if (node->md->exit_policy == NULL)
2729 return ADDR_POLICY_REJECTED;
2730 else
2731 return compare_tor_addr_to_short_policy(addr, port,
2732 node->md->exit_policy);
2733 } else {
2734 return ADDR_POLICY_PROBABLY_REJECTED;
2739 * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
2740 * representation of the list.
2741 * If <b>include_ipv4</b> is true, include IPv4 entries.
2742 * If <b>include_ipv6</b> is true, include IPv6 entries.
2744 char *
2745 policy_dump_to_string(const smartlist_t *policy_list,
2746 int include_ipv4,
2747 int include_ipv6)
2749 smartlist_t *policy_string_list;
2750 char *policy_string = NULL;
2752 policy_string_list = smartlist_new();
2754 SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
2755 char *pbuf;
2756 int bytes_written_to_pbuf;
2757 if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2758 continue; /* Don't include IPv6 parts of address policy */
2760 if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2761 continue; /* Don't include IPv4 parts of address policy */
2764 pbuf = tor_malloc(POLICY_BUF_LEN);
2765 bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2767 if (bytes_written_to_pbuf < 0) {
2768 log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
2769 tor_free(pbuf);
2770 goto done;
2773 smartlist_add(policy_string_list,pbuf);
2774 } SMARTLIST_FOREACH_END(tmpe);
2776 policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
2778 done:
2779 SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
2780 smartlist_free(policy_string_list);
2782 return policy_string;
2785 /** Implementation for GETINFO control command: knows the answer for questions
2786 * about "exit-policy/..." */
2788 getinfo_helper_policies(control_connection_t *conn,
2789 const char *question, char **answer,
2790 const char **errmsg)
2792 (void) conn;
2793 (void) errmsg;
2794 if (!strcmp(question, "exit-policy/default")) {
2795 *answer = tor_strdup(DEFAULT_EXIT_POLICY);
2796 } else if (!strcmp(question, "exit-policy/reject-private/default")) {
2797 smartlist_t *private_policy_strings;
2798 const char **priv = private_nets;
2800 private_policy_strings = smartlist_new();
2802 while (*priv != NULL) {
2803 /* IPv6 addresses are in "[]" and contain ":",
2804 * IPv4 addresses are not in "[]" and contain "." */
2805 smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
2806 priv++;
2809 *answer = smartlist_join_strings(private_policy_strings,
2810 ",", 0, NULL);
2812 SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
2813 smartlist_free(private_policy_strings);
2814 } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
2815 const or_options_t *options = get_options();
2816 const routerinfo_t *me = router_get_my_routerinfo();
2818 if (!me) {
2819 *errmsg = "router_get_my_routerinfo returned NULL";
2820 return -1;
2823 if (!options->ExitPolicyRejectPrivate) {
2824 *answer = tor_strdup("");
2825 return 0;
2828 smartlist_t *private_policy_list = smartlist_new();
2829 smartlist_t *configured_addresses = smartlist_new();
2831 /* Copy the configured addresses into the tor_addr_t* list */
2832 policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
2833 policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
2834 policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2835 options);
2837 policies_parse_exit_policy_reject_private(
2838 &private_policy_list,
2839 options->IPv6Exit,
2840 configured_addresses,
2841 1, 1);
2842 *answer = policy_dump_to_string(private_policy_list, 1, 1);
2844 addr_policy_list_free(private_policy_list);
2845 SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2846 smartlist_free(configured_addresses);
2847 } else if (!strcmpstart(question, "exit-policy/")) {
2848 const routerinfo_t *me = router_get_my_routerinfo();
2850 int include_ipv4 = 0;
2851 int include_ipv6 = 0;
2853 if (!strcmp(question, "exit-policy/ipv4")) {
2854 include_ipv4 = 1;
2855 } else if (!strcmp(question, "exit-policy/ipv6")) {
2856 include_ipv6 = 1;
2857 } else if (!strcmp(question, "exit-policy/full")) {
2858 include_ipv4 = include_ipv6 = 1;
2859 } else {
2860 return 0; /* No such key. */
2863 if (!me) {
2864 *errmsg = "router_get_my_routerinfo returned NULL";
2865 return -1;
2868 *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
2870 return 0;
2873 /** Release all storage held by <b>p</b>. */
2874 void
2875 addr_policy_list_free(smartlist_t *lst)
2877 if (!lst)
2878 return;
2879 SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
2880 smartlist_free(lst);
2883 /** Release all storage held by <b>p</b>. */
2884 void
2885 addr_policy_free(addr_policy_t *p)
2887 if (!p)
2888 return;
2890 if (--p->refcnt <= 0) {
2891 if (p->is_canonical) {
2892 policy_map_ent_t search, *found;
2893 search.policy = p;
2894 found = HT_REMOVE(policy_map, &policy_root, &search);
2895 if (found) {
2896 tor_assert(p == found->policy);
2897 tor_free(found);
2900 tor_free(p);
2904 /** Release all storage held by policy variables. */
2905 void
2906 policies_free_all(void)
2908 addr_policy_list_free(reachable_or_addr_policy);
2909 reachable_or_addr_policy = NULL;
2910 addr_policy_list_free(reachable_dir_addr_policy);
2911 reachable_dir_addr_policy = NULL;
2912 addr_policy_list_free(socks_policy);
2913 socks_policy = NULL;
2914 addr_policy_list_free(dir_policy);
2915 dir_policy = NULL;
2916 addr_policy_list_free(authdir_reject_policy);
2917 authdir_reject_policy = NULL;
2918 addr_policy_list_free(authdir_invalid_policy);
2919 authdir_invalid_policy = NULL;
2920 addr_policy_list_free(authdir_badexit_policy);
2921 authdir_badexit_policy = NULL;
2923 if (!HT_EMPTY(&policy_root)) {
2924 policy_map_ent_t **ent;
2925 int n = 0;
2926 char buf[POLICY_BUF_LEN];
2928 log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
2929 (int)HT_SIZE(&policy_root));
2931 /* Note the first 10 cached policies to try to figure out where they
2932 * might be coming from. */
2933 HT_FOREACH(ent, policy_map, &policy_root) {
2934 if (++n > 10)
2935 break;
2936 if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
2937 log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
2940 HT_CLEAR(policy_map, &policy_root);