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