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