Make sure we don't run off the end of the list
[tor/rransom.git] / src / or / policies.c
blobf0f96e659badd3df7cad84c6924966a35aa2fe71
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char policies_c_id[] = \
7 "$Id$";
9 /**
10 * \file policies.c
11 * \brief Code to parse and use address policies and exit policies.
12 **/
14 #include "or.h"
15 #include "ht.h"
17 /** Policy that addresses for incoming SOCKS connections must match. */
18 static smartlist_t *socks_policy = NULL;
19 /** Policy that addresses for incoming directory connections must match. */
20 static smartlist_t *dir_policy = NULL;
21 /** Policy that addresses for incoming router descriptors must match in order
22 * to be published by us. */
23 static smartlist_t *authdir_reject_policy = NULL;
24 /** Policy that addresses for incoming router descriptors must match in order
25 * to be marked as valid in our networkstatus. */
26 static smartlist_t *authdir_invalid_policy = NULL;
27 /** Policy that addresses for incoming router descriptors must <b>not</b>
28 * match in order to not be marked as BadDirectory. */
29 static smartlist_t *authdir_baddir_policy = NULL;
30 /** Policy that addresses for incoming router descriptors must <b>not</b>
31 * match in order to not be marked as BadExit. */
32 static smartlist_t *authdir_badexit_policy = NULL;
34 /** Parsed addr_policy_t describing which addresses we believe we can start
35 * circuits at. */
36 static smartlist_t *reachable_or_addr_policy = NULL;
37 /** Parsed addr_policy_t describing which addresses we believe we can connect
38 * to directories at. */
39 static smartlist_t *reachable_dir_addr_policy = NULL;
41 /** Element of an exit policy summary */
42 typedef struct policy_summary_item_t {
43 uint16_t prt_min; /**< Lowest port number to accept/reject. */
44 uint16_t prt_max; /**< Highest port number to accept/reject. */
45 uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
46 this portrange. */
47 int accepted:1; /** Has this port already been accepted */
48 } policy_summary_item_t;
50 smartlist_t *policy_summary_create(void);
51 void policy_summary_accept(smartlist_t *summary, uint16_t prt_min, uint16_t prt_max);
52 void policy_summary_reject(smartlist_t *summary, maskbits_t maskbits, uint16_t prt_min, uint16_t prt_max);
53 void policy_summary_add_item(smartlist_t *summary, addr_policy_t *p);
54 int policy_summary_split(smartlist_t *summary, uint16_t prt_min, uint16_t prt_max);
55 policy_summary_item_t* policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts);
57 /** Private networks. This list is used in two places, once to expand the
58 * "private" keyword when parsing our own exit policy, secondly to ignore
59 * just such networks when building exit policy summaries. It is important
60 * that all authorities agree on that list when creating summaries, so don't
61 * just change this without a proper migration plan and a proposal and stuff.
63 static const char *private_nets[] = {
64 "0.0.0.0/8", "169.254.0.0/16",
65 "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
66 // "fc00::/7", "fe80::/10", "fec0::/10", "::/127",
67 NULL };
69 /** Replace all "private" entries in *<b>policy</b> with their expanded
70 * equivalents. */
71 void
72 policy_expand_private(smartlist_t **policy)
74 uint16_t port_min, port_max;
76 int i;
77 smartlist_t *tmp;
79 if (!*policy) /*XXXX021 disallow NULL policies */
80 return;
82 tmp = smartlist_create();
84 SMARTLIST_FOREACH(*policy, addr_policy_t *, p,
86 if (! p->is_private) {
87 smartlist_add(tmp, p);
88 continue;
90 for (i = 0; private_nets[i]; ++i) {
91 addr_policy_t policy;
92 memcpy(&policy, p, sizeof(addr_policy_t));
93 policy.is_private = 0;
94 policy.is_canonical = 0;
95 if (tor_addr_parse_mask_ports(private_nets[i], &policy.addr,
96 &policy.maskbits, &port_min, &port_max)<0) {
97 tor_assert(0);
99 smartlist_add(tmp, addr_policy_get_canonical_entry(&policy));
101 addr_policy_free(p);
104 smartlist_free(*policy);
105 *policy = tmp;
109 * Given a linked list of config lines containing "allow" and "deny"
110 * tokens, parse them and append the result to <b>dest</b>. Return -1
111 * if any tokens are malformed (and don't append any), else return 0.
113 static int
114 parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
115 int assume_action)
117 smartlist_t *result;
118 smartlist_t *entries;
119 addr_policy_t *item;
120 int r = 0;
122 if (!cfg)
123 return 0;
125 result = smartlist_create();
126 entries = smartlist_create();
127 for (; cfg; cfg = cfg->next) {
128 smartlist_split_string(entries, cfg->value, ",",
129 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
130 SMARTLIST_FOREACH(entries, const char *, ent,
132 log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
133 item = router_parse_addr_policy_item_from_string(ent, assume_action);
134 if (item) {
135 smartlist_add(result, item);
136 } else {
137 log_warn(LD_CONFIG,"Malformed policy '%s'.", ent);
138 r = -1;
141 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
142 smartlist_clear(entries);
144 smartlist_free(entries);
145 if (r == -1) {
146 addr_policy_list_free(result);
147 } else {
148 policy_expand_private(&result);
150 if (*dest) {
151 smartlist_add_all(*dest, result);
152 smartlist_free(result);
153 } else {
154 *dest = result;
158 return r;
161 /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
162 * reachable_(or|dir)_addr_policy. The options should already have
163 * been validated by validate_addr_policies.
165 static int
166 parse_reachable_addresses(void)
168 or_options_t *options = get_options();
169 int ret = 0;
171 if (options->ReachableDirAddresses &&
172 options->ReachableORAddresses &&
173 options->ReachableAddresses) {
174 log_warn(LD_CONFIG,
175 "Both ReachableDirAddresses and ReachableORAddresses are set. "
176 "ReachableAddresses setting will be ignored.");
178 addr_policy_list_free(reachable_or_addr_policy);
179 reachable_or_addr_policy = NULL;
180 if (!options->ReachableORAddresses && options->ReachableAddresses)
181 log_info(LD_CONFIG,
182 "Using ReachableAddresses as ReachableORAddresses.");
183 if (parse_addr_policy(options->ReachableORAddresses ?
184 options->ReachableORAddresses :
185 options->ReachableAddresses,
186 &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
187 log_warn(LD_CONFIG,
188 "Error parsing Reachable%sAddresses entry; ignoring.",
189 options->ReachableORAddresses ? "OR" : "");
190 ret = -1;
193 addr_policy_list_free(reachable_dir_addr_policy);
194 reachable_dir_addr_policy = NULL;
195 if (!options->ReachableDirAddresses && options->ReachableAddresses)
196 log_info(LD_CONFIG,
197 "Using ReachableAddresses as ReachableDirAddresses");
198 if (parse_addr_policy(options->ReachableDirAddresses ?
199 options->ReachableDirAddresses :
200 options->ReachableAddresses,
201 &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
202 if (options->ReachableDirAddresses)
203 log_warn(LD_CONFIG,
204 "Error parsing ReachableDirAddresses entry; ignoring.");
205 ret = -1;
207 return ret;
210 /** Return true iff the firewall options might block any address:port
211 * combination.
214 firewall_is_fascist_or(void)
216 return reachable_or_addr_policy != NULL;
219 /** Return true iff <b>policy</b> (possibly NULL) will allow a
220 * connection to <b>addr</b>:<b>port</b>.
222 static int
223 addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
224 smartlist_t *policy)
226 addr_policy_result_t p;
227 p = compare_tor_addr_to_addr_policy(addr, port, policy);
228 switch (p) {
229 case ADDR_POLICY_PROBABLY_ACCEPTED:
230 case ADDR_POLICY_ACCEPTED:
231 return 1;
232 case ADDR_POLICY_PROBABLY_REJECTED:
233 case ADDR_POLICY_REJECTED:
234 return 0;
235 default:
236 log_warn(LD_BUG, "Unexpected result: %d", (int)p);
237 return 0;
241 /* DOCDOC XXXX021 deprecate? */
242 static int
243 addr_policy_permits_address(uint32_t addr, uint16_t port,
244 smartlist_t *policy)
246 tor_addr_t a;
247 tor_addr_from_ipv4h(&a, addr);
248 return addr_policy_permits_tor_addr(&a, port, policy);
251 /** Return true iff we think our firewall will let us make an OR connection to
252 * addr:port. */
254 fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
256 return addr_policy_permits_tor_addr(addr, port,
257 reachable_or_addr_policy);
260 /** DOCDOC */
262 fascist_firewall_allows_or(routerinfo_t *ri)
264 /* XXXX021 proposal 118 */
265 tor_addr_t addr;
266 tor_addr_from_ipv4h(&addr, ri->addr);
267 return fascist_firewall_allows_address_or(&addr, ri->or_port);
270 /** Return true iff we think our firewall will let us make a directory
271 * connection to addr:port. */
273 fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
275 return addr_policy_permits_tor_addr(addr, port,
276 reachable_dir_addr_policy);
279 /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
280 * based on <b>dir_policy</b>. Else return 0.
283 dir_policy_permits_address(const tor_addr_t *addr)
285 return addr_policy_permits_tor_addr(addr, 1, dir_policy);
288 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
289 * based on <b>socks_policy</b>. Else return 0.
292 socks_policy_permits_address(const tor_addr_t *addr)
294 return addr_policy_permits_tor_addr(addr, 1, socks_policy);
297 /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
298 * directory, based on <b>authdir_reject_policy</b>. Else return 0.
301 authdir_policy_permits_address(uint32_t addr, uint16_t port)
303 return addr_policy_permits_address(addr, port, authdir_reject_policy);
306 /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
307 * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
310 authdir_policy_valid_address(uint32_t addr, uint16_t port)
312 return addr_policy_permits_address(addr, port, authdir_invalid_policy);
315 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad dir,
316 * based on <b>authdir_baddir_policy</b>. Else return 0.
319 authdir_policy_baddir_address(uint32_t addr, uint16_t port)
321 return ! addr_policy_permits_address(addr, port, authdir_baddir_policy);
324 /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
325 * based on <b>authdir_badexit_policy</b>. Else return 0.
328 authdir_policy_badexit_address(uint32_t addr, uint16_t port)
330 return ! addr_policy_permits_address(addr, port, authdir_badexit_policy);
333 #define REJECT(arg) \
334 STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
336 /** Config helper: If there's any problem with the policy configuration
337 * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
338 * allocated description of the error. Else return 0. */
340 validate_addr_policies(or_options_t *options, char **msg)
342 /* XXXX Maybe merge this into parse_policies_from_options, to make sure
343 * that the two can't go out of sync. */
345 smartlist_t *addr_policy=NULL;
346 *msg = NULL;
348 if (policies_parse_exit_policy(options->ExitPolicy, &addr_policy,
349 options->ExitPolicyRejectPrivate, NULL))
350 REJECT("Error in ExitPolicy entry.");
352 /* The rest of these calls *append* to addr_policy. So don't actually
353 * use the results for anything other than checking if they parse! */
354 if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
355 REJECT("Error in DirPolicy entry.");
356 if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
357 REJECT("Error in SocksPolicy entry.");
358 if (parse_addr_policy(options->AuthDirReject, &addr_policy,
359 ADDR_POLICY_REJECT))
360 REJECT("Error in AuthDirReject entry.");
361 if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
362 ADDR_POLICY_REJECT))
363 REJECT("Error in AuthDirInvalid entry.");
364 if (parse_addr_policy(options->AuthDirBadDir, &addr_policy,
365 ADDR_POLICY_REJECT))
366 REJECT("Error in AuthDirBadDir entry.");
367 if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
368 ADDR_POLICY_REJECT))
369 REJECT("Error in AuthDirBadExit entry.");
371 if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
372 ADDR_POLICY_ACCEPT))
373 REJECT("Error in ReachableAddresses entry.");
374 if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
375 ADDR_POLICY_ACCEPT))
376 REJECT("Error in ReachableORAddresses entry.");
377 if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
378 ADDR_POLICY_ACCEPT))
379 REJECT("Error in ReachableDirAddresses entry.");
380 if (parse_addr_policy(options->AuthDirReject, &addr_policy,
381 ADDR_POLICY_REJECT))
382 REJECT("Error in AuthDirReject entry.");
383 if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
384 ADDR_POLICY_REJECT))
385 REJECT("Error in AuthDirInvalid entry.");
387 err:
388 addr_policy_list_free(addr_policy);
389 return *msg ? -1 : 0;
390 #undef REJECT
393 /** Parse <b>string</b> in the same way that the exit policy
394 * is parsed, and put the processed version in *<b>policy</b>.
395 * Ignore port specifiers.
397 static int
398 load_policy_from_option(config_line_t *config, smartlist_t **policy,
399 int assume_action)
401 int r;
402 addr_policy_list_free(*policy);
403 *policy = NULL;
404 r = parse_addr_policy(config, policy, assume_action);
405 if (r < 0) {
406 return -1;
408 if (*policy) {
409 SMARTLIST_FOREACH(*policy, addr_policy_t *, n, {
410 /* ports aren't used. */
411 n->prt_min = 1;
412 n->prt_max = 65535;
415 return 0;
418 /** Set all policies based on <b>options</b>, which should have been validated
419 * first by validate_addr_policies. */
421 policies_parse_from_options(or_options_t *options)
423 int ret = 0;
424 if (load_policy_from_option(options->SocksPolicy, &socks_policy, -1) < 0)
425 ret = -1;
426 if (load_policy_from_option(options->DirPolicy, &dir_policy, -1) < 0)
427 ret = -1;
428 if (load_policy_from_option(options->AuthDirReject,
429 &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
430 ret = -1;
431 if (load_policy_from_option(options->AuthDirInvalid,
432 &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
433 ret = -1;
434 if (load_policy_from_option(options->AuthDirBadDir,
435 &authdir_baddir_policy, ADDR_POLICY_REJECT) < 0)
436 ret = -1;
437 if (load_policy_from_option(options->AuthDirBadExit,
438 &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
439 ret = -1;
440 if (parse_reachable_addresses() < 0)
441 ret = -1;
442 return ret;
445 /** Compare two provided address policy items, and return -1, 0, or 1
446 * if the first is less than, equal to, or greater than the second. */
447 static int
448 cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
450 int r;
451 if ((r=((int)a->policy_type - (int)b->policy_type)))
452 return r;
453 if ((r=((int)a->is_private - (int)b->is_private)))
454 return r;
455 if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
456 return r;
457 if ((r=((int)a->maskbits - (int)b->maskbits)))
458 return r;
459 if ((r=((int)a->prt_min - (int)b->prt_min)))
460 return r;
461 if ((r=((int)a->prt_max - (int)b->prt_max)))
462 return r;
463 return 0;
466 /** Like cmp_single_addr_policy() above, but looks at the
467 * whole set of policies in each case. */
469 cmp_addr_policies(smartlist_t *a, smartlist_t *b)
471 int r, i;
472 int len_a = a ? smartlist_len(a) : 0;
473 int len_b = b ? smartlist_len(b) : 0;
475 for (i = 0; i < len_a && i < len_b; ++i) {
476 if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
477 return r;
479 if (i == len_a && i == len_b)
480 return 0;
481 if (i < len_a)
482 return -1;
483 else
484 return 1;
487 /** Node in hashtable used to store address policy entries. */
488 typedef struct policy_map_ent_t {
489 HT_ENTRY(policy_map_ent_t) node;
490 addr_policy_t *policy;
491 } policy_map_ent_t;
493 static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
495 /** Return true iff a and b are equal. */
496 static INLINE int
497 policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
499 return cmp_single_addr_policy(a->policy, b->policy) == 0;
502 /** Return a hashcode for <b>ent</b> */
503 static unsigned int
504 policy_hash(policy_map_ent_t *ent)
506 addr_policy_t *a = ent->policy;
507 unsigned int r;
508 if (a->is_private)
509 r = 0x1234abcd;
510 else
511 r = tor_addr_hash(&a->addr);
512 r += a->prt_min << 8;
513 r += a->prt_max << 16;
514 r += a->maskbits;
515 if (a->policy_type == ADDR_POLICY_REJECT)
516 r ^= 0xffffffff;
518 return r;
521 HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
522 policy_eq)
523 HT_GENERATE(policy_map, policy_map_ent_t, node, policy_hash,
524 policy_eq, 0.6, malloc, realloc, free)
526 /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
527 * "canonical" copy of that addr_policy_t; the canonical copy is a single
528 * reference-counted object. */
529 addr_policy_t *
530 addr_policy_get_canonical_entry(addr_policy_t *e)
532 policy_map_ent_t search, *found;
533 if (e->is_canonical)
534 return e;
536 search.policy = e;
537 found = HT_FIND(policy_map, &policy_root, &search);
538 if (!found) {
539 found = tor_malloc_zero(sizeof(policy_map_ent_t));
540 found->policy = tor_memdup(e, sizeof(addr_policy_t));
541 found->policy->is_canonical = 1;
542 found->policy->refcnt = 0;
543 HT_INSERT(policy_map, &policy_root, found);
546 tor_assert(!cmp_single_addr_policy(found->policy, e));
547 ++found->policy->refcnt;
548 return found->policy;
551 /** DOCDOC */
552 addr_policy_result_t
553 compare_addr_to_addr_policy(uint32_t addr, uint16_t port, smartlist_t *policy)
555 /*XXXX021 deprecate this function? */
556 tor_addr_t a;
557 tor_addr_from_ipv4h(&a, addr);
558 return compare_tor_addr_to_addr_policy(&a, port, policy);
561 /** Decide whether a given addr:port is definitely accepted,
562 * definitely rejected, probably accepted, or probably rejected by a
563 * given policy. If <b>addr</b> is 0, we don't know the IP of the
564 * target address. If <b>port</b> is 0, we don't know the port of the
565 * target address.
567 * For now, the algorithm is pretty simple: we look for definite and
568 * uncertain matches. The first definite match is what we guess; if
569 * it was preceded by no uncertain matches of the opposite policy,
570 * then the guess is definite; otherwise it is probable. (If we
571 * have a known addr and port, all matches are definite; if we have an
572 * unknown addr/port, any address/port ranges other than "all" are
573 * uncertain.)
575 * We could do better by assuming that some ranges never match typical
576 * addresses (127.0.0.1, and so on). But we'll try this for now.
578 addr_policy_result_t
579 compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
580 smartlist_t *policy)
582 int maybe_reject = 0;
583 int maybe_accept = 0;
584 int match = 0;
585 int maybe = 0;
586 int i, len;
587 int addr_is_unknown;
588 addr_is_unknown = tor_addr_is_null(addr);
590 len = policy ? smartlist_len(policy) : 0;
592 for (i = 0; i < len; ++i) {
593 addr_policy_t *tmpe = smartlist_get(policy, i);
594 maybe = 0;
595 if (addr_is_unknown) {
596 /* Address is unknown. */
597 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
598 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
599 /* The port definitely matches. */
600 if (tmpe->maskbits == 0) {
601 match = 1;
602 } else {
603 maybe = 1;
605 } else if (!port) {
606 /* The port maybe matches. */
607 maybe = 1;
609 } else {
610 /* Address is known */
611 if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
612 CMP_SEMANTIC)) {
613 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
614 /* Exact match for the policy */
615 match = 1;
616 } else if (!port) {
617 maybe = 1;
621 if (maybe) {
622 if (tmpe->policy_type == ADDR_POLICY_REJECT)
623 maybe_reject = 1;
624 else
625 maybe_accept = 1;
627 if (match) {
628 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
629 /* If we already hit a clause that might trigger a 'reject', than we
630 * can't be sure of this certain 'accept'.*/
631 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
632 ADDR_POLICY_ACCEPTED;
633 } else {
634 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
635 ADDR_POLICY_REJECTED;
640 /* accept all by default. */
641 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
644 /** Return true iff the address policy <b>a</b> covers every case that
645 * would be covered by <b>b</b>, so that a,b is redundant. */
646 static int
647 addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
649 /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
650 * to "accept *:80". */
651 if (a->maskbits > b->maskbits) {
652 /* a has more fixed bits than b; it can't possibly cover b. */
653 return 0;
655 if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_SEMANTIC)) {
656 /* There's a fixed bit in a that's set differently in b. */
657 return 0;
659 return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
662 /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
663 * that is, there exists an address/port that is covered by <b>a</b> that
664 * is also covered by <b>b</b>.
666 static int
667 addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
669 maskbits_t minbits;
670 /* All the bits we care about are those that are set in both
671 * netmasks. If they are equal in a and b's networkaddresses
672 * then the networks intersect. If there is a difference,
673 * then they do not. */
674 if (a->maskbits < b->maskbits)
675 minbits = a->maskbits;
676 else
677 minbits = b->maskbits;
678 if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_SEMANTIC))
679 return 0;
680 if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
681 return 0;
682 return 1;
685 /** Add the exit policy described by <b>more</b> to <b>policy</b>.
687 static void
688 append_exit_policy_string(smartlist_t **policy, const char *more)
690 config_line_t tmp;
692 tmp.key = NULL;
693 tmp.value = (char*) more;
694 tmp.next = NULL;
695 if (parse_addr_policy(&tmp, policy, -1)<0) {
696 log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
700 /** Detect and excise "dead code" from the policy *<b>dest</b>. */
701 static void
702 exit_policy_remove_redundancies(smartlist_t *dest)
704 addr_policy_t *ap, *tmp, *victim;
705 int i, j;
707 /* Step one: find a *:* entry and cut off everything after it. */
708 for (i = 0; i < smartlist_len(dest); ++i) {
709 ap = smartlist_get(dest, i);
710 if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
711 /* This is a catch-all line -- later lines are unreachable. */
712 while (i+1 < smartlist_len(dest)) {
713 victim = smartlist_get(dest, i+1);
714 smartlist_del(dest, i+1);
715 addr_policy_free(victim);
717 break;
721 /* Step two: for every entry, see if there's a redundant entry
722 * later on, and remove it. */
723 for (i = 0; i < smartlist_len(dest)-1; ++i) {
724 ap = smartlist_get(dest, i);
725 for (j = i+1; j < smartlist_len(dest); ++j) {
726 tmp = smartlist_get(dest, j);
727 tor_assert(j > i);
728 if (addr_policy_covers(ap, tmp)) {
729 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
730 policy_write_item(p1, sizeof(p1), tmp, 0);
731 policy_write_item(p2, sizeof(p2), ap, 0);
732 log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d). It is made "
733 "redundant by %s (%d).", p1, j, p2, i);
734 smartlist_del_keeporder(dest, j--);
735 addr_policy_free(tmp);
740 /* Step three: for every entry A, see if there's an entry B making this one
741 * redundant later on. This is the case if A and B are of the same type
742 * (accept/reject), A is a subset of B, and there is no other entry of
743 * different type in between those two that intersects with A.
745 * Anybody want to doublecheck the logic here? XXX
747 for (i = 0; i < smartlist_len(dest)-1; ++i) {
748 ap = smartlist_get(dest, i);
749 for (j = i+1; j < smartlist_len(dest); ++j) {
750 // tor_assert(j > i); // j starts out at i+1; j only increases; i only
751 // // decreases.
752 tmp = smartlist_get(dest, j);
753 if (ap->policy_type != tmp->policy_type) {
754 if (addr_policy_intersects(ap, tmp))
755 break;
756 } else { /* policy_types are equal. */
757 if (addr_policy_covers(tmp, ap)) {
758 char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
759 policy_write_item(p1, sizeof(p1), ap, 0);
760 policy_write_item(p2, sizeof(p2), tmp, 0);
761 log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s. It is already "
762 "covered by %s.", p1, p2);
763 smartlist_del_keeporder(dest, i--);
764 addr_policy_free(ap);
765 break;
772 #define DEFAULT_EXIT_POLICY \
773 "reject *:25,reject *:119,reject *:135-139,reject *:445," \
774 "reject *:465,reject *:563,reject *:587," \
775 "reject *:1214,reject *:4661-4666," \
776 "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
778 /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
779 * cfg doesn't end in an absolute accept or reject, add the default exit
780 * policy afterwards. If <b>rejectprivate</b> is true, prepend
781 * "reject private:*" to the policy. Return -1 if we can't parse cfg,
782 * else return 0.
785 policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
786 int rejectprivate, const char *local_address)
788 if (rejectprivate) {
789 append_exit_policy_string(dest, "reject private:*");
790 if (local_address) {
791 char buf[POLICY_BUF_LEN];
792 tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
793 append_exit_policy_string(dest, buf);
796 if (parse_addr_policy(cfg, dest, -1))
797 return -1;
798 append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
800 exit_policy_remove_redundancies(*dest);
802 return 0;
805 /** Replace the exit policy of <b>r</b> with reject *:*. */
806 void
807 policies_set_router_exitpolicy_to_reject_all(routerinfo_t *r)
809 addr_policy_t *item;
810 addr_policy_list_free(r->exit_policy);
811 r->exit_policy = smartlist_create();
812 item = router_parse_addr_policy_item_from_string("reject *:*", -1);
813 smartlist_add(r->exit_policy, item);
816 /** Return true iff <b>ri</b> is "useful as an exit node", meaning
817 * it allows exit to at least one /8 address space for at least
818 * two of ports 80, 443, and 6667. */
820 exit_policy_is_general_exit(smartlist_t *policy)
822 static const int ports[] = { 80, 443, 6667 };
823 int n_allowed = 0;
824 int i;
825 if (!policy) /*XXXX021 disallow NULL policies */
826 return 0;
828 for (i = 0; i < 3; ++i) {
829 SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
830 if (p->prt_min > ports[i] || p->prt_max < ports[i])
831 continue; /* Doesn't cover our port. */
832 if (p->maskbits > 8)
833 continue; /* Narrower than a /8. */
834 if (tor_addr_is_loopback(&p->addr))
835 continue; /* 127.x or ::1. */
836 /* We have a match that is at least a /8. */
837 if (p->policy_type == ADDR_POLICY_ACCEPT) {
838 ++n_allowed;
839 break; /* stop considering this port */
843 return n_allowed >= 2;
846 /** Return false if <b>policy</b> might permit access to some addr:port;
847 * otherwise if we are certain it rejects everything, return true. */
849 policy_is_reject_star(smartlist_t *policy)
851 if (!policy) /*XXXX021 disallow NULL policies */
852 return 1;
853 SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
854 if (p->policy_type == ADDR_POLICY_ACCEPT)
855 return 0;
856 else if (p->policy_type == ADDR_POLICY_REJECT &&
857 p->prt_min <= 1 && p->prt_max == 65535 &&
858 p->maskbits == 0)
859 return 1;
861 return 1;
864 /** Write a single address policy to the buf_len byte buffer at buf. Return
865 * the number of characters written, or -1 on failure. */
867 policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
868 int format_for_desc)
870 size_t written = 0;
871 char addrbuf[TOR_ADDR_BUF_LEN];
872 const char *addrpart;
873 int result;
874 const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
875 const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
877 tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
879 /* write accept/reject 1.2.3.4 */
880 if (policy->is_private)
881 addrpart = "private";
882 else if (policy->maskbits == 0)
883 addrpart = "*";
884 else
885 addrpart = addrbuf;
887 result = tor_snprintf(buf, buflen, "%s%s%s %s",
888 (is_ip6&&format_for_desc)?"opt ":"",
889 is_accept ? "accept" : "reject",
890 (is_ip6&&format_for_desc)?"6":"",
891 addrpart);
892 if (result < 0)
893 return -1;
894 written += strlen(buf);
895 /* If the maskbits is 32 we don't need to give it. If the mask is 0,
896 * we already wrote "*". */
897 if (policy->maskbits < 32 && policy->maskbits > 0) {
898 if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
899 return -1;
900 written += strlen(buf+written);
902 if (policy->prt_min <= 1 && policy->prt_max == 65535) {
903 /* There is no port set; write ":*" */
904 if (written+4 > buflen)
905 return -1;
906 strlcat(buf+written, ":*", buflen-written);
907 written += 2;
908 } else if (policy->prt_min == policy->prt_max) {
909 /* There is only one port; write ":80". */
910 result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
911 if (result<0)
912 return -1;
913 written += result;
914 } else {
915 /* There is a range of ports; write ":79-80". */
916 result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
917 policy->prt_min, policy->prt_max);
918 if (result<0)
919 return -1;
920 written += result;
922 if (written < buflen)
923 buf[written] = '\0';
924 else
925 return -1;
927 return (int)written;
930 /** Create a new exit policy summary, initially only with a single
931 * port 1-64k item */
932 /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
933 * RB-tree if that turns out to matter. */
934 smartlist_t *
935 policy_summary_create(void)
937 smartlist_t *summary;
938 policy_summary_item_t* item;
940 item = tor_malloc_zero(sizeof(policy_summary_item_t));
941 item->prt_min = 1;
942 item->prt_max = 65535;
943 item->reject_count = 0;
944 item->accepted = 0;
946 summary = smartlist_create();
947 smartlist_add(summary, item);
949 return summary;
952 /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
953 * The current item is changed to end at new-starts - 1, the new item
954 * copies reject_count and accepted from the old item,
955 * starts at new_starts and ends at the port where the original item
956 * previously ended.
958 policy_summary_item_t*
959 policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts) {
960 policy_summary_item_t* new;
962 new = tor_malloc_zero(sizeof(policy_summary_item_t));
963 new->prt_min = new_starts;
964 new->prt_max = old->prt_max;
965 new->reject_count = old->reject_count;
966 new->accepted = old->accepted;
968 old->prt_max = new_starts-1;
970 tor_assert(old->prt_min < old->prt_max);
971 tor_assert(new->prt_min < new->prt_max);
972 return new;
975 /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
976 * my immortal soul, he can clean it up himself. */
977 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
979 #define REJECT_CUTOFF_COUNT (1<<25)
980 /* Split an exit policy summary so that prt_min and prt_max
981 * fall at exactly the start and end of an item respectively.
984 policy_summary_split(smartlist_t *summary,
985 uint16_t prt_min, uint16_t prt_max)
987 int start_at_index;
989 int i = 0;
990 /* XXXX Do a binary search if run time matters */
991 while (AT(i)->prt_max < prt_min)
992 i++;
993 if (AT(i)->prt_min != prt_min) {
994 policy_summary_item_t* new_item;
995 new_item = policy_summary_item_split(AT(i), prt_min);
996 smartlist_insert(summary, i+1, new_item);
997 i++;
999 start_at_index = i;
1001 while(AT(i)->prt_max < prt_max)
1002 i++;
1003 if (AT(i)->prt_max != prt_max) {
1004 policy_summary_item_t* new_item;
1005 new_item = policy_summary_item_split(AT(i), prt_max+1);
1006 smartlist_insert(summary, i+1, new_item);
1009 return start_at_index;
1012 /** Mark port ranges as accepted if they are below the reject_count */
1013 void
1014 policy_summary_accept(smartlist_t *summary,
1015 uint16_t prt_min, uint16_t prt_max)
1017 int i = policy_summary_split(summary, prt_min, prt_max);
1018 while (i < smartlist_len(summary) &&
1019 AT(i)->prt_max <= prt_max) {
1020 if (!AT(i)->accepted &&
1021 AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
1022 AT(i)->accepted = 1;
1023 i++;
1025 tor_assert(i < smartlist_len(summary) || prt_max==65535);
1028 /** Count the number of addresses in a network with prefixlen maskbits
1029 * against the given portrange. */
1030 void
1031 policy_summary_reject(smartlist_t *summary,
1032 maskbits_t maskbits,
1033 uint16_t prt_min, uint16_t prt_max)
1035 int i = policy_summary_split(summary, prt_min, prt_max);
1036 /* XXX: ipv4 specific */
1037 int count = (1 << (32-maskbits));
1038 while (i < smartlist_len(summary) &&
1039 AT(i)->prt_max <= prt_max) {
1040 AT(i)->reject_count += count;
1041 i++;
1043 tor_assert(i < smartlist_len(summary) || prt_max==65535);
1046 /** Add a single exit policy item to our summary:
1047 * If it is an accept ignore it unless it is for all IP addresses
1048 * ("*"), i.e. it's prefixlen/maskbits is 0, else call
1049 * policy_summary_accept().
1050 * If it's a reject ignore it if it is about one of the private
1051 * networks, else call policy_summary_reject().
1053 void
1054 policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
1056 if (p->policy_type == ADDR_POLICY_ACCEPT) {
1057 if (p->maskbits != 0) {
1058 policy_summary_accept(summary, p->prt_min, p->prt_max);
1060 } else if (p->policy_type == ADDR_POLICY_REJECT) {
1062 int is_private = 0;
1063 int i;
1064 for (i = 0; private_nets[i]; ++i) {
1065 tor_addr_t addr;
1066 maskbits_t maskbits;
1067 if (tor_addr_parse_mask_ports(private_nets[i], &addr,
1068 &maskbits, NULL, NULL)<0) {
1069 tor_assert(0);
1071 if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
1072 p->maskbits == maskbits) {
1073 is_private = 1;
1074 break;
1078 if (!is_private) {
1079 policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
1081 } else
1082 tor_assert(0);
1085 /** Create a string representing a summary for an exit policy.
1086 * The summary will either be an "accept" plus a comma-seperated list of port
1087 * ranges or a "reject" plus portranges, depending on which is shorter.
1089 char *
1090 policy_summarize(smartlist_t *policy)
1092 smartlist_t *summary = policy_summary_create();
1093 smartlist_t *accepts, *rejects;
1094 int i, last, start_prt;
1095 size_t accepts_len, rejects_len, shorter_len, final_size;
1096 char *accepts_str, *rejects_str, *shorter_str, *result;
1097 const char *prefix;
1099 tor_assert(policy);
1101 /* Create the summary list */
1102 SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
1103 policy_summary_add_item(summary, p);
1106 /* Now create two lists of strings, one for accepted and one
1107 * for rejected ports. We take care to merge ranges so that
1108 * we avoid getting stuff like "1-4,5-9,10", instead we want
1109 * "1-10"
1111 i = 0;
1112 start_prt = 1;
1113 accepts = smartlist_create();
1114 rejects = smartlist_create();
1115 while (1) {
1116 last = i == smartlist_len(summary)-1;
1117 if (last ||
1118 AT(i)->accepted != AT(i+1)->accepted) {
1119 char buf[POLICY_BUF_LEN];
1121 if (start_prt == AT(i)->prt_max)
1122 tor_snprintf(buf, sizeof(buf), "%d", start_prt);
1123 else
1124 tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
1126 if (AT(i)->accepted)
1127 smartlist_add(accepts, tor_strdup(buf));
1128 else
1129 smartlist_add(rejects, tor_strdup(buf));
1131 if (last)
1132 break;
1134 start_prt = AT(i+1)->prt_min;
1136 i++;
1139 /* Figure out which of the two stringlists will be shorter and use
1140 * that to build the result
1142 accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
1143 rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
1145 if (rejects_len < accepts_len) {
1146 shorter_str = rejects_str;
1147 shorter_len = rejects_len;
1148 prefix = "reject";
1149 } else {
1150 shorter_str = accepts_str;
1151 shorter_len = accepts_len;
1152 prefix = "accept";
1155 final_size = strlen(prefix)+1+shorter_len+1;
1156 result = malloc(final_size);
1157 tor_snprintf(result, final_size, "%s %s", prefix, shorter_str);
1159 /* cleanup */
1160 SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
1161 smartlist_clear(summary);
1163 tor_free(accepts_str);
1164 SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
1165 smartlist_clear(accepts);
1167 tor_free(rejects_str);
1168 SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
1169 smartlist_clear(rejects);
1171 return result;
1174 /** Implementation for GETINFO control command: knows the answer for questions
1175 * about "exit-policy/..." */
1177 getinfo_helper_policies(control_connection_t *conn,
1178 const char *question, char **answer)
1180 (void) conn;
1181 if (!strcmp(question, "exit-policy/default")) {
1182 *answer = tor_strdup(DEFAULT_EXIT_POLICY);
1184 return 0;
1187 /** Release all storage held by <b>p</b>. */
1188 void
1189 addr_policy_list_free(smartlist_t *lst)
1191 if (!lst) return;
1192 SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
1193 smartlist_free(lst);
1196 /** Release all storage held by <b>p</b>. */
1197 void
1198 addr_policy_free(addr_policy_t *p)
1200 if (p) {
1201 if (--p->refcnt <= 0) {
1202 if (p->is_canonical) {
1203 policy_map_ent_t search, *found;
1204 search.policy = p;
1205 found = HT_REMOVE(policy_map, &policy_root, &search);
1206 if (found) {
1207 tor_assert(p == found->policy);
1208 tor_free(found);
1211 tor_free(p);
1216 /** Release all storage held by policy variables. */
1217 void
1218 policies_free_all(void)
1220 addr_policy_list_free(reachable_or_addr_policy);
1221 reachable_or_addr_policy = NULL;
1222 addr_policy_list_free(reachable_dir_addr_policy);
1223 reachable_dir_addr_policy = NULL;
1224 addr_policy_list_free(socks_policy);
1225 socks_policy = NULL;
1226 addr_policy_list_free(dir_policy);
1227 dir_policy = NULL;
1228 addr_policy_list_free(authdir_reject_policy);
1229 authdir_reject_policy = NULL;
1230 addr_policy_list_free(authdir_invalid_policy);
1231 authdir_invalid_policy = NULL;
1232 addr_policy_list_free(authdir_baddir_policy);
1233 authdir_baddir_policy = NULL;
1234 addr_policy_list_free(authdir_badexit_policy);
1235 authdir_badexit_policy = NULL;
1237 if (!HT_EMPTY(&policy_root))
1238 log_warn(LD_MM, "Still had some address policies cached at shutdown.");
1239 HT_CLEAR(policy_map, &policy_root);
1242 /* vim:set et ts=2 shiftwidth=2: */