Line data Source code
1 : /* Copyright (c) 2001-2004, Roger Dingledine.
2 : * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 : * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 : /* See LICENSE for licensing information */
5 :
6 : /**
7 : * \file policies.c
8 : * \brief Code to parse and use address policies and exit policies.
9 : *
10 : * We have two key kinds of address policy: full and compressed. A full
11 : * policy is an array of accept/reject patterns, to be applied in order.
12 : * A short policy is simply a list of ports. This module handles both
13 : * kinds, including generic functions to apply them to addresses, and
14 : * also including code to manage the global policies that we apply to
15 : * incoming and outgoing connections.
16 : **/
17 :
18 : #define POLICIES_PRIVATE
19 :
20 : #include "core/or/or.h"
21 : #include "feature/client/bridges.h"
22 : #include "app/config/config.h"
23 : #include "core/or/policies.h"
24 : #include "feature/dirparse/policy_parse.h"
25 : #include "feature/nodelist/microdesc.h"
26 : #include "feature/nodelist/networkstatus.h"
27 : #include "feature/nodelist/nodelist.h"
28 : #include "feature/relay/router.h"
29 : #include "feature/relay/routermode.h"
30 : #include "lib/geoip/geoip.h"
31 : #include "ht.h"
32 : #include "lib/crypt_ops/crypto_rand.h"
33 : #include "lib/encoding/confline.h"
34 : #include "trunnel/ed25519_cert.h"
35 :
36 : #include "core/or/addr_policy_st.h"
37 : #include "feature/dirclient/dir_server_st.h"
38 : #include "feature/nodelist/microdesc_st.h"
39 : #include "feature/nodelist/node_st.h"
40 : #include "core/or/port_cfg_st.h"
41 : #include "feature/nodelist/routerinfo_st.h"
42 : #include "feature/nodelist/routerstatus_st.h"
43 :
44 : /** Maximum length of an exit policy summary. */
45 : #define MAX_EXITPOLICY_SUMMARY_LEN 1000
46 :
47 : /** Policy that addresses for incoming SOCKS connections must match. */
48 : static smartlist_t *socks_policy = NULL;
49 : /** Policy that addresses for incoming directory connections must match. */
50 : static smartlist_t *dir_policy = NULL;
51 : /** Policy for incoming MetricsPort connections that must match. */
52 : static smartlist_t *metrics_policy = NULL;
53 : /** Policy that addresses for incoming router descriptors must match in order
54 : * to be published by us. */
55 : static smartlist_t *authdir_reject_policy = NULL;
56 : /** Policy that addresses for incoming router descriptors must match in order
57 : * to be marked as valid in our networkstatus. */
58 : static smartlist_t *authdir_invalid_policy = NULL;
59 : /** Policy that addresses for incoming router descriptors must <b>not</b>
60 : * match in order to not be marked as BadExit. */
61 : static smartlist_t *authdir_badexit_policy = NULL;
62 :
63 : /** Parsed addr_policy_t describing which addresses we believe we can start
64 : * circuits at. */
65 : static smartlist_t *reachable_or_addr_policy = NULL;
66 : /** Parsed addr_policy_t describing which addresses we believe we can connect
67 : * to directories at. */
68 : static smartlist_t *reachable_dir_addr_policy = NULL;
69 :
70 : /** Element of an exit policy summary */
71 : typedef struct policy_summary_item_t {
72 : uint16_t prt_min; /**< Lowest port number to accept/reject. */
73 : uint16_t prt_max; /**< Highest port number to accept/reject. */
74 : uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
75 : this port range. */
76 : unsigned int accepted:1; /** Has this port already been accepted */
77 : } policy_summary_item_t;
78 :
79 : /** Private networks. This list is used in two places, once to expand the
80 : * "private" keyword when parsing our own exit policy, secondly to ignore
81 : * just such networks when building exit policy summaries. It is important
82 : * that all authorities agree on that list when creating summaries, so don't
83 : * just change this without a proper migration plan and a proposal and stuff.
84 : */
85 : static const char *private_nets[] = {
86 : "0.0.0.0/8", "169.254.0.0/16",
87 : "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
88 : "[::]/8",
89 : "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
90 : NULL
91 : };
92 :
93 : static int policies_parse_exit_policy_internal(
94 : config_line_t *cfg,
95 : smartlist_t **dest,
96 : int ipv6_exit,
97 : int rejectprivate,
98 : const smartlist_t *configured_addresses,
99 : int reject_interface_addresses,
100 : int reject_configured_port_addresses,
101 : int add_default_policy,
102 : int add_reduced_policy);
103 :
104 : /** Replace all "private" entries in *<b>policy</b> with their expanded
105 : * equivalents. */
106 : void
107 2511 : policy_expand_private(smartlist_t **policy)
108 : {
109 2511 : uint16_t port_min, port_max;
110 :
111 2511 : int i;
112 2511 : smartlist_t *tmp;
113 :
114 2511 : if (!*policy) /*XXXX disallow NULL policies? */
115 0 : return;
116 :
117 2511 : tmp = smartlist_new();
118 :
119 57269 : SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
120 54758 : if (! p->is_private) {
121 54512 : smartlist_add(tmp, p);
122 54512 : continue;
123 : }
124 3198 : for (i = 0; private_nets[i]; ++i) {
125 2952 : addr_policy_t newpolicy;
126 2952 : memcpy(&newpolicy, p, sizeof(addr_policy_t));
127 2952 : newpolicy.is_private = 0;
128 2952 : newpolicy.is_canonical = 0;
129 2952 : if (tor_addr_parse_mask_ports(private_nets[i], 0,
130 : &newpolicy.addr,
131 : &newpolicy.maskbits, &port_min, &port_max)<0) {
132 0 : tor_assert_unreached();
133 : }
134 2952 : smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
135 : }
136 246 : addr_policy_free(p);
137 54758 : } SMARTLIST_FOREACH_END(p);
138 :
139 2511 : smartlist_free(*policy);
140 2511 : *policy = tmp;
141 : }
142 :
143 : /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
144 : * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
145 : * specific and one IPv6-specific. */
146 : void
147 2690 : policy_expand_unspec(smartlist_t **policy)
148 : {
149 2690 : smartlist_t *tmp;
150 2690 : if (!*policy)
151 : return;
152 :
153 2690 : tmp = smartlist_new();
154 60010 : SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
155 57320 : sa_family_t family = tor_addr_family(&p->addr);
156 57320 : if (family == AF_INET6 || family == AF_INET || p->is_private) {
157 5800 : smartlist_add(tmp, p);
158 51520 : } else if (family == AF_UNSPEC) {
159 51520 : addr_policy_t newpolicy_ipv4;
160 51520 : addr_policy_t newpolicy_ipv6;
161 51520 : memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
162 51520 : memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
163 51520 : newpolicy_ipv4.is_canonical = 0;
164 51520 : newpolicy_ipv6.is_canonical = 0;
165 51520 : if (p->maskbits != 0) {
166 0 : log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
167 0 : newpolicy_ipv4.maskbits = 0;
168 0 : newpolicy_ipv6.maskbits = 0;
169 : }
170 51520 : tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
171 51520 : tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
172 : (const uint8_t *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
173 51520 : smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
174 51520 : smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
175 51520 : addr_policy_free(p);
176 : } else {
177 0 : log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
178 0 : smartlist_add(tmp, p);
179 : }
180 57320 : } SMARTLIST_FOREACH_END(p);
181 :
182 2690 : smartlist_free(*policy);
183 2690 : *policy = tmp;
184 : }
185 :
186 : /**
187 : * Given a linked list of config lines containing "accept[6]" and "reject[6]"
188 : * tokens, parse them and append the result to <b>dest</b>. Return -1
189 : * if any tokens are malformed (and don't append any), else return 0.
190 : *
191 : * If <b>assume_action</b> is nonnegative, then insert its action
192 : * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
193 : * action.
194 : */
195 : static int
196 6096 : parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
197 : int assume_action)
198 : {
199 6096 : smartlist_t *result;
200 6096 : smartlist_t *entries;
201 6096 : addr_policy_t *item;
202 6096 : int malformed_list;
203 6096 : int r = 0;
204 :
205 6096 : if (!cfg)
206 : return 0;
207 :
208 2439 : result = smartlist_new();
209 2439 : entries = smartlist_new();
210 7319 : for (; cfg; cfg = cfg->next) {
211 2441 : smartlist_split_string(entries, cfg->value, ",",
212 : SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
213 56915 : SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
214 54474 : log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
215 54474 : malformed_list = 0;
216 54474 : item = router_parse_addr_policy_item_from_string(ent, assume_action,
217 : &malformed_list);
218 54474 : if (item) {
219 54473 : smartlist_add(result, item);
220 1 : } else if (malformed_list) {
221 : /* the error is so severe the entire list should be discarded */
222 1 : log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
223 : "list.", ent);
224 1 : r = -1;
225 : } else {
226 : /* the error is minor: don't add the item, but keep processing the
227 : * rest of the policies in the list */
228 0 : log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
229 : "The remainder of the policy list will be used.",
230 : ent);
231 : }
232 54474 : } SMARTLIST_FOREACH_END(ent);
233 56915 : SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
234 2441 : smartlist_clear(entries);
235 : }
236 2439 : smartlist_free(entries);
237 2439 : if (r == -1) {
238 1 : addr_policy_list_free(result);
239 : } else {
240 2438 : policy_expand_private(&result);
241 2438 : policy_expand_unspec(&result);
242 :
243 2438 : if (*dest) {
244 1968 : smartlist_add_all(*dest, result);
245 1968 : smartlist_free(result);
246 : } else {
247 470 : *dest = result;
248 : }
249 : }
250 :
251 : return r;
252 : }
253 :
254 : /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
255 : * reachable_(or|dir)_addr_policy. The options should already have
256 : * been validated by validate_addr_policies.
257 : */
258 : static int
259 8 : parse_reachable_addresses(void)
260 : {
261 8 : const or_options_t *options = get_options();
262 8 : int ret = 0;
263 :
264 8 : if (options->ReachableDirAddresses &&
265 1 : options->ReachableORAddresses &&
266 1 : options->ReachableAddresses) {
267 0 : log_warn(LD_CONFIG,
268 : "Both ReachableDirAddresses and ReachableORAddresses are set. "
269 : "ReachableAddresses setting will be ignored.");
270 : }
271 8 : addr_policy_list_free(reachable_or_addr_policy);
272 8 : reachable_or_addr_policy = NULL;
273 8 : if (!options->ReachableORAddresses && options->ReachableAddresses)
274 0 : log_info(LD_CONFIG,
275 : "Using ReachableAddresses as ReachableORAddresses.");
276 8 : if (parse_addr_policy(options->ReachableORAddresses ?
277 : options->ReachableORAddresses :
278 : options->ReachableAddresses,
279 : &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
280 0 : log_warn(LD_CONFIG,
281 : "Error parsing Reachable%sAddresses entry; ignoring.",
282 : options->ReachableORAddresses ? "OR" : "");
283 0 : ret = -1;
284 : }
285 :
286 8 : addr_policy_list_free(reachable_dir_addr_policy);
287 8 : reachable_dir_addr_policy = NULL;
288 8 : if (!options->ReachableDirAddresses && options->ReachableAddresses)
289 0 : log_info(LD_CONFIG,
290 : "Using ReachableAddresses as ReachableDirAddresses");
291 8 : if (parse_addr_policy(options->ReachableDirAddresses ?
292 : options->ReachableDirAddresses :
293 : options->ReachableAddresses,
294 : &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
295 0 : if (options->ReachableDirAddresses)
296 0 : log_warn(LD_CONFIG,
297 : "Error parsing ReachableDirAddresses entry; ignoring.");
298 : ret = -1;
299 : }
300 :
301 : /* We ignore ReachableAddresses for relays */
302 8 : if (!server_mode(options)) {
303 4 : if (policy_is_reject_star(reachable_or_addr_policy, AF_UNSPEC, 0)
304 4 : || policy_is_reject_star(reachable_dir_addr_policy, AF_UNSPEC,0)) {
305 0 : log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
306 : "ReachableAddresses, ReachableORAddresses, or "
307 : "ReachableDirAddresses reject all addresses. Please accept "
308 : "some addresses in these options.");
309 4 : } else if (options->ClientUseIPv4 == 1
310 4 : && (policy_is_reject_star(reachable_or_addr_policy, AF_INET, 0)
311 4 : || policy_is_reject_star(reachable_dir_addr_policy, AF_INET, 0))) {
312 0 : log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
313 : "ReachableAddresses, ReachableORAddresses, or "
314 : "ReachableDirAddresses reject all IPv4 addresses. "
315 : "Tor will not connect using IPv4.");
316 4 : } else if (reachable_addr_use_ipv6(options)
317 0 : && (policy_is_reject_star(reachable_or_addr_policy, AF_INET6, 0)
318 0 : || policy_is_reject_star(reachable_dir_addr_policy, AF_INET6, 0))) {
319 0 : log_warn(LD_CONFIG, "You have configured tor to use or prefer IPv6 "
320 : "(or UseBridges 1), but "
321 : "ReachableAddresses, ReachableORAddresses, or "
322 : "ReachableDirAddresses reject all IPv6 addresses. "
323 : "Tor will not connect using IPv6.");
324 : }
325 : }
326 :
327 : /* Append a reject *:* to reachable_(or|dir)_addr_policy */
328 8 : if (!ret && (options->ReachableDirAddresses ||
329 7 : options->ReachableORAddresses ||
330 6 : options->ReachableAddresses)) {
331 2 : append_exit_policy_string(&reachable_or_addr_policy, "reject *:*");
332 2 : append_exit_policy_string(&reachable_dir_addr_policy, "reject *:*");
333 : }
334 :
335 8 : return ret;
336 : }
337 :
338 : /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
339 : * address:port combination. */
340 : static int
341 7323 : firewall_is_fascist_impl(void)
342 : {
343 7323 : const or_options_t *options = get_options();
344 : /* Assume every non-bridge relay has an IPv4 address.
345 : * Clients which use bridges may only know the IPv6 address of their
346 : * bridge, but they will connect regardless of the ClientUseIPv6 setting. */
347 7323 : return options->ClientUseIPv4 == 0;
348 : }
349 :
350 : /** Return true iff the firewall options, including ClientUseIPv4 0 and
351 : * ClientUseIPv6 0, might block any OR address:port combination.
352 : * Address preferences may still change which address is selected even if
353 : * this function returns false.
354 : */
355 : int
356 7323 : firewall_is_fascist_or(void)
357 : {
358 7323 : return (reachable_or_addr_policy != NULL || firewall_is_fascist_impl());
359 : }
360 :
361 : /** Return true iff the firewall options, including ClientUseIPv4 0 and
362 : * ClientUseIPv6 0, might block any Dir address:port combination.
363 : * Address preferences may still change which address is selected even if
364 : * this function returns false.
365 : */
366 : int
367 0 : firewall_is_fascist_dir(void)
368 : {
369 0 : return (reachable_dir_addr_policy != NULL || firewall_is_fascist_impl());
370 : }
371 :
372 : /** Return true iff <b>policy</b> (possibly NULL) will allow a
373 : * connection to <b>addr</b>:<b>port</b>.
374 : */
375 : static int
376 4782 : addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
377 : smartlist_t *policy)
378 : {
379 4782 : addr_policy_result_t p;
380 4782 : p = compare_tor_addr_to_addr_policy(addr, port, policy);
381 4782 : switch (p) {
382 : case ADDR_POLICY_PROBABLY_ACCEPTED:
383 : case ADDR_POLICY_ACCEPTED:
384 : return 1;
385 22 : case ADDR_POLICY_PROBABLY_REJECTED:
386 : case ADDR_POLICY_REJECTED:
387 22 : return 0;
388 0 : default:
389 0 : log_warn(LD_BUG, "Unexpected result: %d", (int)p);
390 0 : return 0;
391 : }
392 : }
393 :
394 : /** Return true iff we think our firewall will let us make a connection to
395 : * addr:port.
396 : *
397 : * If we are configured as a server, ignore any address family preference and
398 : * just use IPv4.
399 : * Otherwise:
400 : * - return false for all IPv4 addresses:
401 : * - if ClientUseIPv4 is 0, or
402 : * if pref_only and pref_ipv6 are both true;
403 : * - return false for all IPv6 addresses:
404 : * - if reachable_addr_use_ipv6() is 0, or
405 : * - if pref_only is true and pref_ipv6 is false.
406 : *
407 : * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
408 : STATIC int
409 5074 : reachable_addr_allows(const tor_addr_t *addr,
410 : uint16_t port,
411 : smartlist_t *firewall_policy,
412 : int pref_only, int pref_ipv6)
413 : {
414 5074 : const or_options_t *options = get_options();
415 5074 : const int client_mode = !server_mode(options);
416 :
417 5074 : if (!addr || tor_addr_is_null(addr) || !port) {
418 157 : return 0;
419 : }
420 :
421 : /* Clients stop using IPv4 if it's disabled. In most cases, clients also
422 : * stop using IPv4 if it's not preferred.
423 : * Servers must have IPv4 enabled and preferred. */
424 4917 : if (tor_addr_family(addr) == AF_INET && client_mode &&
425 4737 : (!options->ClientUseIPv4 || (pref_only && pref_ipv6))) {
426 : return 0;
427 : }
428 :
429 : /* Clients and Servers won't use IPv6 unless it's enabled (and in most
430 : * cases, IPv6 must also be preferred before it will be used). */
431 4847 : if (tor_addr_family(addr) == AF_INET6 &&
432 172 : (!reachable_addr_use_ipv6(options) || (pref_only && !pref_ipv6))) {
433 : return 0;
434 : }
435 :
436 4750 : return addr_policy_permits_tor_addr(addr, port,
437 : firewall_policy);
438 : }
439 :
440 : /** Is this client configured to use IPv6?
441 : * Returns true if the client might use IPv6 for some of its connections
442 : * (including dual-stack and IPv6-only clients), and false if it will never
443 : * use IPv6 for any connections.
444 : * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
445 : * port: it supports bridge client per-node IPv6 preferences.
446 : */
447 : int
448 11035 : reachable_addr_use_ipv6(const or_options_t *options)
449 : {
450 : /* Clients use IPv6 if it's set, or they use bridges, or they don't use
451 : * IPv4, or they prefer it.
452 : * ClientPreferIPv6DirPort is deprecated, but check it anyway. */
453 10780 : return (options->ClientUseIPv6 == 1 || options->ClientUseIPv4 == 0 ||
454 10759 : options->ClientPreferIPv6ORPort == 1 ||
455 21794 : options->ClientPreferIPv6DirPort == 1 || options->UseBridges == 1);
456 : }
457 :
458 : /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
459 : * ClientPreferIPv6DirPort?
460 : * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
461 : */
462 : static int
463 6168 : reachable_addr_prefer_ipv6_impl(const or_options_t *options)
464 : {
465 : /*
466 : Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
467 : If we're a server or IPv6 is disabled, use IPv4.
468 : If IPv4 is disabled, use IPv6.
469 : */
470 :
471 6168 : if (server_mode(options) || !reachable_addr_use_ipv6(options)) {
472 : return 0;
473 : }
474 :
475 93 : if (!options->ClientUseIPv4) {
476 20 : return 1;
477 : }
478 :
479 : return -1;
480 : }
481 :
482 : /** Do we prefer to connect to IPv6 ORPorts?
483 : * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
484 : * per-node IPv6 preferences.
485 : */
486 : int
487 6103 : reachable_addr_prefer_ipv6_orport(const or_options_t *options)
488 : {
489 6103 : int pref_ipv6 = reachable_addr_prefer_ipv6_impl(options);
490 :
491 6103 : if (pref_ipv6 >= 0) {
492 : return pref_ipv6;
493 : }
494 :
495 : /* We can use both IPv4 and IPv6 - which do we prefer? */
496 32 : if (options->ClientPreferIPv6ORPort == 1) {
497 12 : return 1;
498 : }
499 :
500 : return 0;
501 : }
502 :
503 : /** Do we prefer to connect to IPv6 DirPorts?
504 : *
505 : * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
506 : * preferences. There's no reason to use it instead of this function.)
507 : */
508 : int
509 65 : reachable_addr_prefer_ipv6_dirport(const or_options_t *options)
510 : {
511 65 : int pref_ipv6 = reachable_addr_prefer_ipv6_impl(options);
512 :
513 65 : if (pref_ipv6 >= 0) {
514 : return pref_ipv6;
515 : }
516 :
517 : /* We can use both IPv4 and IPv6 - which do we prefer? */
518 41 : if (options->ClientPreferIPv6DirPort == 1) {
519 12 : return 1;
520 : }
521 :
522 : return 0;
523 : }
524 :
525 : /** Return true iff we think our firewall will let us make a connection to
526 : * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
527 : * fw_connection.
528 : * If pref_only is true, return true if addr is in the client's preferred
529 : * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
530 : * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
531 : */
532 : int
533 5025 : reachable_addr_allows_addr(const tor_addr_t *addr, uint16_t port,
534 : firewall_connection_t fw_connection,
535 : int pref_only, int pref_ipv6)
536 : {
537 5025 : if (fw_connection == FIREWALL_OR_CONNECTION) {
538 4889 : return reachable_addr_allows(addr, port,
539 : reachable_or_addr_policy,
540 : pref_only, pref_ipv6);
541 136 : } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
542 136 : return reachable_addr_allows(addr, port,
543 : reachable_dir_addr_policy,
544 : pref_only, pref_ipv6);
545 : } else {
546 0 : log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
547 : fw_connection);
548 0 : return 0;
549 : }
550 : }
551 :
552 : /** Return true iff we think our firewall will let us make a connection to
553 : * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
554 : * fw_connection.
555 : * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
556 : */
557 : static int
558 336 : reachable_addr_allows_ap(const tor_addr_port_t *ap,
559 : firewall_connection_t fw_connection,
560 : int pref_only, int pref_ipv6)
561 : {
562 336 : tor_assert(ap);
563 336 : return reachable_addr_allows_addr(&ap->addr, ap->port,
564 : fw_connection, pref_only,
565 : pref_ipv6);
566 : }
567 :
568 : /** Return true iff we think our firewall will let us make a connection to
569 : * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
570 : * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
571 : * <b>fw_connection</b>.
572 : * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
573 : */
574 : static int
575 4614 : reachable_addr_allows_base(const tor_addr_t *ipv4_addr, uint16_t ipv4_orport,
576 : uint16_t ipv4_dirport,
577 : const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
578 : uint16_t ipv6_dirport,
579 : firewall_connection_t fw_connection,
580 : int pref_only, int pref_ipv6)
581 : {
582 4614 : if (reachable_addr_allows_addr(ipv4_addr,
583 : (fw_connection == FIREWALL_OR_CONNECTION
584 : ? ipv4_orport
585 : : ipv4_dirport),
586 : fw_connection,
587 : pref_only, pref_ipv6)) {
588 : return 1;
589 : }
590 :
591 48 : if (reachable_addr_allows_addr(ipv6_addr,
592 : (fw_connection == FIREWALL_OR_CONNECTION
593 : ? ipv6_orport
594 : : ipv6_dirport),
595 : fw_connection,
596 : pref_only, pref_ipv6)) {
597 0 : return 1;
598 : }
599 :
600 : return 0;
601 : }
602 :
603 : /** Like reachable_addr_allows_base(), but takes ri. */
604 : static int
605 14 : reachable_addr_allows_ri_impl(const routerinfo_t *ri,
606 : firewall_connection_t fw_connection,
607 : int pref_only, int pref_ipv6)
608 : {
609 14 : if (!ri) {
610 : return 0;
611 : }
612 :
613 : /* Assume IPv4 and IPv6 DirPorts are the same */
614 14 : return reachable_addr_allows_base(&ri->ipv4_addr, ri->ipv4_orport,
615 : ri->ipv4_dirport, &ri->ipv6_addr,
616 14 : ri->ipv6_orport, ri->ipv4_dirport,
617 : fw_connection, pref_only, pref_ipv6);
618 : }
619 :
620 : /** Like reachable_addr_allows_rs, but takes pref_ipv6. */
621 : static int
622 4600 : reachable_addr_allows_rs_impl(const routerstatus_t *rs,
623 : firewall_connection_t fw_connection,
624 : int pref_only, int pref_ipv6)
625 : {
626 4600 : if (!rs) {
627 : return 0;
628 : }
629 :
630 : /* Assume IPv4 and IPv6 DirPorts are the same */
631 4600 : return reachable_addr_allows_base(&rs->ipv4_addr, rs->ipv4_orport,
632 : rs->ipv4_dirport, &rs->ipv6_addr,
633 4600 : rs->ipv6_orport, rs->ipv4_dirport,
634 : fw_connection, pref_only, pref_ipv6);
635 : }
636 :
637 : /** Like reachable_addr_allows_base(), but takes rs.
638 : * When rs is a fake_status from a dir_server_t, it can have a reachable
639 : * address, even when the corresponding node does not.
640 : * nodes can be missing addresses when there's no consensus (IPv4 and IPv6),
641 : * or when there is a microdescriptor consensus, but no microdescriptors
642 : * (microdescriptors have IPv6, the microdesc consensus does not). */
643 : int
644 0 : reachable_addr_allows_rs(const routerstatus_t *rs,
645 : firewall_connection_t fw_connection, int pref_only)
646 : {
647 0 : if (!rs) {
648 : return 0;
649 : }
650 :
651 : /* We don't have access to the node-specific IPv6 preference, so use the
652 : * generic IPv6 preference instead. */
653 0 : const or_options_t *options = get_options();
654 0 : int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
655 0 : ? reachable_addr_prefer_ipv6_orport(options)
656 0 : : reachable_addr_prefer_ipv6_dirport(options));
657 :
658 0 : return reachable_addr_allows_rs_impl(rs, fw_connection, pref_only,
659 : pref_ipv6);
660 : }
661 :
662 : /** Return true iff we think our firewall will let us make a connection to
663 : * ipv6_addr:ipv6_orport based on ReachableORAddresses.
664 : * If <b>fw_connection</b> is FIREWALL_DIR_CONNECTION, returns 0.
665 : * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
666 : */
667 : static int
668 27 : reachable_addr_allows_md_impl(const microdesc_t *md,
669 : firewall_connection_t fw_connection,
670 : int pref_only, int pref_ipv6)
671 : {
672 27 : if (!md) {
673 : return 0;
674 : }
675 :
676 : /* Can't check dirport, it doesn't have one */
677 27 : if (fw_connection == FIREWALL_DIR_CONNECTION) {
678 : return 0;
679 : }
680 :
681 : /* Also can't check IPv4, doesn't have that either */
682 27 : return reachable_addr_allows_addr(&md->ipv6_addr, md->ipv6_orport,
683 : fw_connection, pref_only,
684 : pref_ipv6);
685 : }
686 :
687 : /** Like reachable_addr_allows_base(), but takes node, and looks up pref_ipv6
688 : * from node_ipv6_or/dir_preferred(). */
689 : int
690 4600 : reachable_addr_allows_node(const node_t *node,
691 : firewall_connection_t fw_connection,
692 : int pref_only)
693 : {
694 4600 : if (!node) {
695 : return 0;
696 : }
697 :
698 4600 : node_assert_ok(node);
699 :
700 9200 : const int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
701 4600 : ? node_ipv6_or_preferred(node)
702 4600 : : node_ipv6_dir_preferred(node));
703 :
704 : /* Sometimes, the rs is missing the IPv6 address info, and we need to go
705 : * all the way to the md */
706 4600 : if (node->ri && reachable_addr_allows_ri_impl(node->ri, fw_connection,
707 : pref_only, pref_ipv6)) {
708 : return 1;
709 4600 : } else if (node->rs && reachable_addr_allows_rs_impl(node->rs,
710 : fw_connection,
711 : pref_only,
712 : pref_ipv6)) {
713 : return 1;
714 34 : } else if (node->md && reachable_addr_allows_md_impl(node->md,
715 : fw_connection,
716 : pref_only,
717 : pref_ipv6)) {
718 : return 1;
719 : } else {
720 : /* If we know nothing, assume it's unreachable, we'll never get an address
721 : * to connect to. */
722 34 : return 0;
723 : }
724 : }
725 :
726 : /** Like reachable_addr_allows_rs(), but takes ds. */
727 : int
728 0 : reachable_addr_allows_dir_server(const dir_server_t *ds,
729 : firewall_connection_t fw_connection,
730 : int pref_only)
731 : {
732 0 : if (!ds) {
733 : return 0;
734 : }
735 :
736 : /* A dir_server_t always has a fake_status. As long as it has the same
737 : * addresses/ports in both fake_status and dir_server_t, this works fine.
738 : * (See #17867.)
739 : * reachable_addr_allows_rs only checks the addresses in fake_status. */
740 0 : return reachable_addr_allows_rs(&ds->fake_status, fw_connection,
741 : pref_only);
742 : }
743 :
744 : /** If a and b are both valid and allowed by fw_connection,
745 : * choose one based on want_a and return it.
746 : * Otherwise, return whichever is allowed.
747 : * Otherwise, return NULL.
748 : * pref_only and pref_ipv6 work as in reachable_addr_allows_addr().
749 : */
750 : static const tor_addr_port_t *
751 168 : reachable_addr_choose_impl(const tor_addr_port_t *a,
752 : const tor_addr_port_t *b,
753 : int want_a,
754 : firewall_connection_t fw_connection,
755 : int pref_only, int pref_ipv6)
756 : {
757 168 : const tor_addr_port_t *use_a = NULL;
758 168 : const tor_addr_port_t *use_b = NULL;
759 :
760 168 : if (reachable_addr_allows_ap(a, fw_connection, pref_only,
761 : pref_ipv6)) {
762 88 : use_a = a;
763 : }
764 :
765 168 : if (reachable_addr_allows_ap(b, fw_connection, pref_only,
766 : pref_ipv6)) {
767 59 : use_b = b;
768 : }
769 :
770 : /* If both are allowed */
771 168 : if (use_a && use_b) {
772 : /* Choose a if we want it */
773 0 : return (want_a ? use_a : use_b);
774 : } else {
775 : /* Choose a if we have it */
776 168 : return (use_a ? use_a : use_b);
777 : }
778 : }
779 :
780 : /** If a and b are both valid and preferred by fw_connection,
781 : * choose one based on want_a and return it.
782 : * Otherwise, return whichever is preferred.
783 : * If neither are preferred, and pref_only is false:
784 : * - If a and b are both allowed by fw_connection,
785 : * choose one based on want_a and return it.
786 : * - Otherwise, return whichever is preferred.
787 : * Otherwise, return NULL. */
788 : STATIC const tor_addr_port_t *
789 155 : reachable_addr_choose(const tor_addr_port_t *a,
790 : const tor_addr_port_t *b,
791 : int want_a,
792 : firewall_connection_t fw_connection,
793 : int pref_only, int pref_ipv6)
794 : {
795 155 : const tor_addr_port_t *pref = reachable_addr_choose_impl(
796 : a, b, want_a,
797 : fw_connection,
798 : 1, pref_ipv6);
799 155 : if (pref_only || pref) {
800 : /* If there is a preferred address, use it. If we can only use preferred
801 : * addresses, and neither address is preferred, pref will be NULL, and we
802 : * want to return NULL, so return it. */
803 : return pref;
804 : } else {
805 : /* If there's no preferred address, and we can return addresses that are
806 : * not preferred, use an address that's allowed */
807 13 : return reachable_addr_choose_impl(a, b, want_a, fw_connection,
808 : 0, pref_ipv6);
809 : }
810 : }
811 :
812 : /** Copy an address and port into <b>ap</b> that we think our firewall will
813 : * let us connect to. Uses ipv4_addr/ipv6_addr and
814 : * ipv4_orport/ipv6_orport/ReachableORAddresses or
815 : * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
816 : * <b>fw_connection</b>.
817 : * If pref_only, only choose preferred addresses. In either case, choose
818 : * a preferred address before an address that's not preferred.
819 : * If both addresses could be chosen (they are both preferred or both allowed)
820 : * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4. */
821 : static void
822 135 : reachable_addr_choose_base(const tor_addr_t *ipv4_addr,
823 : uint16_t ipv4_orport,
824 : uint16_t ipv4_dirport,
825 : const tor_addr_t *ipv6_addr,
826 : uint16_t ipv6_orport,
827 : uint16_t ipv6_dirport,
828 : firewall_connection_t fw_connection,
829 : int pref_only,
830 : int pref_ipv6,
831 : tor_addr_port_t* ap)
832 : {
833 135 : const tor_addr_port_t *result = NULL;
834 135 : const int want_ipv4 = !pref_ipv6;
835 :
836 135 : tor_assert(ipv6_addr);
837 135 : tor_assert(ap);
838 :
839 135 : tor_addr_make_null(&ap->addr, AF_UNSPEC);
840 135 : ap->port = 0;
841 :
842 135 : tor_addr_port_t ipv4_ap;
843 135 : tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
844 135 : ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
845 : ? ipv4_orport
846 : : ipv4_dirport);
847 :
848 135 : tor_addr_port_t ipv6_ap;
849 135 : tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
850 135 : ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
851 : ? ipv6_orport
852 : : ipv6_dirport);
853 :
854 135 : result = reachable_addr_choose(&ipv4_ap, &ipv6_ap,
855 : want_ipv4,
856 : fw_connection, pref_only,
857 : pref_ipv6);
858 :
859 135 : if (result) {
860 131 : tor_addr_copy(&ap->addr, &result->addr);
861 131 : ap->port = result->port;
862 : }
863 135 : }
864 :
865 : /** Like reachable_addr_choose_base(), but takes <b>rs</b>.
866 : * Consults the corresponding node, then falls back to rs if node is NULL.
867 : * This should only happen when there's no valid consensus, and rs doesn't
868 : * correspond to a bridge client's bridge.
869 : */
870 : void
871 52 : reachable_addr_choose_from_rs(const routerstatus_t *rs,
872 : firewall_connection_t fw_connection,
873 : int pref_only, tor_addr_port_t* ap)
874 : {
875 52 : tor_assert(ap);
876 :
877 52 : tor_addr_make_null(&ap->addr, AF_UNSPEC);
878 52 : ap->port = 0;
879 :
880 52 : if (!rs) {
881 : return;
882 : }
883 :
884 52 : const or_options_t *options = get_options();
885 52 : const node_t *node = node_get_by_id(rs->identity_digest);
886 :
887 52 : if (node) {
888 0 : reachable_addr_choose_from_node(node, fw_connection, pref_only, ap);
889 : } else {
890 : /* There's no node-specific IPv6 preference, so use the generic IPv6
891 : * preference instead. */
892 104 : int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
893 26 : ? reachable_addr_prefer_ipv6_orport(options)
894 52 : : reachable_addr_prefer_ipv6_dirport(options));
895 :
896 52 : reachable_addr_choose_base(&rs->ipv4_addr, rs->ipv4_orport,
897 : rs->ipv4_dirport, &rs->ipv6_addr,
898 52 : rs->ipv6_orport, rs->ipv4_dirport,
899 : fw_connection, pref_only, pref_ipv6,
900 : ap);
901 : }
902 : }
903 :
904 : /** Like reachable_addr_choose_base(), but takes in a smartlist
905 : * <b>lspecs</b> consisting of one or more link specifiers. We assume
906 : * fw_connection is FIREWALL_OR_CONNECTION as link specifiers cannot
907 : * contain DirPorts.
908 : */
909 : void
910 20 : reachable_addr_choose_from_ls(const smartlist_t *lspecs,
911 : int pref_only, tor_addr_port_t* ap)
912 : {
913 20 : int have_v4 = 0, have_v6 = 0;
914 20 : uint16_t port_v4 = 0, port_v6 = 0;
915 20 : tor_addr_t addr_v4, addr_v6;
916 :
917 20 : tor_assert(ap);
918 :
919 20 : if (lspecs == NULL) {
920 1 : log_warn(LD_BUG, "Unknown or missing link specifiers");
921 4 : return;
922 : }
923 19 : if (smartlist_len(lspecs) == 0) {
924 1 : log_warn(LD_PROTOCOL, "Link specifiers are empty");
925 1 : return;
926 : }
927 :
928 18 : tor_addr_make_null(&ap->addr, AF_UNSPEC);
929 18 : ap->port = 0;
930 :
931 18 : tor_addr_make_null(&addr_v4, AF_INET);
932 18 : tor_addr_make_null(&addr_v6, AF_INET6);
933 :
934 65 : SMARTLIST_FOREACH_BEGIN(lspecs, const link_specifier_t *, ls) {
935 47 : switch (link_specifier_get_ls_type(ls)) {
936 14 : case LS_IPV4:
937 : /* Skip if we already seen a v4. */
938 14 : if (have_v4) continue;
939 14 : tor_addr_from_ipv4h(&addr_v4,
940 : link_specifier_get_un_ipv4_addr(ls));
941 14 : port_v4 = link_specifier_get_un_ipv4_port(ls);
942 14 : have_v4 = 1;
943 14 : break;
944 15 : case LS_IPV6:
945 : /* Skip if we already seen a v6, or deliberately skip it if we're not a
946 : * direct connection. */
947 15 : if (have_v6) continue;
948 15 : tor_addr_from_ipv6_bytes(&addr_v6,
949 : link_specifier_getconstarray_un_ipv6_addr(ls));
950 15 : port_v6 = link_specifier_get_un_ipv6_port(ls);
951 15 : have_v6 = 1;
952 15 : break;
953 : default:
954 : /* Ignore unknown. */
955 : break;
956 : }
957 47 : } SMARTLIST_FOREACH_END(ls);
958 :
959 : /* If we don't have IPv4 or IPv6 in link specifiers, log a bug and return. */
960 18 : if (!have_v4 && !have_v6) {
961 1 : if (!have_v6) {
962 1 : log_warn(LD_PROTOCOL, "None of our link specifiers have IPv4 or IPv6");
963 : } else {
964 : log_warn(LD_PROTOCOL, "None of our link specifiers have IPv4");
965 : }
966 1 : return;
967 : }
968 :
969 : /* Here, don't check for DirPorts as link specifiers are only used for
970 : * ORPorts. */
971 17 : const or_options_t *options = get_options();
972 17 : int pref_ipv6 = reachable_addr_prefer_ipv6_orport(options);
973 : /* Assume that the DirPorts are zero as link specifiers only use ORPorts. */
974 17 : reachable_addr_choose_base(&addr_v4, port_v4, 0,
975 : &addr_v6, port_v6, 0,
976 : FIREWALL_OR_CONNECTION,
977 : pref_only, pref_ipv6,
978 : ap);
979 : }
980 :
981 : /** Like reachable_addr_choose_base(), but takes <b>node</b>, and
982 : * looks up the node's IPv6 preference rather than taking an argument
983 : * for pref_ipv6. */
984 : void
985 66 : reachable_addr_choose_from_node(const node_t *node,
986 : firewall_connection_t fw_connection,
987 : int pref_only, tor_addr_port_t *ap)
988 : {
989 66 : tor_assert(ap);
990 :
991 66 : tor_addr_make_null(&ap->addr, AF_UNSPEC);
992 66 : ap->port = 0;
993 :
994 66 : if (!node) {
995 0 : return;
996 : }
997 :
998 66 : node_assert_ok(node);
999 :
1000 132 : const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
1001 36 : ? node_ipv6_or_preferred(node)
1002 66 : : node_ipv6_dir_preferred(node));
1003 :
1004 66 : tor_addr_port_t ipv4_or_ap;
1005 66 : node_get_prim_orport(node, &ipv4_or_ap);
1006 66 : tor_addr_port_t ipv4_dir_ap;
1007 66 : node_get_prim_dirport(node, &ipv4_dir_ap);
1008 :
1009 66 : tor_addr_port_t ipv6_or_ap;
1010 66 : node_get_pref_ipv6_orport(node, &ipv6_or_ap);
1011 66 : tor_addr_port_t ipv6_dir_ap;
1012 66 : node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
1013 :
1014 : /* Assume the IPv6 OR and Dir addresses are the same. */
1015 66 : reachable_addr_choose_base(&ipv4_or_ap.addr, ipv4_or_ap.port,
1016 66 : ipv4_dir_ap.port, &ipv6_or_ap.addr,
1017 66 : ipv6_or_ap.port, ipv6_dir_ap.port,
1018 : fw_connection, pref_only,
1019 : pref_ipv6_node, ap);
1020 : }
1021 :
1022 : /** Like reachable_addr_choose_from_rs(), but takes <b>ds</b>. */
1023 : void
1024 0 : reachable_addr_choose_from_dir_server(const dir_server_t *ds,
1025 : firewall_connection_t fw_connection,
1026 : int pref_only,
1027 : tor_addr_port_t *ap)
1028 : {
1029 0 : tor_assert(ap);
1030 :
1031 0 : tor_addr_make_null(&ap->addr, AF_UNSPEC);
1032 0 : ap->port = 0;
1033 :
1034 0 : if (!ds) {
1035 : return;
1036 : }
1037 :
1038 : /* A dir_server_t always has a fake_status. As long as it has the same
1039 : * addresses/ports in both fake_status and dir_server_t, this works fine.
1040 : * (See #17867.)
1041 : * This function relies on reachable_addr_choose_from_rs looking up the
1042 : * node if it can, because that will get the latest info for the relay. */
1043 0 : reachable_addr_choose_from_rs(&ds->fake_status, fw_connection,
1044 : pref_only, ap);
1045 : }
1046 :
1047 : /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
1048 : * based on <b>dir_policy</b>. Else return 0.
1049 : */
1050 : int
1051 0 : dir_policy_permits_address(const tor_addr_t *addr)
1052 : {
1053 0 : return addr_policy_permits_tor_addr(addr, 1, dir_policy);
1054 : }
1055 :
1056 : /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1057 : * based on <b>socks_policy</b>. Else return 0.
1058 : */
1059 : int
1060 0 : socks_policy_permits_address(const tor_addr_t *addr)
1061 : {
1062 0 : return addr_policy_permits_tor_addr(addr, 1, socks_policy);
1063 : }
1064 :
1065 : /** Return 1 if <b>addr</b> is permitted to connect to our metrics port,
1066 : * based on <b>socks_policy</b>. Else return 0.
1067 : */
1068 : int
1069 8 : metrics_policy_permits_address(const tor_addr_t *addr)
1070 : {
1071 8 : return addr_policy_permits_tor_addr(addr, 1, metrics_policy);
1072 : }
1073 :
1074 : /** Return true iff the address <b>addr</b> is in a country listed in the
1075 : * case-insensitive list of country codes <b>cc_list</b>. */
1076 : static int
1077 24 : addr_is_in_cc_list(const tor_addr_t *addr, const smartlist_t *cc_list)
1078 : {
1079 24 : country_t country;
1080 24 : const char *name;
1081 :
1082 24 : if (!cc_list)
1083 : return 0;
1084 24 : country = geoip_get_country_by_addr(addr);
1085 24 : name = geoip_get_country_name(country);
1086 24 : return smartlist_contains_string_case(cc_list, name);
1087 : }
1088 :
1089 : /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
1090 : * directory, based on <b>authdir_reject_policy</b>. Else return 0.
1091 : */
1092 : int
1093 8 : authdir_policy_permits_address(const tor_addr_t *addr, uint16_t port)
1094 : {
1095 8 : if (!addr_policy_permits_tor_addr(addr, port, authdir_reject_policy))
1096 : return 0;
1097 8 : return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
1098 : }
1099 :
1100 : /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
1101 : * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
1102 : */
1103 : int
1104 8 : authdir_policy_valid_address(const tor_addr_t *addr, uint16_t port)
1105 : {
1106 8 : if (!addr_policy_permits_tor_addr(addr, port, authdir_invalid_policy))
1107 : return 0;
1108 8 : return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
1109 : }
1110 :
1111 : /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
1112 : * based on <b>authdir_badexit_policy</b>. Else return 0.
1113 : */
1114 : int
1115 8 : authdir_policy_badexit_address(const tor_addr_t *addr, uint16_t port)
1116 : {
1117 8 : if (!addr_policy_permits_tor_addr(addr, port, authdir_badexit_policy))
1118 : return 1;
1119 8 : return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
1120 : }
1121 :
1122 : #define REJECT(arg) \
1123 : STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
1124 :
1125 : /** Check <b>or_options</b> to determine whether or not we are using the
1126 : * default options for exit policy. Return true if so, false otherwise. */
1127 : static int
1128 536 : policy_using_default_exit_options(const or_options_t *or_options)
1129 : {
1130 532 : return (or_options->ExitPolicy == NULL && or_options->ExitRelay == -1 &&
1131 1033 : or_options->ReducedExitPolicy == 0 && or_options->IPv6Exit == 0);
1132 : }
1133 :
1134 : /** Config helper: If there's any problem with the policy configuration
1135 : * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
1136 : * allocated description of the error. Else return 0. */
1137 : int
1138 453 : validate_addr_policies(const or_options_t *options, char **msg)
1139 : {
1140 : /* XXXX Maybe merge this into parse_policies_from_options, to make sure
1141 : * that the two can't go out of sync. */
1142 :
1143 453 : smartlist_t *addr_policy=NULL;
1144 453 : *msg = NULL;
1145 :
1146 453 : if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
1147 1 : REJECT("Error in ExitPolicy entry.");
1148 : }
1149 :
1150 452 : static int warned_about_nonexit = 0;
1151 :
1152 452 : if (public_server_mode(options) && !warned_about_nonexit &&
1153 118 : policy_using_default_exit_options(options)) {
1154 83 : warned_about_nonexit = 1;
1155 83 : log_notice(LD_CONFIG, "By default, Tor does not run as an exit relay. "
1156 : "If you want to be an exit relay, "
1157 : "set ExitRelay to 1. To suppress this message in the future, "
1158 : "set ExitRelay to 0.");
1159 : }
1160 :
1161 : /* The rest of these calls *append* to addr_policy. So don't actually
1162 : * use the results for anything other than checking if they parse! */
1163 452 : if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
1164 0 : REJECT("Error in DirPolicy entry.");
1165 452 : if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
1166 0 : REJECT("Error in SocksPolicy entry.");
1167 452 : if (parse_addr_policy(options->AuthDirReject, &addr_policy,
1168 : ADDR_POLICY_REJECT))
1169 0 : REJECT("Error in AuthDirReject entry.");
1170 452 : if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
1171 : ADDR_POLICY_REJECT))
1172 0 : REJECT("Error in AuthDirInvalid entry.");
1173 452 : if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
1174 : ADDR_POLICY_REJECT))
1175 0 : REJECT("Error in AuthDirBadExit entry.");
1176 :
1177 452 : if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
1178 : ADDR_POLICY_ACCEPT))
1179 0 : REJECT("Error in ReachableAddresses entry.");
1180 452 : if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
1181 : ADDR_POLICY_ACCEPT))
1182 0 : REJECT("Error in ReachableORAddresses entry.");
1183 452 : if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
1184 : ADDR_POLICY_ACCEPT))
1185 0 : REJECT("Error in ReachableDirAddresses entry.");
1186 :
1187 452 : err:
1188 453 : addr_policy_list_free(addr_policy);
1189 453 : return *msg ? -1 : 0;
1190 : #undef REJECT
1191 : }
1192 :
1193 : /** Parse <b>string</b> in the same way that the exit policy
1194 : * is parsed, and put the processed version in *<b>policy</b>.
1195 : * Ignore port specifiers.
1196 : */
1197 : static int
1198 48 : load_policy_from_option(config_line_t *config, const char *option_name,
1199 : smartlist_t **policy,
1200 : int assume_action)
1201 : {
1202 48 : int r;
1203 48 : int killed_any_ports = 0;
1204 48 : addr_policy_list_free(*policy);
1205 48 : *policy = NULL;
1206 48 : r = parse_addr_policy(config, policy, assume_action);
1207 48 : if (r < 0) {
1208 : return -1;
1209 : }
1210 48 : if (*policy) {
1211 4 : SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
1212 : /* ports aren't used in these. */
1213 2 : if (n->prt_min > 1 || n->prt_max != 65535) {
1214 0 : addr_policy_t newp, *c;
1215 0 : memcpy(&newp, n, sizeof(newp));
1216 0 : newp.prt_min = 1;
1217 0 : newp.prt_max = 65535;
1218 0 : newp.is_canonical = 0;
1219 0 : c = addr_policy_get_canonical_entry(&newp);
1220 0 : SMARTLIST_REPLACE_CURRENT(*policy, n, c);
1221 0 : addr_policy_free(n);
1222 0 : killed_any_ports = 1;
1223 : }
1224 2 : } SMARTLIST_FOREACH_END(n);
1225 : }
1226 2 : if (killed_any_ports) {
1227 0 : log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
1228 : }
1229 : return 0;
1230 : }
1231 :
1232 : /** Helper: Parse the MetricsPortPolicy option into the metrics_policy and set
1233 : * the reject all by default.
1234 : *
1235 : * Return 0 on success else -1. */
1236 : static int
1237 8 : parse_metrics_port_policy(const or_options_t *options)
1238 : {
1239 8 : if (load_policy_from_option(options->MetricsPortPolicy, "MetricsPortPolicy",
1240 : &metrics_policy, -1) < 0) {
1241 : return -1;
1242 : }
1243 : /* It is a reject all by default. */
1244 8 : append_exit_policy_string(&metrics_policy, "reject *:*");
1245 8 : return 0;
1246 : }
1247 :
1248 : /** Set all policies based on <b>options</b>, which should have been validated
1249 : * first by validate_addr_policies. */
1250 : int
1251 8 : policies_parse_from_options(const or_options_t *options)
1252 : {
1253 8 : int ret = 0;
1254 8 : if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
1255 : &socks_policy, -1) < 0)
1256 0 : ret = -1;
1257 8 : if (load_policy_from_option(options->DirPolicy, "DirPolicy",
1258 : &dir_policy, -1) < 0)
1259 0 : ret = -1;
1260 8 : if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
1261 : &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
1262 0 : ret = -1;
1263 8 : if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
1264 : &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
1265 0 : ret = -1;
1266 8 : if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
1267 : &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
1268 0 : ret = -1;
1269 8 : if (parse_metrics_port_policy(options) < 0) {
1270 0 : ret = -1;
1271 : }
1272 8 : if (parse_reachable_addresses() < 0)
1273 0 : ret = -1;
1274 8 : return ret;
1275 : }
1276 :
1277 : /** Compare two provided address policy items, and renturn -1, 0, or 1
1278 : * if the first is less than, equal to, or greater than the second. */
1279 : static int
1280 380958 : single_addr_policy_eq(const addr_policy_t *a, const addr_policy_t *b)
1281 : {
1282 380958 : int r;
1283 : #define CMP_FIELD(field) do { \
1284 : if (a->field != b->field) { \
1285 : return 0; \
1286 : } \
1287 : } while (0)
1288 380958 : CMP_FIELD(policy_type);
1289 374565 : CMP_FIELD(is_private);
1290 : /* refcnt and is_canonical are irrelevant to equality,
1291 : * they are hash table implementation details */
1292 374563 : if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
1293 : return 0;
1294 343606 : CMP_FIELD(maskbits);
1295 343486 : CMP_FIELD(prt_min);
1296 321911 : CMP_FIELD(prt_max);
1297 : #undef CMP_FIELD
1298 : return 1;
1299 : }
1300 :
1301 : /** As single_addr_policy_eq, but compare every element of two policies.
1302 : */
1303 : int
1304 4 : addr_policies_eq(const smartlist_t *a, const smartlist_t *b)
1305 : {
1306 4 : int i;
1307 4 : int len_a = a ? smartlist_len(a) : 0;
1308 4 : int len_b = b ? smartlist_len(b) : 0;
1309 :
1310 4 : if (len_a != len_b)
1311 : return 0;
1312 :
1313 35 : for (i = 0; i < len_a; ++i) {
1314 33 : if (! single_addr_policy_eq(smartlist_get(a, i), smartlist_get(b, i)))
1315 : return 0;
1316 : }
1317 :
1318 : return 1;
1319 : }
1320 :
1321 : /** Node in hashtable used to store address policy entries. */
1322 : typedef struct policy_map_ent_t {
1323 : HT_ENTRY(policy_map_ent_t) node;
1324 : addr_policy_t *policy;
1325 : } policy_map_ent_t;
1326 :
1327 : /* DOCDOC policy_root */
1328 : static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
1329 :
1330 : /** Return true iff a and b are equal. */
1331 : static inline int
1332 219975 : policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
1333 : {
1334 219975 : return single_addr_policy_eq(a->policy, b->policy);
1335 : }
1336 :
1337 : /** Return a hashcode for <b>ent</b> */
1338 : static unsigned int
1339 459754 : policy_hash(const policy_map_ent_t *ent)
1340 : {
1341 459754 : const addr_policy_t *a = ent->policy;
1342 459754 : addr_policy_t aa;
1343 459754 : memset(&aa, 0, sizeof(aa));
1344 :
1345 459754 : aa.prt_min = a->prt_min;
1346 459754 : aa.prt_max = a->prt_max;
1347 459754 : aa.maskbits = a->maskbits;
1348 459754 : aa.policy_type = a->policy_type;
1349 459754 : aa.is_private = a->is_private;
1350 :
1351 459754 : if (a->is_private) {
1352 738 : aa.is_private = 1;
1353 : } else {
1354 459016 : tor_addr_copy_tight(&aa.addr, &a->addr);
1355 : }
1356 :
1357 459754 : return (unsigned) siphash24g(&aa, sizeof(aa));
1358 : }
1359 :
1360 829410 : HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
1361 : policy_eq);
1362 10902 : HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
1363 : policy_eq, 0.6, tor_reallocarray_, tor_free_);
1364 :
1365 : /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
1366 : * "canonical" copy of that addr_policy_t; the canonical copy is a single
1367 : * reference-counted object. */
1368 : addr_policy_t *
1369 160950 : addr_policy_get_canonical_entry(addr_policy_t *e)
1370 : {
1371 160950 : policy_map_ent_t search, *found;
1372 160950 : if (e->is_canonical)
1373 : return e;
1374 :
1375 160950 : search.policy = e;
1376 160950 : found = HT_FIND(policy_map, &policy_root, &search);
1377 160950 : if (!found) {
1378 149413 : found = tor_malloc_zero(sizeof(policy_map_ent_t));
1379 149413 : found->policy = tor_memdup(e, sizeof(addr_policy_t));
1380 149413 : found->policy->is_canonical = 1;
1381 149413 : found->policy->refcnt = 0;
1382 149413 : HT_INSERT(policy_map, &policy_root, found);
1383 : }
1384 :
1385 160950 : tor_assert(single_addr_policy_eq(found->policy, e));
1386 160950 : ++found->policy->refcnt;
1387 160950 : return found->policy;
1388 : }
1389 :
1390 : /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1391 : * addr and port are both known. */
1392 : static addr_policy_result_t
1393 2161 : compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
1394 : const smartlist_t *policy)
1395 : {
1396 : /* We know the address and port, and we know the policy, so we can just
1397 : * compute an exact match. */
1398 2642 : SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1399 614 : if (tmpe->addr.family == AF_UNSPEC) {
1400 0 : log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1401 : "matches other AF_UNSPEC addresses.");
1402 : }
1403 : /* Address is known */
1404 614 : if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1405 : CMP_EXACT)) {
1406 140 : if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
1407 : /* Exact match for the policy */
1408 133 : return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
1409 133 : ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
1410 : }
1411 : }
1412 481 : } SMARTLIST_FOREACH_END(tmpe);
1413 :
1414 : /* accept all by default. */
1415 : return ADDR_POLICY_ACCEPTED;
1416 : }
1417 :
1418 : /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1419 : * addr is known but port is not. */
1420 : static addr_policy_result_t
1421 29 : compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
1422 : const smartlist_t *policy)
1423 : {
1424 : /* We look to see if there's a definite match. If so, we return that
1425 : match's value, unless there's an intervening possible match that says
1426 : something different. */
1427 29 : int maybe_accept = 0, maybe_reject = 0;
1428 :
1429 29 : SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1430 8 : if (tmpe->addr.family == AF_UNSPEC) {
1431 0 : log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1432 : "matches other AF_UNSPEC addresses.");
1433 : }
1434 8 : if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
1435 : CMP_EXACT)) {
1436 8 : if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
1437 : /* Definitely matches, since it covers all ports. */
1438 8 : if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1439 : /* If we already hit a clause that might trigger a 'reject', than we
1440 : * can't be sure of this certain 'accept'.*/
1441 0 : return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1442 : ADDR_POLICY_ACCEPTED;
1443 : } else {
1444 8 : return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1445 : ADDR_POLICY_REJECTED;
1446 : }
1447 : } else {
1448 : /* Might match. */
1449 0 : if (tmpe->policy_type == ADDR_POLICY_REJECT)
1450 : maybe_reject = 1;
1451 : else
1452 0 : maybe_accept = 1;
1453 : }
1454 : }
1455 0 : } SMARTLIST_FOREACH_END(tmpe);
1456 :
1457 : /* accept all by default. */
1458 21 : return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1459 : }
1460 :
1461 : /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
1462 : * port is known but address is not. */
1463 : static addr_policy_result_t
1464 4 : compare_unknown_tor_addr_to_addr_policy(uint16_t port,
1465 : const smartlist_t *policy)
1466 : {
1467 : /* We look to see if there's a definite match. If so, we return that
1468 : match's value, unless there's an intervening possible match that says
1469 : something different. */
1470 4 : int maybe_accept = 0, maybe_reject = 0;
1471 :
1472 8 : SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
1473 4 : if (tmpe->addr.family == AF_UNSPEC) {
1474 0 : log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
1475 : "matches other AF_UNSPEC addresses.");
1476 : }
1477 4 : if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
1478 4 : if (tmpe->maskbits == 0) {
1479 : /* Definitely matches, since it covers all addresses. */
1480 0 : if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1481 : /* If we already hit a clause that might trigger a 'reject', than we
1482 : * can't be sure of this certain 'accept'.*/
1483 0 : return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
1484 : ADDR_POLICY_ACCEPTED;
1485 : } else {
1486 0 : return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
1487 : ADDR_POLICY_REJECTED;
1488 : }
1489 : } else {
1490 : /* Might match. */
1491 4 : if (tmpe->policy_type == ADDR_POLICY_REJECT)
1492 : maybe_reject = 1;
1493 : else
1494 0 : maybe_accept = 1;
1495 : }
1496 : }
1497 4 : } SMARTLIST_FOREACH_END(tmpe);
1498 :
1499 : /* accept all by default. */
1500 4 : return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1501 : }
1502 :
1503 : /** Decide whether a given addr:port is definitely accepted,
1504 : * definitely rejected, probably accepted, or probably rejected by a
1505 : * given policy. If <b>addr</b> is 0, we don't know the IP of the
1506 : * target address. If <b>port</b> is 0, we don't know the port of the
1507 : * target address. (At least one of <b>addr</b> and <b>port</b> must be
1508 : * provided. If you want to know whether a policy would definitely reject
1509 : * an unknown address:port, use policy_is_reject_star().)
1510 : *
1511 : * We could do better by assuming that some ranges never match typical
1512 : * addresses (127.0.0.1, and so on). But we'll try this for now.
1513 : */
1514 6929 : MOCK_IMPL(addr_policy_result_t,
1515 : compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
1516 : const smartlist_t *policy))
1517 : {
1518 6929 : if (!policy) {
1519 : /* no policy? accept all. */
1520 : return ADDR_POLICY_ACCEPTED;
1521 2195 : } else if (addr == NULL || tor_addr_is_null(addr)) {
1522 5 : if (port == 0) {
1523 1 : log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
1524 : addr ? tor_addr_family(addr) : -1);
1525 1 : return ADDR_POLICY_REJECTED;
1526 : }
1527 4 : return compare_unknown_tor_addr_to_addr_policy(port, policy);
1528 2190 : } else if (port == 0) {
1529 29 : return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
1530 : } else {
1531 2161 : return compare_known_tor_addr_to_addr_policy(addr, port, policy);
1532 : }
1533 : }
1534 :
1535 : /** Return true iff the address policy <b>a</b> covers every case that
1536 : * would be covered by <b>b</b>, so that a,b is redundant. */
1537 : static int
1538 78002572 : addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
1539 : {
1540 78002572 : if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
1541 : /* You can't cover a different family. */
1542 : return 0;
1543 : }
1544 : /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
1545 : * to "accept *:80". */
1546 43299046 : if (a->maskbits > b->maskbits) {
1547 : /* a has more fixed bits than b; it can't possibly cover b. */
1548 : return 0;
1549 : }
1550 43130804 : if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
1551 : /* There's a fixed bit in a that's set differently in b. */
1552 : return 0;
1553 : }
1554 43111560 : return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
1555 : }
1556 :
1557 : /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
1558 : * that is, there exists an address/port that is covered by <b>a</b> that
1559 : * is also covered by <b>b</b>.
1560 : */
1561 : static int
1562 83143 : addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
1563 : {
1564 83143 : maskbits_t minbits;
1565 : /* All the bits we care about are those that are set in both
1566 : * netmasks. If they are equal in a and b's networkaddresses
1567 : * then the networks intersect. If there is a difference,
1568 : * then they do not. */
1569 83143 : if (a->maskbits < b->maskbits)
1570 : minbits = a->maskbits;
1571 : else
1572 : minbits = b->maskbits;
1573 83143 : if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
1574 : return 0;
1575 57383 : if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
1576 0 : return 0;
1577 : return 1;
1578 : }
1579 :
1580 : /** Add the exit policy described by <b>more</b> to <b>policy</b>.
1581 : */
1582 : STATIC void
1583 1927 : append_exit_policy_string(smartlist_t **policy, const char *more)
1584 : {
1585 1927 : config_line_t tmp;
1586 :
1587 1927 : tmp.key = NULL;
1588 1927 : tmp.value = (char*) more;
1589 1927 : tmp.next = NULL;
1590 1927 : if (parse_addr_policy(&tmp, policy, -1)<0) {
1591 0 : log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
1592 : }
1593 1927 : }
1594 :
1595 : /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
1596 : void
1597 30 : addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
1598 : {
1599 30 : tor_assert(dest);
1600 30 : tor_assert(addr);
1601 :
1602 30 : addr_policy_t p, *add;
1603 30 : memset(&p, 0, sizeof(p));
1604 30 : p.policy_type = ADDR_POLICY_REJECT;
1605 30 : p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
1606 30 : tor_addr_copy(&p.addr, addr);
1607 30 : p.prt_min = 1;
1608 30 : p.prt_max = 65535;
1609 :
1610 30 : add = addr_policy_get_canonical_entry(&p);
1611 30 : if (!*dest)
1612 11 : *dest = smartlist_new();
1613 30 : smartlist_add(*dest, add);
1614 30 : log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
1615 : fmt_addr(addr));
1616 30 : }
1617 :
1618 : /* Is addr public for the purposes of rejection? */
1619 : static int
1620 35 : tor_addr_is_public_for_reject(const tor_addr_t *addr)
1621 : {
1622 70 : return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
1623 70 : && !tor_addr_is_multicast(addr));
1624 : }
1625 :
1626 : /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
1627 : * Filter the address, only adding an IPv4 reject rule if ipv4_rules
1628 : * is true, and similarly for ipv6_rules. Check each address returns true for
1629 : * tor_addr_is_public_for_reject before adding it.
1630 : */
1631 : static void
1632 35 : addr_policy_append_reject_addr_filter(smartlist_t **dest,
1633 : const tor_addr_t *addr,
1634 : int ipv4_rules,
1635 : int ipv6_rules)
1636 : {
1637 35 : tor_assert(dest);
1638 35 : tor_assert(addr);
1639 :
1640 : /* Only reject IP addresses which are public */
1641 35 : if (tor_addr_is_public_for_reject(addr)) {
1642 :
1643 : /* Reject IPv4 addresses and IPv6 addresses based on the filters */
1644 35 : int is_ipv4 = tor_addr_is_v4(addr);
1645 35 : if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
1646 30 : addr_policy_append_reject_addr(dest, addr);
1647 : }
1648 : }
1649 35 : }
1650 :
1651 : /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1652 : * list as needed. */
1653 : void
1654 0 : addr_policy_append_reject_addr_list(smartlist_t **dest,
1655 : const smartlist_t *addrs)
1656 : {
1657 0 : tor_assert(dest);
1658 0 : tor_assert(addrs);
1659 :
1660 0 : SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1661 0 : addr_policy_append_reject_addr(dest, addr);
1662 0 : } SMARTLIST_FOREACH_END(addr);
1663 0 : }
1664 :
1665 : /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
1666 : * list as needed. Filter using */
1667 : static void
1668 32 : addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
1669 : const smartlist_t *addrs,
1670 : int ipv4_rules,
1671 : int ipv6_rules)
1672 : {
1673 32 : tor_assert(dest);
1674 32 : tor_assert(addrs);
1675 :
1676 63 : SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
1677 31 : addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
1678 31 : } SMARTLIST_FOREACH_END(addr);
1679 32 : }
1680 :
1681 : /** Detect and excise "dead code" from the policy *<b>dest</b>. */
1682 : static void
1683 987 : exit_policy_remove_redundancies(smartlist_t *dest)
1684 : {
1685 987 : addr_policy_t *ap, *tmp;
1686 987 : int i, j;
1687 :
1688 : /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
1689 : */
1690 : {
1691 987 : int kill_v4=0, kill_v6=0;
1692 111165 : for (i = 0; i < smartlist_len(dest); ++i) {
1693 110178 : sa_family_t family;
1694 110178 : ap = smartlist_get(dest, i);
1695 110178 : family = tor_addr_family(&ap->addr);
1696 110178 : if ((family == AF_INET && kill_v4) ||
1697 91654 : (family == AF_INET6 && kill_v6)) {
1698 48727 : smartlist_del_keeporder(dest, i--);
1699 48727 : addr_policy_free(ap);
1700 48727 : continue;
1701 : }
1702 :
1703 61451 : if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
1704 : /* This is a catch-all line -- later lines are unreachable. */
1705 1138 : if (family == AF_INET) {
1706 : kill_v4 = 1;
1707 650 : } else if (family == AF_INET6) {
1708 650 : kill_v6 = 1;
1709 : }
1710 : }
1711 : }
1712 : }
1713 :
1714 : /* Step two: for every entry, see if there's a redundant entry
1715 : * later on, and remove it. */
1716 61407 : for (i = 0; i < smartlist_len(dest)-1; ++i) {
1717 60420 : ap = smartlist_get(dest, i);
1718 39152495 : for (j = i+1; j < smartlist_len(dest); ++j) {
1719 39092075 : tmp = smartlist_get(dest, j);
1720 39092075 : tor_assert(j > i);
1721 39092075 : if (addr_policy_covers(ap, tmp)) {
1722 207 : char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1723 207 : policy_write_item(p1, sizeof(p1), tmp, 0);
1724 207 : policy_write_item(p2, sizeof(p2), ap, 0);
1725 207 : log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
1726 : "redundant by %s (%d).", p1, j, p2, i);
1727 207 : smartlist_del_keeporder(dest, j--);
1728 207 : addr_policy_free(tmp);
1729 : }
1730 : }
1731 : }
1732 :
1733 : /* Step three: for every entry A, see if there's an entry B making this one
1734 : * redundant later on. This is the case if A and B are of the same type
1735 : * (accept/reject), A is a subset of B, and there is no other entry of
1736 : * different type in between those two that intersects with A.
1737 : *
1738 : * Anybody want to double-check the logic here? XXX
1739 : */
1740 61404 : for (i = 0; i < smartlist_len(dest)-1; ++i) {
1741 60417 : ap = smartlist_get(dest, i);
1742 38996259 : for (j = i+1; j < smartlist_len(dest); ++j) {
1743 : // tor_assert(j > i); // j starts out at i+1; j only increases; i only
1744 : // // decreases.
1745 38993640 : tmp = smartlist_get(dest, j);
1746 38993640 : if (ap->policy_type != tmp->policy_type) {
1747 83143 : if (addr_policy_intersects(ap, tmp))
1748 : break;
1749 : } else { /* policy_types are equal. */
1750 38910497 : if (addr_policy_covers(tmp, ap)) {
1751 415 : char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
1752 415 : policy_write_item(p1, sizeof(p1), ap, 0);
1753 415 : policy_write_item(p2, sizeof(p2), tmp, 0);
1754 415 : log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
1755 : "covered by %s.", p1, p2);
1756 415 : smartlist_del_keeporder(dest, i--);
1757 415 : addr_policy_free(ap);
1758 415 : break;
1759 : }
1760 : }
1761 : }
1762 : }
1763 987 : }
1764 :
1765 : /** Reject private helper for policies_parse_exit_policy_internal: rejects
1766 : * publicly routable addresses on this exit relay.
1767 : *
1768 : * Add reject entries to the linked list *<b>dest</b>:
1769 : * <ul>
1770 : * <li>if configured_addresses is non-NULL, add entries that reject each
1771 : * tor_addr_t in the list as a destination.
1772 : * <li>if reject_interface_addresses is true, add entries that reject each
1773 : * public IPv4 and IPv6 address of each interface on this machine.
1774 : * <li>if reject_configured_port_addresses is true, add entries that reject
1775 : * each IPv4 and IPv6 address configured for a port.
1776 : * </ul>
1777 : *
1778 : * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
1779 : * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
1780 : * false.)
1781 : *
1782 : * The list in <b>dest</b> is created as needed.
1783 : */
1784 : void
1785 508 : policies_parse_exit_policy_reject_private(
1786 : smartlist_t **dest,
1787 : int ipv6_exit,
1788 : const smartlist_t *configured_addresses,
1789 : int reject_interface_addresses,
1790 : int reject_configured_port_addresses)
1791 : {
1792 508 : tor_assert(dest);
1793 :
1794 : /* Reject configured addresses, if they are from public netblocks. */
1795 508 : if (configured_addresses) {
1796 16 : addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
1797 : 1, ipv6_exit);
1798 : }
1799 :
1800 : /* Reject configured port addresses, if they are from public netblocks. */
1801 508 : if (reject_configured_port_addresses) {
1802 7 : const smartlist_t *port_addrs = get_configured_ports();
1803 :
1804 11 : SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
1805 :
1806 : /* Only reject port IP addresses, not port unix sockets */
1807 4 : if (!port->is_unix_addr) {
1808 4 : addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
1809 : }
1810 4 : } SMARTLIST_FOREACH_END(port);
1811 : }
1812 :
1813 : /* Reject local addresses from public netblocks on any interface. */
1814 508 : if (reject_interface_addresses) {
1815 9 : smartlist_t *public_addresses = NULL;
1816 :
1817 : /* Reject public IPv4 addresses on any interface */
1818 9 : public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
1819 9 : addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
1820 9 : interface_address6_list_free(public_addresses);
1821 :
1822 : /* Don't look for IPv6 addresses if we're configured as IPv4-only */
1823 9 : if (ipv6_exit) {
1824 : /* Reject public IPv6 addresses on any interface */
1825 7 : public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
1826 7 : addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
1827 7 : interface_address6_list_free(public_addresses);
1828 : }
1829 : }
1830 :
1831 : /* If addresses were added multiple times, remove all but one of them. */
1832 508 : if (*dest) {
1833 499 : exit_policy_remove_redundancies(*dest);
1834 : }
1835 508 : }
1836 :
1837 : /**
1838 : * Iterate through <b>policy</b> looking for redundant entries. Log a
1839 : * warning message with the first redundant entry, if any is found.
1840 : */
1841 : static void
1842 488 : policies_log_first_redundant_entry(const smartlist_t *policy)
1843 : {
1844 488 : int found_final_effective_entry = 0;
1845 488 : int first_redundant_entry = 0;
1846 488 : tor_assert(policy);
1847 70878 : SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
1848 70390 : sa_family_t family;
1849 70390 : int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
1850 70390 : const int i = p_sl_idx;
1851 :
1852 : /* Look for accept/reject *[4|6|]:* entries */
1853 70390 : if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
1854 1417 : family = tor_addr_family(&p->addr);
1855 : /* accept/reject *:* may have already been expanded into
1856 : * accept/reject *4:*,accept/reject *6:*
1857 : * But handle both forms.
1858 : */
1859 1417 : if (family == AF_INET || family == AF_UNSPEC) {
1860 628 : found_ipv4_wildcard = 1;
1861 : }
1862 1417 : if (family == AF_INET6 || family == AF_UNSPEC) {
1863 789 : found_ipv6_wildcard = 1;
1864 : }
1865 : }
1866 :
1867 : /* We also find accept *4:*,reject *6:* ; and
1868 : * accept *4:*,<other policies>,accept *6:* ; and similar.
1869 : * That's ok, because they make any subsequent entries redundant. */
1870 70390 : if (found_ipv4_wildcard && found_ipv6_wildcard) {
1871 0 : found_final_effective_entry = 1;
1872 : /* if we're not on the final entry in the list */
1873 0 : if (i < smartlist_len(policy) - 1) {
1874 0 : first_redundant_entry = i + 1;
1875 : }
1876 : break;
1877 : }
1878 70390 : } SMARTLIST_FOREACH_END(p);
1879 :
1880 : /* Work out if there are redundant trailing entries in the policy list */
1881 488 : if (found_final_effective_entry && first_redundant_entry > 0) {
1882 0 : const addr_policy_t *p;
1883 : /* Longest possible policy is
1884 : * "accept6 ffff:ffff:..255/128:10000-65535",
1885 : * which contains a max-length IPv6 address, plus 24 characters. */
1886 0 : char line[TOR_ADDR_BUF_LEN + 32];
1887 :
1888 0 : tor_assert(first_redundant_entry < smartlist_len(policy));
1889 0 : p = smartlist_get(policy, first_redundant_entry);
1890 : /* since we've already parsed the policy into an addr_policy_t struct,
1891 : * we might not log exactly what the user typed in */
1892 0 : policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
1893 0 : log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
1894 : "redundant, as it follows accept/reject *:* rules for both "
1895 : "IPv4 and IPv6. They will be removed from the exit policy. (Use "
1896 : "accept/reject *:* as the last entry in any exit policy.)",
1897 : line);
1898 : }
1899 488 : }
1900 :
1901 : #define DEFAULT_EXIT_POLICY \
1902 : "reject *:25,reject *:119,reject *:135-139,reject *:445," \
1903 : "reject *:563,reject *:1214,reject *:4661-4666," \
1904 : "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
1905 :
1906 : #define REDUCED_EXIT_POLICY \
1907 : "accept *:20-23,accept *:43,accept *:53,accept *:79-81,accept *:88," \
1908 : "accept *:110,accept *:143,accept *:194,accept *:220,accept *:389," \
1909 : "accept *:443,accept *:464,accept *:465,accept *:531,accept *:543-544," \
1910 : "accept *:554,accept *:563,accept *:587,accept *:636,accept *:706," \
1911 : "accept *:749,accept *:873,accept *:902-904,accept *:981,accept *:989-995," \
1912 : "accept *:1194,accept *:1220,accept *:1293,accept *:1500,accept *:1533," \
1913 : "accept *:1677,accept *:1723,accept *:1755,accept *:1863," \
1914 : "accept *:2082-2083,accept *:2086-2087,accept *:2095-2096," \
1915 : "accept *:2102-2104,accept *:3128,accept *:3389,accept *:3690," \
1916 : "accept *:4321,accept *:4643,accept *:5050,accept *:5190," \
1917 : "accept *:5222-5223,accept *:5228,accept *:5900,accept *:6660-6669," \
1918 : "accept *:6679,accept *:6697,accept *:8000,accept *:8008,accept *:8074," \
1919 : "accept *:8080,accept *:8082,accept *:8087-8088,accept *:8232-8233," \
1920 : "accept *:8332-8333,accept *:8443,accept *:8888,accept *:9418," \
1921 : "accept *:9999,accept *:10000,accept *:11371,accept *:19294," \
1922 : "accept *:19638,accept *:50002,accept *:64738,reject *:*"
1923 :
1924 : /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
1925 : *
1926 : * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
1927 : *
1928 : * If <b>configured_addresses</b> contains addresses:
1929 : * - prepend entries that reject the addresses in this list. These may be the
1930 : * advertised relay addresses and/or the outbound bind addresses,
1931 : * depending on the ExitPolicyRejectPrivate and
1932 : * ExitPolicyRejectLocalInterfaces settings.
1933 : * If <b>rejectprivate</b> is true:
1934 : * - prepend "reject private:*" to the policy.
1935 : * If <b>reject_interface_addresses</b> is true:
1936 : * - prepend entries that reject publicly routable interface addresses on
1937 : * this exit relay by calling policies_parse_exit_policy_reject_private
1938 : * If <b>reject_configured_port_addresses</b> is true:
1939 : * - prepend entries that reject all configured port addresses
1940 : *
1941 : * If cfg doesn't end in an absolute accept or reject and if
1942 : * <b>add_default_policy</b> is true, add the default exit
1943 : * policy afterwards.
1944 : *
1945 : * Return -1 if we can't parse cfg, else return 0.
1946 : *
1947 : * This function is used to parse the exit policy from our torrc. For
1948 : * the functions used to parse the exit policy from a router descriptor,
1949 : * see router_add_exit_policy.
1950 : */
1951 : static int
1952 489 : policies_parse_exit_policy_internal(config_line_t *cfg,
1953 : smartlist_t **dest,
1954 : int ipv6_exit,
1955 : int rejectprivate,
1956 : const smartlist_t *configured_addresses,
1957 : int reject_interface_addresses,
1958 : int reject_configured_port_addresses,
1959 : int add_default_policy,
1960 : int add_reduced_policy)
1961 : {
1962 489 : if (!ipv6_exit) {
1963 162 : append_exit_policy_string(dest, "reject *6:*");
1964 : }
1965 489 : if (rejectprivate) {
1966 : /* Reject IPv4 and IPv6 reserved private netblocks */
1967 245 : append_exit_policy_string(dest, "reject private:*");
1968 : }
1969 :
1970 : /* Consider rejecting IPv4 and IPv6 advertised relay addresses, outbound bind
1971 : * addresses, publicly routable addresses, and configured port addresses
1972 : * on this exit relay */
1973 489 : policies_parse_exit_policy_reject_private(dest, ipv6_exit,
1974 : configured_addresses,
1975 : reject_interface_addresses,
1976 : reject_configured_port_addresses);
1977 :
1978 489 : if (parse_addr_policy(cfg, dest, -1))
1979 : return -1;
1980 :
1981 : /* Before we add the default policy and final rejects, check to see if
1982 : * there are any lines after accept *:* or reject *:*. These lines have no
1983 : * effect, and are most likely an error. */
1984 488 : policies_log_first_redundant_entry(*dest);
1985 :
1986 488 : if (add_reduced_policy) {
1987 240 : append_exit_policy_string(dest, REDUCED_EXIT_POLICY);
1988 248 : } else if (add_default_policy) {
1989 128 : append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
1990 : } else {
1991 120 : append_exit_policy_string(dest, "reject *4:*");
1992 120 : append_exit_policy_string(dest, "reject *6:*");
1993 : }
1994 488 : exit_policy_remove_redundancies(*dest);
1995 :
1996 488 : return 0;
1997 : }
1998 :
1999 : /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
2000 : *
2001 : * Prepend an entry that rejects all IPv6 destinations unless
2002 : * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
2003 : *
2004 : * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
2005 : * - prepend an entry that rejects all destinations in all netblocks
2006 : * reserved for private use.
2007 : * - prepend entries that reject the advertised relay addresses in
2008 : * configured_addresses
2009 : * If <b>EXIT_POLICY_REJECT_LOCAL_INTERFACES</b> bit is set in <b>options</b>:
2010 : * - prepend entries that reject publicly routable addresses on this exit
2011 : * relay by calling policies_parse_exit_policy_internal
2012 : * - prepend entries that reject the outbound bind addresses in
2013 : * configured_addresses
2014 : * - prepend entries that reject all configured port addresses
2015 : *
2016 : * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
2017 : * default exit policy entries to <b>result</b> smartlist.
2018 : */
2019 : int
2020 489 : policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
2021 : exit_policy_parser_cfg_t options,
2022 : const smartlist_t *configured_addresses)
2023 : {
2024 489 : int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
2025 489 : int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
2026 489 : int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
2027 489 : int reject_local_interfaces = (options &
2028 489 : EXIT_POLICY_REJECT_LOCAL_INTERFACES) ? 1 : 0;
2029 489 : int add_reduced = (options & EXIT_POLICY_ADD_REDUCED) ? 1 : 0;
2030 :
2031 489 : return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
2032 : reject_private,
2033 : configured_addresses,
2034 : reject_local_interfaces,
2035 : reject_local_interfaces,
2036 : add_default,
2037 : add_reduced);
2038 : }
2039 :
2040 : /** Helper function that adds a copy of addr to a smartlist as long as it is
2041 : * non-NULL and not tor_addr_is_null().
2042 : *
2043 : * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2044 : */
2045 : static void
2046 10 : policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
2047 : {
2048 10 : if (addr && !tor_addr_is_null(addr)) {
2049 8 : tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
2050 8 : tor_addr_copy(addr_copy, addr);
2051 8 : smartlist_add(addr_list, addr_copy);
2052 : }
2053 10 : }
2054 :
2055 : /** Helper function that adds copies of or_options->OutboundBindAddresses
2056 : * to a smartlist as tor_addr_t *, as long as or_options is non-NULL, and
2057 : * the addresses are not tor_addr_is_null(), by passing them to
2058 : * policies_add_addr_to_smartlist.
2059 : *
2060 : * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
2061 : */
2062 : static void
2063 5 : policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
2064 : const or_options_t *or_options)
2065 : {
2066 5 : if (or_options) {
2067 25 : for (int i=0;i<OUTBOUND_ADDR_MAX;i++) {
2068 60 : for (int j=0;j<2;j++) {
2069 40 : if (!tor_addr_is_null(&or_options->OutboundBindAddresses[i][j])) {
2070 4 : policies_copy_addr_to_smartlist(addr_list,
2071 : &or_options->OutboundBindAddresses[i][j]);
2072 : }
2073 : }
2074 : }
2075 : }
2076 5 : }
2077 :
2078 : /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
2079 : * smartlist.
2080 : * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
2081 : * rejects all IPv6 destinations.
2082 : *
2083 : * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
2084 : * - prepend an entry that rejects all destinations in all netblocks reserved
2085 : * for private use.
2086 : * - if ipv4_local_address is non-zero, treat it as a host-order IPv4 address,
2087 : * and add it to the list of configured addresses.
2088 : * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
2089 : * to the list of configured addresses.
2090 : * If <b>or_options->ExitPolicyRejectLocalInterfaces</b> is true:
2091 : * - if or_options->OutboundBindAddresses[][0] (=IPv4) is not the null
2092 : * tor_addr_t, add it to the list of configured addresses.
2093 : * - if or_options->OutboundBindAddresses[][1] (=IPv6) is not the null
2094 : * tor_addr_t, add it to the list of configured addresses.
2095 : *
2096 : * If <b>or_options->BridgeRelay</b> is false, append entries of default
2097 : * Tor exit policy into <b>result</b> smartlist.
2098 : *
2099 : * If or_options->ExitRelay is false, or is auto without specifying an exit
2100 : * policy, then make our exit policy into "reject *:*" regardless.
2101 : */
2102 : int
2103 453 : policies_parse_exit_policy_from_options(const or_options_t *or_options,
2104 : const tor_addr_t *ipv4_local_address,
2105 : const tor_addr_t *ipv6_local_address,
2106 : smartlist_t **result)
2107 : {
2108 453 : exit_policy_parser_cfg_t parser_cfg = 0;
2109 453 : smartlist_t *configured_addresses = NULL;
2110 453 : int rv = 0;
2111 :
2112 : /* Short-circuit for non-exit relays, or for relays where we didn't specify
2113 : * ExitPolicy or ReducedExitPolicy or IPv6Exit and ExitRelay is auto. */
2114 453 : if (or_options->ExitRelay == 0 ||
2115 418 : policy_using_default_exit_options(or_options)) {
2116 449 : append_exit_policy_string(result, "reject *4:*");
2117 449 : append_exit_policy_string(result, "reject *6:*");
2118 449 : return 0;
2119 : }
2120 :
2121 4 : configured_addresses = smartlist_new();
2122 :
2123 : /* Configure the parser */
2124 4 : if (or_options->IPv6Exit) {
2125 3 : parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
2126 : }
2127 :
2128 4 : if (or_options->ExitPolicyRejectPrivate) {
2129 1 : parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
2130 : }
2131 :
2132 4 : if (!or_options->BridgeRelay) {
2133 4 : if (or_options->ReducedExitPolicy)
2134 0 : parser_cfg |= EXIT_POLICY_ADD_REDUCED;
2135 : else
2136 4 : parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
2137 : }
2138 :
2139 4 : if (or_options->ExitPolicyRejectLocalInterfaces) {
2140 3 : parser_cfg |= EXIT_POLICY_REJECT_LOCAL_INTERFACES;
2141 : }
2142 :
2143 : /* Copy the configured addresses into the tor_addr_t* list */
2144 4 : if (or_options->ExitPolicyRejectPrivate) {
2145 1 : policies_copy_addr_to_smartlist(configured_addresses, ipv4_local_address);
2146 1 : policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
2147 : }
2148 :
2149 4 : if (or_options->ExitPolicyRejectLocalInterfaces) {
2150 3 : policies_copy_outbound_addresses_to_smartlist(configured_addresses,
2151 : or_options);
2152 : }
2153 :
2154 4 : rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
2155 : configured_addresses);
2156 :
2157 4 : SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
2158 4 : smartlist_free(configured_addresses);
2159 :
2160 4 : return rv;
2161 : }
2162 :
2163 : /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
2164 : * *<b>dest</b> as needed. */
2165 : void
2166 0 : policies_exit_policy_append_reject_star(smartlist_t **dest)
2167 : {
2168 0 : append_exit_policy_string(dest, "reject *4:*");
2169 0 : append_exit_policy_string(dest, "reject *6:*");
2170 0 : }
2171 :
2172 : /** Replace the exit policy of <b>node</b> with reject *:* */
2173 : void
2174 0 : policies_set_node_exitpolicy_to_reject_all(node_t *node)
2175 : {
2176 0 : node->rejects_all = 1;
2177 0 : }
2178 :
2179 : /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
2180 : * allows exiting to <b>port</b>. Otherwise, return 0. */
2181 : static int
2182 14 : exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
2183 : {
2184 14 : uint32_t mask, ip, i;
2185 : /* Is this /8 rejected (1), or undecided (0)? */
2186 14 : char subnet_status[256];
2187 :
2188 14 : memset(subnet_status, 0, sizeof(subnet_status));
2189 191 : SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2190 183 : if (tor_addr_family(&p->addr) != AF_INET)
2191 71 : continue; /* IPv4 only for now */
2192 112 : if (p->prt_min > port || p->prt_max < port)
2193 60 : continue; /* Doesn't cover our port. */
2194 52 : mask = 0;
2195 52 : tor_assert(p->maskbits <= 32);
2196 :
2197 52 : if (p->maskbits)
2198 46 : mask = UINT32_MAX<<(32-p->maskbits);
2199 52 : ip = tor_addr_to_ipv4h(&p->addr);
2200 :
2201 : /* Calculate the first and last subnet that this exit policy touches
2202 : * and set it as loop boundaries. */
2203 104 : for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
2204 58 : tor_addr_t addr;
2205 58 : if (subnet_status[i] != 0)
2206 29 : continue; /* We already reject some part of this /8 */
2207 58 : tor_addr_from_ipv4h(&addr, i<<24);
2208 58 : if (tor_addr_is_internal(&addr, 0) &&
2209 28 : !get_options()->DirAllowPrivateAddresses) {
2210 28 : continue; /* Local or non-routable addresses */
2211 : }
2212 30 : if (p->policy_type == ADDR_POLICY_ACCEPT) {
2213 7 : if (p->maskbits > 8)
2214 1 : continue; /* Narrower than a /8. */
2215 : /* We found an allowed subnet of at least size /8. Done
2216 : * for this port! */
2217 6 : return 1;
2218 23 : } else if (p->policy_type == ADDR_POLICY_REJECT) {
2219 23 : subnet_status[i] = 1;
2220 : }
2221 : }
2222 177 : } SMARTLIST_FOREACH_END(p);
2223 : return 0;
2224 : }
2225 :
2226 : /** Return true iff <b>ri</b> is "useful as an exit node", meaning
2227 : * it allows exit to at least one /8 address space for each of ports 80
2228 : * and 443. */
2229 : int
2230 12 : exit_policy_is_general_exit(smartlist_t *policy)
2231 : {
2232 12 : if (!policy) /*XXXX disallow NULL policies? */
2233 : return 0;
2234 :
2235 14 : return (exit_policy_is_general_exit_helper(policy, 80) &&
2236 3 : exit_policy_is_general_exit_helper(policy, 443));
2237 : }
2238 :
2239 : /** Return false if <b>policy</b> might permit access to some addr:port;
2240 : * otherwise if we are certain it rejects everything, return true. If no
2241 : * part of <b>policy</b> matches, return <b>default_reject</b>.
2242 : * NULL policies are allowed, and treated as empty. */
2243 : int
2244 98 : policy_is_reject_star(const smartlist_t *policy, sa_family_t family,
2245 : int default_reject)
2246 : {
2247 98 : if (!policy)
2248 : return default_reject;
2249 257 : SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
2250 251 : if (p->policy_type == ADDR_POLICY_ACCEPT &&
2251 63 : (tor_addr_family(&p->addr) == family ||
2252 : tor_addr_family(&p->addr) == AF_UNSPEC)) {
2253 : return 0;
2254 195 : } else if (p->policy_type == ADDR_POLICY_REJECT &&
2255 188 : p->prt_min <= 1 && p->prt_max == 65535 &&
2256 168 : p->maskbits == 0 &&
2257 29 : (tor_addr_family(&p->addr) == family ||
2258 : tor_addr_family(&p->addr) == AF_UNSPEC)) {
2259 : return 1;
2260 : }
2261 173 : } SMARTLIST_FOREACH_END(p);
2262 : return default_reject;
2263 : }
2264 :
2265 : /** Write a single address policy to the buf_len byte buffer at buf. Return
2266 : * the number of characters written, or -1 on failure. */
2267 : int
2268 1305 : policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
2269 : int format_for_desc)
2270 : {
2271 1305 : size_t written = 0;
2272 1305 : char addrbuf[TOR_ADDR_BUF_LEN];
2273 1305 : const char *addrpart;
2274 1305 : int result;
2275 1305 : const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
2276 1305 : const sa_family_t family = tor_addr_family(&policy->addr);
2277 1305 : const int is_ip6 = (family == AF_INET6);
2278 :
2279 1305 : tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
2280 :
2281 : /* write accept/reject 1.2.3.4 */
2282 1305 : if (policy->is_private) {
2283 : addrpart = "private";
2284 1305 : } else if (policy->maskbits == 0) {
2285 378 : if (format_for_desc)
2286 : addrpart = "*";
2287 347 : else if (family == AF_INET6)
2288 : addrpart = "*6";
2289 222 : else if (family == AF_INET)
2290 : addrpart = "*4";
2291 : else
2292 0 : addrpart = "*";
2293 : } else {
2294 : addrpart = addrbuf;
2295 : }
2296 :
2297 2584 : result = tor_snprintf(buf, buflen, "%s%s %s",
2298 : is_accept ? "accept" : "reject",
2299 1305 : (is_ip6&&format_for_desc)?"6":"",
2300 : addrpart);
2301 1305 : if (result < 0)
2302 : return -1;
2303 1305 : written += strlen(buf);
2304 : /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
2305 : the mask is 0, we already wrote "*". */
2306 1956 : if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
2307 904 : if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
2308 : return -1;
2309 904 : written += strlen(buf+written);
2310 : }
2311 1305 : if (policy->prt_min <= 1 && policy->prt_max == 65535) {
2312 : /* There is no port set; write ":*" */
2313 1265 : if (written+4 > buflen)
2314 : return -1;
2315 1265 : strlcat(buf+written, ":*", buflen-written);
2316 1265 : written += 2;
2317 40 : } else if (policy->prt_min == policy->prt_max) {
2318 : /* There is only one port; write ":80". */
2319 40 : result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
2320 40 : if (result<0)
2321 : return -1;
2322 40 : written += result;
2323 : } else {
2324 : /* There is a range of ports; write ":79-80". */
2325 0 : result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
2326 : policy->prt_min, policy->prt_max);
2327 0 : if (result<0)
2328 : return -1;
2329 0 : written += result;
2330 : }
2331 1305 : if (written < buflen)
2332 1305 : buf[written] = '\0';
2333 : else
2334 : return -1;
2335 :
2336 1305 : return (int)written;
2337 : }
2338 :
2339 : /** Create a new exit policy summary, initially only with a single
2340 : * port 1-64k item */
2341 : /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
2342 : * RB-tree if that turns out to matter. */
2343 : static smartlist_t *
2344 591 : policy_summary_create(void)
2345 : {
2346 591 : smartlist_t *summary;
2347 591 : policy_summary_item_t* item;
2348 :
2349 591 : item = tor_malloc_zero(sizeof(policy_summary_item_t));
2350 591 : item->prt_min = 1;
2351 591 : item->prt_max = 65535;
2352 591 : item->reject_count = 0;
2353 591 : item->accepted = 0;
2354 :
2355 591 : summary = smartlist_new();
2356 591 : smartlist_add(summary, item);
2357 :
2358 591 : return summary;
2359 : }
2360 :
2361 : /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
2362 : * The current item is changed to end at new-starts - 1, the new item
2363 : * copies reject_count and accepted from the old item,
2364 : * starts at new_starts and ends at the port where the original item
2365 : * previously ended.
2366 : */
2367 : static policy_summary_item_t*
2368 65248 : policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
2369 : {
2370 65248 : policy_summary_item_t* new;
2371 :
2372 65248 : new = tor_malloc_zero(sizeof(policy_summary_item_t));
2373 65248 : new->prt_min = new_starts;
2374 65248 : new->prt_max = old->prt_max;
2375 65248 : new->reject_count = old->reject_count;
2376 65248 : new->accepted = old->accepted;
2377 :
2378 65248 : old->prt_max = new_starts-1;
2379 :
2380 65248 : tor_assert(old->prt_min <= old->prt_max);
2381 65248 : tor_assert(new->prt_min <= new->prt_max);
2382 65248 : return new;
2383 : }
2384 :
2385 : /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
2386 : * my immortal soul, he can clean it up himself. */
2387 : #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
2388 :
2389 : #define IPV4_BITS (32)
2390 : /* Every IPv4 address is counted as one rejection */
2391 : #define REJECT_CUTOFF_SCALE_IPV4 (0)
2392 : /* Ports are rejected in an IPv4 summary if they are rejected in more than two
2393 : * IPv4 /8 address blocks */
2394 : #define REJECT_CUTOFF_COUNT_IPV4 (UINT64_C(1) << \
2395 : (IPV4_BITS - REJECT_CUTOFF_SCALE_IPV4 - 7))
2396 :
2397 : #define IPV6_BITS (128)
2398 : /* IPv6 /64s are counted as one rejection, anything smaller is ignored */
2399 : #define REJECT_CUTOFF_SCALE_IPV6 (64)
2400 : /* Ports are rejected in an IPv6 summary if they are rejected in more than one
2401 : * IPv6 /16 address block.
2402 : * This is roughly equivalent to the IPv4 cutoff, as only five IPv6 /12s (and
2403 : * some scattered smaller blocks) have been allocated to the RIRs.
2404 : * Network providers are typically allocated one or more IPv6 /32s.
2405 : */
2406 : #define REJECT_CUTOFF_COUNT_IPV6 (UINT64_C(1) << \
2407 : (IPV6_BITS - REJECT_CUTOFF_SCALE_IPV6 - 16))
2408 :
2409 : /** Split an exit policy summary so that prt_min and prt_max
2410 : * fall at exactly the start and end of an item respectively.
2411 : */
2412 : static int
2413 33723 : policy_summary_split(smartlist_t *summary,
2414 : uint16_t prt_min, uint16_t prt_max)
2415 : {
2416 33723 : int start_at_index;
2417 :
2418 33723 : int i = 0;
2419 :
2420 25768107 : while (AT(i)->prt_max < prt_min)
2421 25734384 : i++;
2422 33723 : if (AT(i)->prt_min != prt_min) {
2423 32520 : policy_summary_item_t* new_item;
2424 32520 : new_item = policy_summary_item_split(AT(i), prt_min);
2425 32520 : smartlist_insert(summary, i+1, new_item);
2426 32520 : i++;
2427 : }
2428 33723 : start_at_index = i;
2429 :
2430 98971 : while (AT(i)->prt_max < prt_max)
2431 65248 : i++;
2432 33723 : if (AT(i)->prt_max != prt_max) {
2433 32728 : policy_summary_item_t* new_item;
2434 32728 : new_item = policy_summary_item_split(AT(i), prt_max+1);
2435 32728 : smartlist_insert(summary, i+1, new_item);
2436 : }
2437 :
2438 33723 : return start_at_index;
2439 : }
2440 :
2441 : /** Mark port ranges as accepted if they are below the reject_count for family
2442 : */
2443 : static void
2444 8715 : policy_summary_accept(smartlist_t *summary,
2445 : uint16_t prt_min, uint16_t prt_max,
2446 : sa_family_t family)
2447 : {
2448 8715 : tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2449 17430 : uint64_t family_reject_count = ((family == AF_INET) ?
2450 8715 : REJECT_CUTOFF_COUNT_IPV4 :
2451 : REJECT_CUTOFF_COUNT_IPV6);
2452 :
2453 8715 : int i = policy_summary_split(summary, prt_min, prt_max);
2454 65686 : while (i < smartlist_len(summary) &&
2455 65539 : AT(i)->prt_max <= prt_max) {
2456 56971 : if (!AT(i)->accepted &&
2457 56971 : AT(i)->reject_count <= family_reject_count)
2458 32763 : AT(i)->accepted = 1;
2459 56971 : i++;
2460 : }
2461 8715 : tor_assert(i < smartlist_len(summary) || prt_max==65535);
2462 8715 : }
2463 :
2464 : /** Count the number of addresses in a network in family with prefixlen
2465 : * maskbits against the given portrange. */
2466 : static void
2467 25008 : policy_summary_reject(smartlist_t *summary,
2468 : maskbits_t maskbits,
2469 : uint16_t prt_min, uint16_t prt_max,
2470 : sa_family_t family)
2471 : {
2472 25008 : tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
2473 :
2474 25008 : int i = policy_summary_split(summary, prt_min, prt_max);
2475 :
2476 : /* The length of a single address mask */
2477 25008 : int addrbits = (family == AF_INET) ? IPV4_BITS : IPV6_BITS;
2478 25008 : tor_assert_nonfatal_once(addrbits >= maskbits);
2479 :
2480 : /* We divide IPv6 address counts by (1 << scale) to keep them in a uint64_t
2481 : */
2482 50016 : int scale = ((family == AF_INET) ?
2483 25008 : REJECT_CUTOFF_SCALE_IPV4 :
2484 : REJECT_CUTOFF_SCALE_IPV6);
2485 :
2486 25008 : tor_assert_nonfatal_once(addrbits >= scale);
2487 25008 : if (maskbits > (addrbits - scale)) {
2488 80 : tor_assert_nonfatal_once(family == AF_INET6);
2489 : /* The address range is so small, we'd need billions of them to reach the
2490 : * rejection limit. So we ignore this range in the reject count. */
2491 80 : return;
2492 : }
2493 :
2494 24928 : uint64_t count = 0;
2495 24928 : if (addrbits - scale - maskbits >= 64) {
2496 8152 : tor_assert_nonfatal_once(family == AF_INET6);
2497 : /* The address range is so large, it's an automatic rejection for all ports
2498 : * in the range. */
2499 : count = UINT64_MAX;
2500 : } else {
2501 16776 : count = (UINT64_C(1) << (addrbits - scale - maskbits));
2502 : }
2503 24928 : tor_assert_nonfatal_once(count > 0);
2504 66848 : while (i < smartlist_len(summary) &&
2505 66240 : AT(i)->prt_max <= prt_max) {
2506 41920 : if (AT(i)->reject_count <= UINT64_MAX - count) {
2507 41760 : AT(i)->reject_count += count;
2508 : } else {
2509 : /* IPv4 would require a 4-billion address redundant policy to get here,
2510 : * but IPv6 just needs to have ::/0 */
2511 160 : if (family == AF_INET) {
2512 0 : tor_assert_nonfatal_unreached_once();
2513 : }
2514 : /* If we do get here, use saturating arithmetic */
2515 160 : AT(i)->reject_count = UINT64_MAX;
2516 : }
2517 41920 : i++;
2518 : }
2519 24928 : tor_assert(i < smartlist_len(summary) || prt_max==65535);
2520 : }
2521 :
2522 : /** Add a single exit policy item to our summary:
2523 : *
2524 : * If it is an accept, ignore it unless it is for all IP addresses
2525 : * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
2526 : * policy_summary_accept().
2527 : *
2528 : * If it is a reject, ignore it if it is about one of the private
2529 : * networks. Otherwise call policy_summary_reject().
2530 : */
2531 : static void
2532 34879 : policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
2533 : {
2534 34879 : if (p->policy_type == ADDR_POLICY_ACCEPT) {
2535 8731 : if (p->maskbits == 0) {
2536 8715 : policy_summary_accept(summary, p->prt_min, p->prt_max, p->addr.family);
2537 : }
2538 26148 : } else if (p->policy_type == ADDR_POLICY_REJECT) {
2539 :
2540 330852 : int is_private = 0;
2541 : int i;
2542 330852 : for (i = 0; private_nets[i]; ++i) {
2543 305844 : tor_addr_t addr;
2544 305844 : maskbits_t maskbits;
2545 305844 : if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
2546 : &maskbits, NULL, NULL)<0) {
2547 0 : tor_assert(0);
2548 : }
2549 305844 : if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
2550 33748 : p->maskbits == maskbits) {
2551 1140 : is_private = 1;
2552 1140 : break;
2553 : }
2554 : }
2555 :
2556 1140 : if (!is_private) {
2557 25008 : policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max,
2558 25008 : p->addr.family);
2559 : }
2560 : } else
2561 0 : tor_assert(0);
2562 34879 : }
2563 :
2564 : /** Create a string representing a summary for an exit policy.
2565 : * The summary will either be an "accept" plus a comma-separated list of port
2566 : * ranges or a "reject" plus port-ranges, depending on which is shorter.
2567 : *
2568 : * If no exits are allowed at all then "reject 1-65535" is returned. If no
2569 : * ports are blocked instead of "reject " we return "accept 1-65535". (These
2570 : * are an exception to the shorter-representation-wins rule).
2571 : */
2572 : char *
2573 591 : policy_summarize(smartlist_t *policy, sa_family_t family)
2574 : {
2575 591 : smartlist_t *summary = policy_summary_create();
2576 591 : smartlist_t *accepts, *rejects;
2577 591 : int i, last, start_prt;
2578 591 : size_t accepts_len, rejects_len;
2579 591 : char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
2580 591 : const char *prefix;
2581 :
2582 591 : tor_assert(policy);
2583 :
2584 : /* Create the summary list */
2585 58818 : SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
2586 58227 : sa_family_t f = tor_addr_family(&p->addr);
2587 58227 : if (f != AF_INET && f != AF_INET6) {
2588 0 : log_warn(LD_BUG, "Weird family when summarizing address policy");
2589 : }
2590 58227 : if (f != family)
2591 23348 : continue;
2592 34879 : policy_summary_add_item(summary, p);
2593 58227 : } SMARTLIST_FOREACH_END(p);
2594 :
2595 : /* Now create two lists of strings, one for accepted and one
2596 : * for rejected ports. We take care to merge ranges so that
2597 : * we avoid getting stuff like "1-4,5-9,10", instead we want
2598 : * "1-10"
2599 : */
2600 591 : i = 0;
2601 591 : start_prt = 1;
2602 591 : accepts = smartlist_new();
2603 591 : rejects = smartlist_new();
2604 131087 : while (1) {
2605 65839 : last = i == smartlist_len(summary)-1;
2606 65839 : if (last ||
2607 65248 : AT(i)->accepted != AT(i+1)->accepted) {
2608 65471 : char buf[POLICY_BUF_LEN];
2609 :
2610 65471 : if (start_prt == AT(i)->prt_max)
2611 62584 : tor_snprintf(buf, sizeof(buf), "%d", start_prt);
2612 : else
2613 2887 : tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
2614 :
2615 65471 : if (AT(i)->accepted)
2616 32587 : smartlist_add_strdup(accepts, buf);
2617 : else
2618 32884 : smartlist_add_strdup(rejects, buf);
2619 :
2620 65471 : if (last)
2621 : break;
2622 :
2623 64880 : start_prt = AT(i+1)->prt_min;
2624 65248 : };
2625 65248 : i++;
2626 591 : };
2627 :
2628 : /* Figure out which of the two stringlists will be shorter and use
2629 : * that to build the result
2630 : */
2631 591 : if (smartlist_len(accepts) == 0) { /* no exits at all */
2632 228 : result = tor_strdup("reject 1-65535");
2633 228 : goto cleanup;
2634 : }
2635 363 : if (smartlist_len(rejects) == 0) { /* no rejects at all */
2636 59 : result = tor_strdup("accept 1-65535");
2637 59 : goto cleanup;
2638 : }
2639 :
2640 304 : accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
2641 304 : rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
2642 :
2643 304 : if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
2644 48 : accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
2645 48 : char *c;
2646 48 : shorter_str = accepts_str;
2647 48 : prefix = "accept";
2648 :
2649 48 : c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
2650 144 : while (*c != ',' && c >= shorter_str)
2651 96 : c--;
2652 48 : tor_assert(c >= shorter_str);
2653 48 : tor_assert(*c == ',');
2654 48 : *c = '\0';
2655 :
2656 256 : } else if (rejects_len < accepts_len) {
2657 : shorter_str = rejects_str;
2658 : prefix = "reject";
2659 : } else {
2660 216 : shorter_str = accepts_str;
2661 216 : prefix = "accept";
2662 : }
2663 :
2664 304 : tor_asprintf(&result, "%s %s", prefix, shorter_str);
2665 :
2666 591 : cleanup:
2667 : /* cleanup */
2668 66430 : SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
2669 591 : smartlist_free(summary);
2670 :
2671 591 : tor_free(accepts_str);
2672 33178 : SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
2673 591 : smartlist_free(accepts);
2674 :
2675 591 : tor_free(rejects_str);
2676 33475 : SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
2677 591 : smartlist_free(rejects);
2678 :
2679 591 : return result;
2680 : }
2681 :
2682 : /** Convert a summarized policy string into a short_policy_t. Return NULL
2683 : * if the string is not well-formed. */
2684 : short_policy_t *
2685 4389 : parse_short_policy(const char *summary)
2686 : {
2687 4389 : const char *orig_summary = summary;
2688 4389 : short_policy_t *result;
2689 4389 : int is_accept;
2690 4389 : int n_entries;
2691 4389 : short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
2692 4389 : char *next;
2693 :
2694 4389 : if (!strcmpstart(summary, "accept ")) {
2695 4216 : is_accept = 1;
2696 4216 : summary += strlen("accept ");
2697 173 : } else if (!strcmpstart(summary, "reject ")) {
2698 164 : is_accept = 0;
2699 164 : summary += strlen("reject ");
2700 : } else {
2701 9 : log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
2702 9 : return NULL;
2703 : }
2704 :
2705 4380 : n_entries = 0;
2706 24279 : for ( ; *summary; summary = next) {
2707 19911 : if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
2708 1 : log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
2709 : escaped(orig_summary));
2710 1 : return NULL;
2711 : }
2712 :
2713 19910 : unsigned low, high;
2714 19910 : int ok;
2715 19910 : low = (unsigned) tor_parse_ulong(summary, 10, 1, 65535, &ok, &next);
2716 19910 : if (!ok) {
2717 14 : if (! TOR_ISDIGIT(*summary) || *summary == ',') {
2718 : /* Unrecognized format: skip it. */
2719 13 : goto skip_ent;
2720 : } else {
2721 1 : goto bad_ent;
2722 : }
2723 : }
2724 :
2725 19896 : switch (*next) {
2726 15114 : case ',':
2727 15114 : ++next;
2728 : FALLTHROUGH;
2729 : case '\0':
2730 : high = low;
2731 : break;
2732 633 : case '-':
2733 633 : high = (unsigned) tor_parse_ulong(next+1, 10, low, 65535, &ok, &next);
2734 633 : if (!ok)
2735 5 : goto bad_ent;
2736 :
2737 628 : if (*next == ',')
2738 409 : ++next;
2739 219 : else if (*next != '\0')
2740 0 : goto bad_ent;
2741 :
2742 : break;
2743 2 : default:
2744 2 : goto bad_ent;
2745 : }
2746 :
2747 19889 : entries[n_entries].min_port = low;
2748 19889 : entries[n_entries].max_port = high;
2749 19889 : n_entries++;
2750 :
2751 19889 : continue;
2752 13 : skip_ent:
2753 13 : next = strchr(next, ',');
2754 13 : if (!next)
2755 : break;
2756 10 : ++next;
2757 : }
2758 :
2759 4371 : if (n_entries == 0) {
2760 3 : log_fn(LOG_PROTOCOL_WARN, LD_DIR,
2761 : "Found no port-range entries in summary %s", escaped(orig_summary));
2762 3 : return NULL;
2763 : }
2764 :
2765 : {
2766 4368 : size_t size = offsetof(short_policy_t, entries) +
2767 : sizeof(short_policy_entry_t)*(n_entries);
2768 4368 : result = tor_malloc_zero(size);
2769 :
2770 4368 : tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
2771 : }
2772 :
2773 4368 : result->is_accept = is_accept;
2774 4368 : result->n_entries = n_entries;
2775 4368 : memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
2776 4368 : return result;
2777 :
2778 8 : bad_ent:
2779 8 : log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
2780 : escaped(orig_summary));
2781 8 : return NULL;
2782 : }
2783 :
2784 : /** Write <b>policy</b> back out into a string. */
2785 : char *
2786 487 : write_short_policy(const short_policy_t *policy)
2787 : {
2788 487 : int i;
2789 487 : char *answer;
2790 487 : smartlist_t *sl = smartlist_new();
2791 :
2792 487 : smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
2793 :
2794 15867 : for (i=0; i < policy->n_entries; i++) {
2795 14893 : const short_policy_entry_t *e = &policy->entries[i];
2796 14893 : if (e->min_port == e->max_port) {
2797 14304 : smartlist_add_asprintf(sl, "%d", e->min_port);
2798 : } else {
2799 589 : smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
2800 : }
2801 14893 : if (i < policy->n_entries-1)
2802 14406 : smartlist_add_strdup(sl, ",");
2803 : }
2804 487 : answer = smartlist_join_strings(sl, "", 0, NULL);
2805 30273 : SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
2806 487 : smartlist_free(sl);
2807 487 : return answer;
2808 : }
2809 :
2810 : /** Release all storage held in <b>policy</b>. */
2811 : void
2812 33682 : short_policy_free_(short_policy_t *policy)
2813 : {
2814 33682 : tor_free(policy);
2815 33682 : }
2816 :
2817 : /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
2818 : * or rejected by the summarized policy <b>policy</b>. Return values are as
2819 : * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
2820 : * functions, requires the <b>port</b> be specified. */
2821 : addr_policy_result_t
2822 117 : compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
2823 : const short_policy_t *policy)
2824 : {
2825 117 : int i;
2826 117 : int found_match = 0;
2827 117 : int accept_;
2828 :
2829 117 : tor_assert(port != 0);
2830 :
2831 117 : if (addr && tor_addr_is_null(addr))
2832 : addr = NULL; /* Unspec means 'no address at all,' in this context. */
2833 :
2834 117 : if (addr && get_options()->ClientRejectInternalAddresses &&
2835 0 : (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
2836 0 : return ADDR_POLICY_REJECTED;
2837 :
2838 117 : for (i=0; i < policy->n_entries; ++i) {
2839 117 : const short_policy_entry_t *e = &policy->entries[i];
2840 117 : if (e->min_port <= port && port <= e->max_port) {
2841 : found_match = 1;
2842 : break;
2843 : }
2844 : }
2845 :
2846 117 : if (found_match)
2847 117 : accept_ = policy->is_accept;
2848 : else
2849 0 : accept_ = ! policy->is_accept;
2850 :
2851 : /* ???? are these right? -NM */
2852 : /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
2853 : * case here, because it would cause clients to believe that the node
2854 : * allows exit enclaving. Trying it anyway would open up a cool attack
2855 : * where the node refuses due to exitpolicy, the client reacts in
2856 : * surprise by rewriting the node's exitpolicy to reject *:*, and then
2857 : * an adversary targets users by causing them to attempt such connections
2858 : * to 98% of the exits.
2859 : *
2860 : * Once microdescriptors can handle addresses in special cases (e.g. if
2861 : * we ever solve ticket 1774), we can provide certainty here. -RD */
2862 117 : if (accept_)
2863 : return ADDR_POLICY_PROBABLY_ACCEPTED;
2864 : else
2865 0 : return ADDR_POLICY_REJECTED;
2866 : }
2867 :
2868 : /** Return true iff <b>policy</b> seems reject all ports */
2869 : int
2870 16 : short_policy_is_reject_star(const short_policy_t *policy)
2871 : {
2872 : /* This doesn't need to be as much on the lookout as policy_is_reject_star,
2873 : * since policy summaries are from the consensus or from consensus
2874 : * microdescs.
2875 : */
2876 16 : tor_assert(policy);
2877 : /* Check for an exact match of "reject 1-65535". */
2878 16 : return (policy->is_accept == 0 && policy->n_entries == 1 &&
2879 16 : policy->entries[0].min_port == 1 &&
2880 : policy->entries[0].max_port == 65535);
2881 : }
2882 :
2883 : /** Decide whether addr:port is probably or definitely accepted or rejected by
2884 : * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
2885 : * interpretation. */
2886 : addr_policy_result_t
2887 813 : compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
2888 : const node_t *node)
2889 : {
2890 813 : if (node->rejects_all)
2891 : return ADDR_POLICY_REJECTED;
2892 :
2893 813 : if (addr && tor_addr_family(addr) == AF_INET6) {
2894 0 : const short_policy_t *p = NULL;
2895 0 : if (node->ri)
2896 0 : p = node->ri->ipv6_exit_policy;
2897 0 : else if (node->md)
2898 0 : p = node->md->ipv6_exit_policy;
2899 0 : if (p)
2900 0 : return compare_tor_addr_to_short_policy(addr, port, p);
2901 : else
2902 : return ADDR_POLICY_REJECTED;
2903 : }
2904 :
2905 813 : if (node->ri) {
2906 0 : return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
2907 813 : } else if (node->md) {
2908 813 : if (node->md->exit_policy == NULL)
2909 : return ADDR_POLICY_REJECTED;
2910 : else
2911 117 : return compare_tor_addr_to_short_policy(addr, port,
2912 : node->md->exit_policy);
2913 : } else {
2914 : return ADDR_POLICY_PROBABLY_REJECTED;
2915 : }
2916 : }
2917 :
2918 : /**
2919 : * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
2920 : * representation of the list.
2921 : * If <b>include_ipv4</b> is true, include IPv4 entries.
2922 : * If <b>include_ipv6</b> is true, include IPv6 entries.
2923 : */
2924 : char *
2925 32 : policy_dump_to_string(const smartlist_t *policy_list,
2926 : int include_ipv4,
2927 : int include_ipv6)
2928 : {
2929 32 : smartlist_t *policy_string_list;
2930 32 : char *policy_string = NULL;
2931 :
2932 32 : policy_string_list = smartlist_new();
2933 :
2934 95 : SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
2935 63 : char *pbuf;
2936 63 : int bytes_written_to_pbuf;
2937 63 : if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2938 1 : continue; /* Don't include IPv6 parts of address policy */
2939 : }
2940 62 : if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2941 1 : continue; /* Don't include IPv4 parts of address policy */
2942 : }
2943 :
2944 61 : pbuf = tor_malloc(POLICY_BUF_LEN);
2945 61 : bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2946 :
2947 61 : if (bytes_written_to_pbuf < 0) {
2948 0 : log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
2949 0 : tor_free(pbuf);
2950 0 : goto done;
2951 : }
2952 :
2953 61 : smartlist_add(policy_string_list,pbuf);
2954 63 : } SMARTLIST_FOREACH_END(tmpe);
2955 :
2956 32 : policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
2957 :
2958 32 : done:
2959 93 : SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
2960 32 : smartlist_free(policy_string_list);
2961 :
2962 32 : return policy_string;
2963 : }
2964 :
2965 : /** Implementation for GETINFO control command: knows the answer for questions
2966 : * about "exit-policy/..." */
2967 : int
2968 19 : getinfo_helper_policies(control_connection_t *conn,
2969 : const char *question, char **answer,
2970 : const char **errmsg)
2971 : {
2972 19 : (void) conn;
2973 19 : (void) errmsg;
2974 19 : if (!strcmp(question, "exit-policy/default")) {
2975 1 : *answer = tor_strdup(DEFAULT_EXIT_POLICY);
2976 18 : } else if (!strcmp(question, "exit-policy/reject-private/default")) {
2977 1 : smartlist_t *private_policy_strings;
2978 1 : const char **priv = private_nets;
2979 :
2980 1 : private_policy_strings = smartlist_new();
2981 :
2982 13 : while (*priv != NULL) {
2983 : /* IPv6 addresses are in "[]" and contain ":",
2984 : * IPv4 addresses are not in "[]" and contain "." */
2985 12 : smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
2986 12 : priv++;
2987 : }
2988 :
2989 1 : *answer = smartlist_join_strings(private_policy_strings,
2990 : ",", 0, NULL);
2991 :
2992 13 : SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
2993 1 : smartlist_free(private_policy_strings);
2994 17 : } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
2995 5 : const or_options_t *options = get_options();
2996 5 : int err = 0;
2997 5 : const routerinfo_t *me = router_get_my_routerinfo_with_err(&err);
2998 :
2999 5 : if (!me) {
3000 0 : *errmsg = routerinfo_err_to_string(err);
3001 2 : return routerinfo_err_is_transient(err) ? -1 : 0;
3002 : }
3003 :
3004 5 : if (!options->ExitPolicyRejectPrivate &&
3005 : !options->ExitPolicyRejectLocalInterfaces) {
3006 2 : *answer = tor_strdup("");
3007 2 : return 0;
3008 : }
3009 :
3010 3 : smartlist_t *private_policy_list = smartlist_new();
3011 3 : smartlist_t *configured_addresses = smartlist_new();
3012 :
3013 : /* Copy the configured addresses into the tor_addr_t* list */
3014 3 : if (options->ExitPolicyRejectPrivate) {
3015 2 : policies_copy_addr_to_smartlist(configured_addresses, &me->ipv4_addr);
3016 2 : policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
3017 : }
3018 :
3019 3 : if (options->ExitPolicyRejectLocalInterfaces) {
3020 2 : policies_copy_outbound_addresses_to_smartlist(configured_addresses,
3021 : options);
3022 : }
3023 :
3024 3 : policies_parse_exit_policy_reject_private(
3025 : &private_policy_list,
3026 3 : options->IPv6Exit,
3027 : configured_addresses,
3028 : options->ExitPolicyRejectLocalInterfaces,
3029 3 : options->ExitPolicyRejectLocalInterfaces);
3030 3 : *answer = policy_dump_to_string(private_policy_list, 1, 1);
3031 :
3032 3 : addr_policy_list_free(private_policy_list);
3033 11 : SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
3034 3 : smartlist_free(configured_addresses);
3035 12 : } else if (!strcmpstart(question, "exit-policy/")) {
3036 12 : int include_ipv4 = 0;
3037 12 : int include_ipv6 = 0;
3038 :
3039 12 : int err = 0;
3040 12 : const routerinfo_t *me = router_get_my_routerinfo_with_err(&err);
3041 :
3042 12 : if (!me) {
3043 6 : *errmsg = routerinfo_err_to_string(err);
3044 12 : return routerinfo_err_is_transient(err) ? -1 : 0;
3045 : }
3046 :
3047 6 : if (!strcmp(question, "exit-policy/ipv4")) {
3048 : include_ipv4 = 1;
3049 4 : } else if (!strcmp(question, "exit-policy/ipv6")) {
3050 : include_ipv6 = 1;
3051 2 : } else if (!strcmp(question, "exit-policy/full")) {
3052 : include_ipv4 = include_ipv6 = 1;
3053 : } else {
3054 : return 0; /* No such key. */
3055 : }
3056 :
3057 6 : *answer = router_dump_exit_policy_to_string(me,include_ipv4,
3058 : include_ipv6);
3059 : }
3060 :
3061 : return 0;
3062 : }
3063 :
3064 : /** Release all storage held by <b>p</b>. */
3065 : void
3066 9521 : addr_policy_list_free_(smartlist_t *lst)
3067 : {
3068 9521 : if (!lst)
3069 : return;
3070 60828 : SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
3071 1129 : smartlist_free(lst);
3072 : }
3073 :
3074 : /** Release all storage held by <b>p</b>. */
3075 : void
3076 160946 : addr_policy_free_(addr_policy_t *p)
3077 : {
3078 160946 : if (!p)
3079 : return;
3080 :
3081 160945 : if (--p->refcnt <= 0) {
3082 149408 : if (p->is_canonical) {
3083 149391 : policy_map_ent_t search, *found;
3084 149391 : search.policy = p;
3085 149391 : found = HT_REMOVE(policy_map, &policy_root, &search);
3086 149391 : if (found) {
3087 149391 : tor_assert(p == found->policy);
3088 149391 : tor_free(found);
3089 : }
3090 : }
3091 149408 : tor_free(p);
3092 : }
3093 : }
3094 :
3095 : /** Release all storage held by policy variables. */
3096 : void
3097 268 : policies_free_all(void)
3098 : {
3099 268 : addr_policy_list_free(reachable_or_addr_policy);
3100 268 : reachable_or_addr_policy = NULL;
3101 268 : addr_policy_list_free(reachable_dir_addr_policy);
3102 268 : reachable_dir_addr_policy = NULL;
3103 268 : addr_policy_list_free(socks_policy);
3104 268 : socks_policy = NULL;
3105 268 : addr_policy_list_free(dir_policy);
3106 268 : dir_policy = NULL;
3107 268 : addr_policy_list_free(metrics_policy);
3108 268 : metrics_policy = NULL;
3109 268 : addr_policy_list_free(authdir_reject_policy);
3110 268 : authdir_reject_policy = NULL;
3111 268 : addr_policy_list_free(authdir_invalid_policy);
3112 268 : authdir_invalid_policy = NULL;
3113 268 : addr_policy_list_free(authdir_badexit_policy);
3114 268 : authdir_badexit_policy = NULL;
3115 :
3116 268 : if (!HT_EMPTY(&policy_root)) {
3117 0 : policy_map_ent_t **ent;
3118 0 : int n = 0;
3119 0 : char buf[POLICY_BUF_LEN];
3120 :
3121 0 : log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
3122 : (int)HT_SIZE(&policy_root));
3123 :
3124 : /* Note the first 10 cached policies to try to figure out where they
3125 : * might be coming from. */
3126 0 : HT_FOREACH(ent, policy_map, &policy_root) {
3127 0 : if (++n > 10)
3128 : break;
3129 0 : if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
3130 0 : log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
3131 : }
3132 : }
3133 268 : HT_CLEAR(policy_map, &policy_root);
3134 268 : }
|