ip_fw2.c revision 200567
1/*- 2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 1. Redistributions of source code must retain the above copyright 8 * notice, this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright 10 * notice, this list of conditions and the following disclaimer in the 11 * documentation and/or other materials provided with the distribution. 12 * 13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 23 * SUCH DAMAGE. 24 */ 25 26#include <sys/cdefs.h> 27__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 200567 2009-12-15 09:46:27Z luigi $"); 28 29#define DEB(x) 30#define DDB(x) x 31 32/* 33 * Implement IP packet firewall (new version) 34 */ 35 36#if !defined(KLD_MODULE) 37#include "opt_ipfw.h" 38#include "opt_ipdivert.h" 39#include "opt_ipdn.h" 40#include "opt_inet.h" 41#ifndef INET 42#error IPFIREWALL requires INET. 43#endif /* INET */ 44#endif 45#include "opt_inet6.h" 46#include "opt_ipsec.h" 47 48#include <sys/param.h> 49#include <sys/systm.h> 50#include <sys/condvar.h> 51#include <sys/eventhandler.h> 52#include <sys/malloc.h> 53#include <sys/mbuf.h> 54#include <sys/kernel.h> 55#include <sys/lock.h> 56#include <sys/jail.h> 57#include <sys/module.h> 58#include <sys/priv.h> 59#include <sys/proc.h> 60#include <sys/rwlock.h> 61#include <sys/socket.h> 62#include <sys/socketvar.h> 63#include <sys/sysctl.h> 64#include <sys/syslog.h> 65#include <sys/ucred.h> 66#include <net/ethernet.h> /* for ETHERTYPE_IP */ 67#include <net/if.h> 68#include <net/radix.h> 69#include <net/route.h> 70#include <net/pf_mtag.h> 71#include <net/vnet.h> 72 73#define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */ 74 75#include <netinet/in.h> 76#include <netinet/in_var.h> 77#include <netinet/in_pcb.h> 78#include <netinet/ip.h> 79#include <netinet/ip_var.h> 80#include <netinet/ip_icmp.h> 81#include <netinet/ip_fw.h> 82#include <netinet/ip_divert.h> 83#include <netinet/ip_dummynet.h> 84#include <netinet/ip_carp.h> 85#include <netinet/pim.h> 86#include <netinet/tcp_var.h> 87#include <netinet/udp.h> 88#include <netinet/udp_var.h> 89#include <netinet/sctp.h> 90 91#include <netgraph/ng_ipfw.h> 92 93#include <netinet/ip6.h> 94#include <netinet/icmp6.h> 95#ifdef INET6 96#include <netinet6/scope6_var.h> 97#include <netinet6/ip6_var.h> 98#endif 99 100#include <machine/in_cksum.h> /* XXX for in_cksum */ 101 102#ifdef MAC 103#include <security/mac/mac_framework.h> 104#endif 105 106static VNET_DEFINE(int, ipfw_vnet_ready) = 0; 107#define V_ipfw_vnet_ready VNET(ipfw_vnet_ready) 108/* 109 * set_disable contains one bit per set value (0..31). 110 * If the bit is set, all rules with the corresponding set 111 * are disabled. Set RESVD_SET(31) is reserved for the default rule 112 * and rules that are not deleted by the flush command, 113 * and CANNOT be disabled. 114 * Rules in set RESVD_SET can only be deleted explicitly. 115 */ 116static VNET_DEFINE(u_int32_t, set_disable); 117static VNET_DEFINE(int, fw_verbose); 118static VNET_DEFINE(struct callout, ipfw_timeout); 119static VNET_DEFINE(int, verbose_limit); 120 121#define V_set_disable VNET(set_disable) 122#define V_fw_verbose VNET(fw_verbose) 123#define V_ipfw_timeout VNET(ipfw_timeout) 124#define V_verbose_limit VNET(verbose_limit) 125 126#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT 127static int default_to_accept = 1; 128#else 129static int default_to_accept; 130#endif 131static uma_zone_t ipfw_dyn_rule_zone; 132 133struct ip_fw *ip_fw_default_rule; 134 135/* 136 * list of rules for layer 3 137 */ 138VNET_DEFINE(struct ip_fw_chain, layer3_chain); 139 140MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's"); 141MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables"); 142#define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL) 143ipfw_nat_t *ipfw_nat_ptr = NULL; 144ipfw_nat_cfg_t *ipfw_nat_cfg_ptr; 145ipfw_nat_cfg_t *ipfw_nat_del_ptr; 146ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr; 147ipfw_nat_cfg_t *ipfw_nat_get_log_ptr; 148 149struct table_entry { 150 struct radix_node rn[2]; 151 struct sockaddr_in addr, mask; 152 u_int32_t value; 153}; 154 155static VNET_DEFINE(int, autoinc_step); 156#define V_autoinc_step VNET(autoinc_step) 157static VNET_DEFINE(int, fw_deny_unknown_exthdrs); 158#define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs) 159 160extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS); 161 162#ifdef SYSCTL_NODE 163SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall"); 164SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable, 165 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0, 166 ipfw_chg_hook, "I", "Enable ipfw"); 167SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, 168 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0, 169 "Rule number auto-increment step"); 170SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass, 171 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0, 172 "Only do a single pass through ipfw when using dummynet(4)"); 173SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose, 174 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0, 175 "Log matches to ipfw rules"); 176SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, 177 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0, 178 "Set upper limit of matches of ipfw rules logged"); 179SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD, 180 NULL, IPFW_DEFAULT_RULE, 181 "The default/max possible rule number."); 182SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD, 183 NULL, IPFW_TABLES_MAX, 184 "The maximum number of tables."); 185SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN, 186 &default_to_accept, 0, 187 "Make the default rule accept all packets."); 188TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept); 189 190#ifdef INET6 191SYSCTL_DECL(_net_inet6_ip6); 192SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall"); 193SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable, 194 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0, 195 ipfw_chg_hook, "I", "Enable ipfw+6"); 196SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs, 197 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0, 198 "Deny packets with unknown IPv6 Extension Headers"); 199#endif /* INET6 */ 200 201#endif /* SYSCTL_NODE */ 202 203/* 204 * Description of dynamic rules. 205 * 206 * Dynamic rules are stored in lists accessed through a hash table 207 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can 208 * be modified through the sysctl variable dyn_buckets which is 209 * updated when the table becomes empty. 210 * 211 * XXX currently there is only one list, ipfw_dyn. 212 * 213 * When a packet is received, its address fields are first masked 214 * with the mask defined for the rule, then hashed, then matched 215 * against the entries in the corresponding list. 216 * Dynamic rules can be used for different purposes: 217 * + stateful rules; 218 * + enforcing limits on the number of sessions; 219 * + in-kernel NAT (not implemented yet) 220 * 221 * The lifetime of dynamic rules is regulated by dyn_*_lifetime, 222 * measured in seconds and depending on the flags. 223 * 224 * The total number of dynamic rules is stored in dyn_count. 225 * The max number of dynamic rules is dyn_max. When we reach 226 * the maximum number of rules we do not create anymore. This is 227 * done to avoid consuming too much memory, but also too much 228 * time when searching on each packet (ideally, we should try instead 229 * to put a limit on the length of the list on each bucket...). 230 * 231 * Each dynamic rule holds a pointer to the parent ipfw rule so 232 * we know what action to perform. Dynamic rules are removed when 233 * the parent rule is deleted. XXX we should make them survive. 234 * 235 * There are some limitations with dynamic rules -- we do not 236 * obey the 'randomized match', and we do not do multiple 237 * passes through the firewall. XXX check the latter!!! 238 */ 239static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v); 240static VNET_DEFINE(u_int32_t, dyn_buckets); 241static VNET_DEFINE(u_int32_t, curr_dyn_buckets); 242 243#define V_ipfw_dyn_v VNET(ipfw_dyn_v) 244#define V_dyn_buckets VNET(dyn_buckets) 245#define V_curr_dyn_buckets VNET(curr_dyn_buckets) 246 247static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */ 248#define IPFW_DYN_LOCK_INIT() \ 249 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF) 250#define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx) 251#define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx) 252#define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx) 253#define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED) 254 255static struct mbuf *send_pkt(struct mbuf *, struct ipfw_flow_id *, 256 u_int32_t, u_int32_t, int); 257 258 259/* 260 * Timeouts for various events in handing dynamic rules. 261 */ 262static VNET_DEFINE(u_int32_t, dyn_ack_lifetime); 263static VNET_DEFINE(u_int32_t, dyn_syn_lifetime); 264static VNET_DEFINE(u_int32_t, dyn_fin_lifetime); 265static VNET_DEFINE(u_int32_t, dyn_rst_lifetime); 266static VNET_DEFINE(u_int32_t, dyn_udp_lifetime); 267static VNET_DEFINE(u_int32_t, dyn_short_lifetime); 268 269#define V_dyn_ack_lifetime VNET(dyn_ack_lifetime) 270#define V_dyn_syn_lifetime VNET(dyn_syn_lifetime) 271#define V_dyn_fin_lifetime VNET(dyn_fin_lifetime) 272#define V_dyn_rst_lifetime VNET(dyn_rst_lifetime) 273#define V_dyn_udp_lifetime VNET(dyn_udp_lifetime) 274#define V_dyn_short_lifetime VNET(dyn_short_lifetime) 275 276/* 277 * Keepalives are sent if dyn_keepalive is set. They are sent every 278 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval 279 * seconds of lifetime of a rule. 280 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower 281 * than dyn_keepalive_period. 282 */ 283 284static VNET_DEFINE(u_int32_t, dyn_keepalive_interval); 285static VNET_DEFINE(u_int32_t, dyn_keepalive_period); 286static VNET_DEFINE(u_int32_t, dyn_keepalive); 287 288#define V_dyn_keepalive_interval VNET(dyn_keepalive_interval) 289#define V_dyn_keepalive_period VNET(dyn_keepalive_period) 290#define V_dyn_keepalive VNET(dyn_keepalive) 291 292static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */ 293static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */ 294static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */ 295static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */ 296 297#define V_static_count VNET(static_count) 298#define V_static_len VNET(static_len) 299#define V_dyn_count VNET(dyn_count) 300#define V_dyn_max VNET(dyn_max) 301 302#ifdef SYSCTL_NODE 303SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, 304 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0, 305 "Number of dyn. buckets"); 306SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, 307 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0, 308 "Current Number of dyn. buckets"); 309SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, 310 CTLFLAG_RD, &VNET_NAME(dyn_count), 0, 311 "Number of dyn. rules"); 312SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, 313 CTLFLAG_RW, &VNET_NAME(dyn_max), 0, 314 "Max number of dyn. rules"); 315SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count, 316 CTLFLAG_RD, &VNET_NAME(static_count), 0, 317 "Number of static rules"); 318SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, 319 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0, 320 "Lifetime of dyn. rules for acks"); 321SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, 322 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0, 323 "Lifetime of dyn. rules for syn"); 324SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, 325 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0, 326 "Lifetime of dyn. rules for fin"); 327SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, 328 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0, 329 "Lifetime of dyn. rules for rst"); 330SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, 331 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0, 332 "Lifetime of dyn. rules for UDP"); 333SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, 334 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0, 335 "Lifetime of dyn. rules for other situations"); 336SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, 337 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0, 338 "Enable keepalives for dyn. rules"); 339#endif /* SYSCTL_NODE */ 340 341/* 342 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T 343 * Other macros just cast void * into the appropriate type 344 */ 345#define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl)) 346#define TCP(p) ((struct tcphdr *)(p)) 347#define SCTP(p) ((struct sctphdr *)(p)) 348#define UDP(p) ((struct udphdr *)(p)) 349#define ICMP(p) ((struct icmphdr *)(p)) 350#define ICMP6(p) ((struct icmp6_hdr *)(p)) 351 352static __inline int 353icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd) 354{ 355 int type = icmp->icmp_type; 356 357 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) ); 358} 359 360#define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \ 361 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) ) 362 363static int 364is_icmp_query(struct icmphdr *icmp) 365{ 366 int type = icmp->icmp_type; 367 368 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) ); 369} 370#undef TT 371 372/* 373 * The following checks use two arrays of 8 or 16 bits to store the 374 * bits that we want set or clear, respectively. They are in the 375 * low and high half of cmd->arg1 or cmd->d[0]. 376 * 377 * We scan options and store the bits we find set. We succeed if 378 * 379 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear 380 * 381 * The code is sometimes optimized not to store additional variables. 382 */ 383 384static int 385flags_match(ipfw_insn *cmd, u_int8_t bits) 386{ 387 u_char want_clear; 388 bits = ~bits; 389 390 if ( ((cmd->arg1 & 0xff) & bits) != 0) 391 return 0; /* some bits we want set were clear */ 392 want_clear = (cmd->arg1 >> 8) & 0xff; 393 if ( (want_clear & bits) != want_clear) 394 return 0; /* some bits we want clear were set */ 395 return 1; 396} 397 398static int 399ipopts_match(struct ip *ip, ipfw_insn *cmd) 400{ 401 int optlen, bits = 0; 402 u_char *cp = (u_char *)(ip + 1); 403 int x = (ip->ip_hl << 2) - sizeof (struct ip); 404 405 for (; x > 0; x -= optlen, cp += optlen) { 406 int opt = cp[IPOPT_OPTVAL]; 407 408 if (opt == IPOPT_EOL) 409 break; 410 if (opt == IPOPT_NOP) 411 optlen = 1; 412 else { 413 optlen = cp[IPOPT_OLEN]; 414 if (optlen <= 0 || optlen > x) 415 return 0; /* invalid or truncated */ 416 } 417 switch (opt) { 418 419 default: 420 break; 421 422 case IPOPT_LSRR: 423 bits |= IP_FW_IPOPT_LSRR; 424 break; 425 426 case IPOPT_SSRR: 427 bits |= IP_FW_IPOPT_SSRR; 428 break; 429 430 case IPOPT_RR: 431 bits |= IP_FW_IPOPT_RR; 432 break; 433 434 case IPOPT_TS: 435 bits |= IP_FW_IPOPT_TS; 436 break; 437 } 438 } 439 return (flags_match(cmd, bits)); 440} 441 442static int 443tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd) 444{ 445 int optlen, bits = 0; 446 u_char *cp = (u_char *)(tcp + 1); 447 int x = (tcp->th_off << 2) - sizeof(struct tcphdr); 448 449 for (; x > 0; x -= optlen, cp += optlen) { 450 int opt = cp[0]; 451 if (opt == TCPOPT_EOL) 452 break; 453 if (opt == TCPOPT_NOP) 454 optlen = 1; 455 else { 456 optlen = cp[1]; 457 if (optlen <= 0) 458 break; 459 } 460 461 switch (opt) { 462 463 default: 464 break; 465 466 case TCPOPT_MAXSEG: 467 bits |= IP_FW_TCPOPT_MSS; 468 break; 469 470 case TCPOPT_WINDOW: 471 bits |= IP_FW_TCPOPT_WINDOW; 472 break; 473 474 case TCPOPT_SACK_PERMITTED: 475 case TCPOPT_SACK: 476 bits |= IP_FW_TCPOPT_SACK; 477 break; 478 479 case TCPOPT_TIMESTAMP: 480 bits |= IP_FW_TCPOPT_TS; 481 break; 482 483 } 484 } 485 return (flags_match(cmd, bits)); 486} 487 488static int 489iface_match(struct ifnet *ifp, ipfw_insn_if *cmd) 490{ 491 if (ifp == NULL) /* no iface with this packet, match fails */ 492 return 0; 493 /* Check by name or by IP address */ 494 if (cmd->name[0] != '\0') { /* match by name */ 495 /* Check name */ 496 if (cmd->p.glob) { 497 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0) 498 return(1); 499 } else { 500 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0) 501 return(1); 502 } 503 } else { 504 struct ifaddr *ia; 505 506 if_addr_rlock(ifp); 507 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) { 508 if (ia->ifa_addr->sa_family != AF_INET) 509 continue; 510 if (cmd->p.ip.s_addr == ((struct sockaddr_in *) 511 (ia->ifa_addr))->sin_addr.s_addr) { 512 if_addr_runlock(ifp); 513 return(1); /* match */ 514 } 515 } 516 if_addr_runlock(ifp); 517 } 518 return(0); /* no match, fail ... */ 519} 520 521/* 522 * The verify_path function checks if a route to the src exists and 523 * if it is reachable via ifp (when provided). 524 * 525 * The 'verrevpath' option checks that the interface that an IP packet 526 * arrives on is the same interface that traffic destined for the 527 * packet's source address would be routed out of. The 'versrcreach' 528 * option just checks that the source address is reachable via any route 529 * (except default) in the routing table. These two are a measure to block 530 * forged packets. This is also commonly known as "anti-spoofing" or Unicast 531 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs 532 * is purposely reminiscent of the Cisco IOS command, 533 * 534 * ip verify unicast reverse-path 535 * ip verify unicast source reachable-via any 536 * 537 * which implements the same functionality. But note that syntax is 538 * misleading. The check may be performed on all IP packets whether unicast, 539 * multicast, or broadcast. 540 */ 541static int 542verify_path(struct in_addr src, struct ifnet *ifp, u_int fib) 543{ 544 struct route ro; 545 struct sockaddr_in *dst; 546 547 bzero(&ro, sizeof(ro)); 548 549 dst = (struct sockaddr_in *)&(ro.ro_dst); 550 dst->sin_family = AF_INET; 551 dst->sin_len = sizeof(*dst); 552 dst->sin_addr = src; 553 in_rtalloc_ign(&ro, 0, fib); 554 555 if (ro.ro_rt == NULL) 556 return 0; 557 558 /* 559 * If ifp is provided, check for equality with rtentry. 560 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp, 561 * in order to pass packets injected back by if_simloop(): 562 * if useloopback == 1 routing entry (via lo0) for our own address 563 * may exist, so we need to handle routing assymetry. 564 */ 565 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) { 566 RTFREE(ro.ro_rt); 567 return 0; 568 } 569 570 /* if no ifp provided, check if rtentry is not default route */ 571 if (ifp == NULL && 572 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) { 573 RTFREE(ro.ro_rt); 574 return 0; 575 } 576 577 /* or if this is a blackhole/reject route */ 578 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) { 579 RTFREE(ro.ro_rt); 580 return 0; 581 } 582 583 /* found valid route */ 584 RTFREE(ro.ro_rt); 585 return 1; 586} 587 588#ifdef INET6 589/* 590 * ipv6 specific rules here... 591 */ 592static __inline int 593icmp6type_match (int type, ipfw_insn_u32 *cmd) 594{ 595 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) ); 596} 597 598static int 599flow6id_match( int curr_flow, ipfw_insn_u32 *cmd ) 600{ 601 int i; 602 for (i=0; i <= cmd->o.arg1; ++i ) 603 if (curr_flow == cmd->d[i] ) 604 return 1; 605 return 0; 606} 607 608/* support for IP6_*_ME opcodes */ 609static int 610search_ip6_addr_net (struct in6_addr * ip6_addr) 611{ 612 struct ifnet *mdc; 613 struct ifaddr *mdc2; 614 struct in6_ifaddr *fdm; 615 struct in6_addr copia; 616 617 TAILQ_FOREACH(mdc, &V_ifnet, if_link) { 618 if_addr_rlock(mdc); 619 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) { 620 if (mdc2->ifa_addr->sa_family == AF_INET6) { 621 fdm = (struct in6_ifaddr *)mdc2; 622 copia = fdm->ia_addr.sin6_addr; 623 /* need for leaving scope_id in the sock_addr */ 624 in6_clearscope(&copia); 625 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) { 626 if_addr_runlock(mdc); 627 return 1; 628 } 629 } 630 } 631 if_addr_runlock(mdc); 632 } 633 return 0; 634} 635 636static int 637verify_path6(struct in6_addr *src, struct ifnet *ifp) 638{ 639 struct route_in6 ro; 640 struct sockaddr_in6 *dst; 641 642 bzero(&ro, sizeof(ro)); 643 644 dst = (struct sockaddr_in6 * )&(ro.ro_dst); 645 dst->sin6_family = AF_INET6; 646 dst->sin6_len = sizeof(*dst); 647 dst->sin6_addr = *src; 648 /* XXX MRT 0 for ipv6 at this time */ 649 rtalloc_ign((struct route *)&ro, 0); 650 651 if (ro.ro_rt == NULL) 652 return 0; 653 654 /* 655 * if ifp is provided, check for equality with rtentry 656 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp, 657 * to support the case of sending packets to an address of our own. 658 * (where the former interface is the first argument of if_simloop() 659 * (=ifp), the latter is lo0) 660 */ 661 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) { 662 RTFREE(ro.ro_rt); 663 return 0; 664 } 665 666 /* if no ifp provided, check if rtentry is not default route */ 667 if (ifp == NULL && 668 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) { 669 RTFREE(ro.ro_rt); 670 return 0; 671 } 672 673 /* or if this is a blackhole/reject route */ 674 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) { 675 RTFREE(ro.ro_rt); 676 return 0; 677 } 678 679 /* found valid route */ 680 RTFREE(ro.ro_rt); 681 return 1; 682 683} 684static __inline int 685hash_packet6(struct ipfw_flow_id *id) 686{ 687 u_int32_t i; 688 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^ 689 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^ 690 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^ 691 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^ 692 (id->dst_port) ^ (id->src_port); 693 return i; 694} 695 696static int 697is_icmp6_query(int icmp6_type) 698{ 699 if ((icmp6_type <= ICMP6_MAXTYPE) && 700 (icmp6_type == ICMP6_ECHO_REQUEST || 701 icmp6_type == ICMP6_MEMBERSHIP_QUERY || 702 icmp6_type == ICMP6_WRUREQUEST || 703 icmp6_type == ICMP6_FQDN_QUERY || 704 icmp6_type == ICMP6_NI_QUERY)) 705 return (1); 706 707 return (0); 708} 709 710static void 711send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6) 712{ 713 struct mbuf *m; 714 715 m = args->m; 716 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) { 717 struct tcphdr *tcp; 718 tcp = (struct tcphdr *)((char *)ip6 + hlen); 719 720 if ((tcp->th_flags & TH_RST) == 0) { 721 struct mbuf *m0; 722 m0 = send_pkt(args->m, &(args->f_id), 723 ntohl(tcp->th_seq), ntohl(tcp->th_ack), 724 tcp->th_flags | TH_RST); 725 if (m0 != NULL) 726 ip6_output(m0, NULL, NULL, 0, NULL, NULL, 727 NULL); 728 } 729 m_freem(m); 730 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */ 731#if 0 732 /* 733 * Unlike above, the mbufs need to line up with the ip6 hdr, 734 * as the contents are read. We need to m_adj() the 735 * needed amount. 736 * The mbuf will however be thrown away so we can adjust it. 737 * Remember we did an m_pullup on it already so we 738 * can make some assumptions about contiguousness. 739 */ 740 if (args->L3offset) 741 m_adj(m, args->L3offset); 742#endif 743 icmp6_error(m, ICMP6_DST_UNREACH, code, 0); 744 } else 745 m_freem(m); 746 747 args->m = NULL; 748} 749 750#endif /* INET6 */ 751 752/* counter for ipfw_log(NULL...) */ 753static VNET_DEFINE(u_int64_t, norule_counter); 754#define V_norule_counter VNET(norule_counter) 755 756#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0 757#define SNP(buf) buf, sizeof(buf) 758 759/* 760 * We enter here when we have a rule with O_LOG. 761 * XXX this function alone takes about 2Kbytes of code! 762 */ 763static void 764ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args, 765 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg, 766 struct ip *ip) 767{ 768 struct ether_header *eh = args->eh; 769 char *action; 770 int limit_reached = 0; 771 char action2[40], proto[128], fragment[32]; 772 773 fragment[0] = '\0'; 774 proto[0] = '\0'; 775 776 if (f == NULL) { /* bogus pkt */ 777 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit) 778 return; 779 V_norule_counter++; 780 if (V_norule_counter == V_verbose_limit) 781 limit_reached = V_verbose_limit; 782 action = "Refuse"; 783 } else { /* O_LOG is the first action, find the real one */ 784 ipfw_insn *cmd = ACTION_PTR(f); 785 ipfw_insn_log *l = (ipfw_insn_log *)cmd; 786 787 if (l->max_log != 0 && l->log_left == 0) 788 return; 789 l->log_left--; 790 if (l->log_left == 0) 791 limit_reached = l->max_log; 792 cmd += F_LEN(cmd); /* point to first action */ 793 if (cmd->opcode == O_ALTQ) { 794 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd; 795 796 snprintf(SNPARGS(action2, 0), "Altq %d", 797 altq->qid); 798 cmd += F_LEN(cmd); 799 } 800 if (cmd->opcode == O_PROB) 801 cmd += F_LEN(cmd); 802 803 if (cmd->opcode == O_TAG) 804 cmd += F_LEN(cmd); 805 806 action = action2; 807 switch (cmd->opcode) { 808 case O_DENY: 809 action = "Deny"; 810 break; 811 812 case O_REJECT: 813 if (cmd->arg1==ICMP_REJECT_RST) 814 action = "Reset"; 815 else if (cmd->arg1==ICMP_UNREACH_HOST) 816 action = "Reject"; 817 else 818 snprintf(SNPARGS(action2, 0), "Unreach %d", 819 cmd->arg1); 820 break; 821 822 case O_UNREACH6: 823 if (cmd->arg1==ICMP6_UNREACH_RST) 824 action = "Reset"; 825 else 826 snprintf(SNPARGS(action2, 0), "Unreach %d", 827 cmd->arg1); 828 break; 829 830 case O_ACCEPT: 831 action = "Accept"; 832 break; 833 case O_COUNT: 834 action = "Count"; 835 break; 836 case O_DIVERT: 837 snprintf(SNPARGS(action2, 0), "Divert %d", 838 cmd->arg1); 839 break; 840 case O_TEE: 841 snprintf(SNPARGS(action2, 0), "Tee %d", 842 cmd->arg1); 843 break; 844 case O_SETFIB: 845 snprintf(SNPARGS(action2, 0), "SetFib %d", 846 cmd->arg1); 847 break; 848 case O_SKIPTO: 849 snprintf(SNPARGS(action2, 0), "SkipTo %d", 850 cmd->arg1); 851 break; 852 case O_PIPE: 853 snprintf(SNPARGS(action2, 0), "Pipe %d", 854 cmd->arg1); 855 break; 856 case O_QUEUE: 857 snprintf(SNPARGS(action2, 0), "Queue %d", 858 cmd->arg1); 859 break; 860 case O_FORWARD_IP: { 861 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd; 862 int len; 863 struct in_addr dummyaddr; 864 if (sa->sa.sin_addr.s_addr == INADDR_ANY) 865 dummyaddr.s_addr = htonl(tablearg); 866 else 867 dummyaddr.s_addr = sa->sa.sin_addr.s_addr; 868 869 len = snprintf(SNPARGS(action2, 0), "Forward to %s", 870 inet_ntoa(dummyaddr)); 871 872 if (sa->sa.sin_port) 873 snprintf(SNPARGS(action2, len), ":%d", 874 sa->sa.sin_port); 875 } 876 break; 877 case O_NETGRAPH: 878 snprintf(SNPARGS(action2, 0), "Netgraph %d", 879 cmd->arg1); 880 break; 881 case O_NGTEE: 882 snprintf(SNPARGS(action2, 0), "Ngtee %d", 883 cmd->arg1); 884 break; 885 case O_NAT: 886 action = "Nat"; 887 break; 888 case O_REASS: 889 action = "Reass"; 890 break; 891 default: 892 action = "UNKNOWN"; 893 break; 894 } 895 } 896 897 if (hlen == 0) { /* non-ip */ 898 snprintf(SNPARGS(proto, 0), "MAC"); 899 900 } else { 901 int len; 902#ifdef INET6 903 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2]; 904#else 905 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN]; 906#endif 907 struct icmphdr *icmp; 908 struct tcphdr *tcp; 909 struct udphdr *udp; 910#ifdef INET6 911 struct ip6_hdr *ip6 = NULL; 912 struct icmp6_hdr *icmp6; 913#endif 914 src[0] = '\0'; 915 dst[0] = '\0'; 916#ifdef INET6 917 if (IS_IP6_FLOW_ID(&(args->f_id))) { 918 char ip6buf[INET6_ADDRSTRLEN]; 919 snprintf(src, sizeof(src), "[%s]", 920 ip6_sprintf(ip6buf, &args->f_id.src_ip6)); 921 snprintf(dst, sizeof(dst), "[%s]", 922 ip6_sprintf(ip6buf, &args->f_id.dst_ip6)); 923 924 ip6 = (struct ip6_hdr *)ip; 925 tcp = (struct tcphdr *)(((char *)ip) + hlen); 926 udp = (struct udphdr *)(((char *)ip) + hlen); 927 } else 928#endif 929 { 930 tcp = L3HDR(struct tcphdr, ip); 931 udp = L3HDR(struct udphdr, ip); 932 933 inet_ntoa_r(ip->ip_src, src); 934 inet_ntoa_r(ip->ip_dst, dst); 935 } 936 937 switch (args->f_id.proto) { 938 case IPPROTO_TCP: 939 len = snprintf(SNPARGS(proto, 0), "TCP %s", src); 940 if (offset == 0) 941 snprintf(SNPARGS(proto, len), ":%d %s:%d", 942 ntohs(tcp->th_sport), 943 dst, 944 ntohs(tcp->th_dport)); 945 else 946 snprintf(SNPARGS(proto, len), " %s", dst); 947 break; 948 949 case IPPROTO_UDP: 950 len = snprintf(SNPARGS(proto, 0), "UDP %s", src); 951 if (offset == 0) 952 snprintf(SNPARGS(proto, len), ":%d %s:%d", 953 ntohs(udp->uh_sport), 954 dst, 955 ntohs(udp->uh_dport)); 956 else 957 snprintf(SNPARGS(proto, len), " %s", dst); 958 break; 959 960 case IPPROTO_ICMP: 961 icmp = L3HDR(struct icmphdr, ip); 962 if (offset == 0) 963 len = snprintf(SNPARGS(proto, 0), 964 "ICMP:%u.%u ", 965 icmp->icmp_type, icmp->icmp_code); 966 else 967 len = snprintf(SNPARGS(proto, 0), "ICMP "); 968 len += snprintf(SNPARGS(proto, len), "%s", src); 969 snprintf(SNPARGS(proto, len), " %s", dst); 970 break; 971#ifdef INET6 972 case IPPROTO_ICMPV6: 973 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen); 974 if (offset == 0) 975 len = snprintf(SNPARGS(proto, 0), 976 "ICMPv6:%u.%u ", 977 icmp6->icmp6_type, icmp6->icmp6_code); 978 else 979 len = snprintf(SNPARGS(proto, 0), "ICMPv6 "); 980 len += snprintf(SNPARGS(proto, len), "%s", src); 981 snprintf(SNPARGS(proto, len), " %s", dst); 982 break; 983#endif 984 default: 985 len = snprintf(SNPARGS(proto, 0), "P:%d %s", 986 args->f_id.proto, src); 987 snprintf(SNPARGS(proto, len), " %s", dst); 988 break; 989 } 990 991#ifdef INET6 992 if (IS_IP6_FLOW_ID(&(args->f_id))) { 993 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG)) 994 snprintf(SNPARGS(fragment, 0), 995 " (frag %08x:%d@%d%s)", 996 args->f_id.frag_id6, 997 ntohs(ip6->ip6_plen) - hlen, 998 ntohs(offset & IP6F_OFF_MASK) << 3, 999 (offset & IP6F_MORE_FRAG) ? "+" : ""); 1000 } else 1001#endif 1002 { 1003 int ip_off, ip_len; 1004 if (eh != NULL) { /* layer 2 packets are as on the wire */ 1005 ip_off = ntohs(ip->ip_off); 1006 ip_len = ntohs(ip->ip_len); 1007 } else { 1008 ip_off = ip->ip_off; 1009 ip_len = ip->ip_len; 1010 } 1011 if (ip_off & (IP_MF | IP_OFFMASK)) 1012 snprintf(SNPARGS(fragment, 0), 1013 " (frag %d:%d@%d%s)", 1014 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2), 1015 offset << 3, 1016 (ip_off & IP_MF) ? "+" : ""); 1017 } 1018 } 1019 if (oif || m->m_pkthdr.rcvif) 1020 log(LOG_SECURITY | LOG_INFO, 1021 "ipfw: %d %s %s %s via %s%s\n", 1022 f ? f->rulenum : -1, 1023 action, proto, oif ? "out" : "in", 1024 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname, 1025 fragment); 1026 else 1027 log(LOG_SECURITY | LOG_INFO, 1028 "ipfw: %d %s %s [no if info]%s\n", 1029 f ? f->rulenum : -1, 1030 action, proto, fragment); 1031 if (limit_reached) 1032 log(LOG_SECURITY | LOG_NOTICE, 1033 "ipfw: limit %d reached on entry %d\n", 1034 limit_reached, f ? f->rulenum : -1); 1035} 1036 1037/* 1038 * IMPORTANT: the hash function for dynamic rules must be commutative 1039 * in source and destination (ip,port), because rules are bidirectional 1040 * and we want to find both in the same bucket. 1041 */ 1042static __inline int 1043hash_packet(struct ipfw_flow_id *id) 1044{ 1045 u_int32_t i; 1046 1047#ifdef INET6 1048 if (IS_IP6_FLOW_ID(id)) 1049 i = hash_packet6(id); 1050 else 1051#endif /* INET6 */ 1052 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port); 1053 i &= (V_curr_dyn_buckets - 1); 1054 return i; 1055} 1056 1057static __inline void 1058unlink_dyn_rule_print(struct ipfw_flow_id *id) 1059{ 1060 struct in_addr da; 1061#ifdef INET6 1062 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN]; 1063#else 1064 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN]; 1065#endif 1066 1067#ifdef INET6 1068 if (IS_IP6_FLOW_ID(id)) { 1069 ip6_sprintf(src, &id->src_ip6); 1070 ip6_sprintf(dst, &id->dst_ip6); 1071 } else 1072#endif 1073 { 1074 da.s_addr = htonl(id->src_ip); 1075 inet_ntoa_r(da, src); 1076 da.s_addr = htonl(id->dst_ip); 1077 inet_ntoa_r(da, dst); 1078 } 1079 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n", 1080 src, id->src_port, dst, id->dst_port, V_dyn_count - 1); 1081} 1082 1083/** 1084 * unlink a dynamic rule from a chain. prev is a pointer to 1085 * the previous one, q is a pointer to the rule to delete, 1086 * head is a pointer to the head of the queue. 1087 * Modifies q and potentially also head. 1088 */ 1089#define UNLINK_DYN_RULE(prev, head, q) { \ 1090 ipfw_dyn_rule *old_q = q; \ 1091 \ 1092 /* remove a refcount to the parent */ \ 1093 if (q->dyn_type == O_LIMIT) \ 1094 q->parent->count--; \ 1095 DEB(unlink_dyn_rule_print(&q->id);) \ 1096 if (prev != NULL) \ 1097 prev->next = q = q->next; \ 1098 else \ 1099 head = q = q->next; \ 1100 V_dyn_count--; \ 1101 uma_zfree(ipfw_dyn_rule_zone, old_q); } 1102 1103#define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0) 1104 1105/** 1106 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL. 1107 * 1108 * If keep_me == NULL, rules are deleted even if not expired, 1109 * otherwise only expired rules are removed. 1110 * 1111 * The value of the second parameter is also used to point to identify 1112 * a rule we absolutely do not want to remove (e.g. because we are 1113 * holding a reference to it -- this is the case with O_LIMIT_PARENT 1114 * rules). The pointer is only used for comparison, so any non-null 1115 * value will do. 1116 */ 1117static void 1118remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me) 1119{ 1120 static u_int32_t last_remove = 0; 1121 1122#define FORCE (keep_me == NULL) 1123 1124 ipfw_dyn_rule *prev, *q; 1125 int i, pass = 0, max_pass = 0; 1126 1127 IPFW_DYN_LOCK_ASSERT(); 1128 1129 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0) 1130 return; 1131 /* do not expire more than once per second, it is useless */ 1132 if (!FORCE && last_remove == time_uptime) 1133 return; 1134 last_remove = time_uptime; 1135 1136 /* 1137 * because O_LIMIT refer to parent rules, during the first pass only 1138 * remove child and mark any pending LIMIT_PARENT, and remove 1139 * them in a second pass. 1140 */ 1141next_pass: 1142 for (i = 0 ; i < V_curr_dyn_buckets ; i++) { 1143 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) { 1144 /* 1145 * Logic can become complex here, so we split tests. 1146 */ 1147 if (q == keep_me) 1148 goto next; 1149 if (rule != NULL && rule != q->rule) 1150 goto next; /* not the one we are looking for */ 1151 if (q->dyn_type == O_LIMIT_PARENT) { 1152 /* 1153 * handle parent in the second pass, 1154 * record we need one. 1155 */ 1156 max_pass = 1; 1157 if (pass == 0) 1158 goto next; 1159 if (FORCE && q->count != 0 ) { 1160 /* XXX should not happen! */ 1161 printf("ipfw: OUCH! cannot remove rule," 1162 " count %d\n", q->count); 1163 } 1164 } else { 1165 if (!FORCE && 1166 !TIME_LEQ( q->expire, time_uptime )) 1167 goto next; 1168 } 1169 if (q->dyn_type != O_LIMIT_PARENT || !q->count) { 1170 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q); 1171 continue; 1172 } 1173next: 1174 prev=q; 1175 q=q->next; 1176 } 1177 } 1178 if (pass++ < max_pass) 1179 goto next_pass; 1180} 1181 1182 1183/** 1184 * lookup a dynamic rule. 1185 */ 1186static ipfw_dyn_rule * 1187lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction, 1188 struct tcphdr *tcp) 1189{ 1190 /* 1191 * stateful ipfw extensions. 1192 * Lookup into dynamic session queue 1193 */ 1194#define MATCH_REVERSE 0 1195#define MATCH_FORWARD 1 1196#define MATCH_NONE 2 1197#define MATCH_UNKNOWN 3 1198 int i, dir = MATCH_NONE; 1199 ipfw_dyn_rule *prev, *q=NULL; 1200 1201 IPFW_DYN_LOCK_ASSERT(); 1202 1203 if (V_ipfw_dyn_v == NULL) 1204 goto done; /* not found */ 1205 i = hash_packet( pkt ); 1206 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) { 1207 if (q->dyn_type == O_LIMIT_PARENT && q->count) 1208 goto next; 1209 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */ 1210 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q); 1211 continue; 1212 } 1213 if (pkt->proto == q->id.proto && 1214 q->dyn_type != O_LIMIT_PARENT) { 1215 if (IS_IP6_FLOW_ID(pkt)) { 1216 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1217 &(q->id.src_ip6)) && 1218 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1219 &(q->id.dst_ip6)) && 1220 pkt->src_port == q->id.src_port && 1221 pkt->dst_port == q->id.dst_port ) { 1222 dir = MATCH_FORWARD; 1223 break; 1224 } 1225 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1226 &(q->id.dst_ip6)) && 1227 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1228 &(q->id.src_ip6)) && 1229 pkt->src_port == q->id.dst_port && 1230 pkt->dst_port == q->id.src_port ) { 1231 dir = MATCH_REVERSE; 1232 break; 1233 } 1234 } else { 1235 if (pkt->src_ip == q->id.src_ip && 1236 pkt->dst_ip == q->id.dst_ip && 1237 pkt->src_port == q->id.src_port && 1238 pkt->dst_port == q->id.dst_port ) { 1239 dir = MATCH_FORWARD; 1240 break; 1241 } 1242 if (pkt->src_ip == q->id.dst_ip && 1243 pkt->dst_ip == q->id.src_ip && 1244 pkt->src_port == q->id.dst_port && 1245 pkt->dst_port == q->id.src_port ) { 1246 dir = MATCH_REVERSE; 1247 break; 1248 } 1249 } 1250 } 1251next: 1252 prev = q; 1253 q = q->next; 1254 } 1255 if (q == NULL) 1256 goto done; /* q = NULL, not found */ 1257 1258 if ( prev != NULL) { /* found and not in front */ 1259 prev->next = q->next; 1260 q->next = V_ipfw_dyn_v[i]; 1261 V_ipfw_dyn_v[i] = q; 1262 } 1263 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */ 1264 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST); 1265 1266#define BOTH_SYN (TH_SYN | (TH_SYN << 8)) 1267#define BOTH_FIN (TH_FIN | (TH_FIN << 8)) 1268 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8); 1269 switch (q->state) { 1270 case TH_SYN: /* opening */ 1271 q->expire = time_uptime + V_dyn_syn_lifetime; 1272 break; 1273 1274 case BOTH_SYN: /* move to established */ 1275 case BOTH_SYN | TH_FIN : /* one side tries to close */ 1276 case BOTH_SYN | (TH_FIN << 8) : 1277 if (tcp) { 1278#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0) 1279 u_int32_t ack = ntohl(tcp->th_ack); 1280 if (dir == MATCH_FORWARD) { 1281 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd)) 1282 q->ack_fwd = ack; 1283 else { /* ignore out-of-sequence */ 1284 break; 1285 } 1286 } else { 1287 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev)) 1288 q->ack_rev = ack; 1289 else { /* ignore out-of-sequence */ 1290 break; 1291 } 1292 } 1293 } 1294 q->expire = time_uptime + V_dyn_ack_lifetime; 1295 break; 1296 1297 case BOTH_SYN | BOTH_FIN: /* both sides closed */ 1298 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period) 1299 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1; 1300 q->expire = time_uptime + V_dyn_fin_lifetime; 1301 break; 1302 1303 default: 1304#if 0 1305 /* 1306 * reset or some invalid combination, but can also 1307 * occur if we use keep-state the wrong way. 1308 */ 1309 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0) 1310 printf("invalid state: 0x%x\n", q->state); 1311#endif 1312 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period) 1313 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1; 1314 q->expire = time_uptime + V_dyn_rst_lifetime; 1315 break; 1316 } 1317 } else if (pkt->proto == IPPROTO_UDP) { 1318 q->expire = time_uptime + V_dyn_udp_lifetime; 1319 } else { 1320 /* other protocols */ 1321 q->expire = time_uptime + V_dyn_short_lifetime; 1322 } 1323done: 1324 if (match_direction) 1325 *match_direction = dir; 1326 return q; 1327} 1328 1329static ipfw_dyn_rule * 1330lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction, 1331 struct tcphdr *tcp) 1332{ 1333 ipfw_dyn_rule *q; 1334 1335 IPFW_DYN_LOCK(); 1336 q = lookup_dyn_rule_locked(pkt, match_direction, tcp); 1337 if (q == NULL) 1338 IPFW_DYN_UNLOCK(); 1339 /* NB: return table locked when q is not NULL */ 1340 return q; 1341} 1342 1343static void 1344realloc_dynamic_table(void) 1345{ 1346 IPFW_DYN_LOCK_ASSERT(); 1347 1348 /* 1349 * Try reallocation, make sure we have a power of 2 and do 1350 * not allow more than 64k entries. In case of overflow, 1351 * default to 1024. 1352 */ 1353 1354 if (V_dyn_buckets > 65536) 1355 V_dyn_buckets = 1024; 1356 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */ 1357 V_dyn_buckets = V_curr_dyn_buckets; /* reset */ 1358 return; 1359 } 1360 V_curr_dyn_buckets = V_dyn_buckets; 1361 if (V_ipfw_dyn_v != NULL) 1362 free(V_ipfw_dyn_v, M_IPFW); 1363 for (;;) { 1364 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *), 1365 M_IPFW, M_NOWAIT | M_ZERO); 1366 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2) 1367 break; 1368 V_curr_dyn_buckets /= 2; 1369 } 1370} 1371 1372/** 1373 * Install state of type 'type' for a dynamic session. 1374 * The hash table contains two type of rules: 1375 * - regular rules (O_KEEP_STATE) 1376 * - rules for sessions with limited number of sess per user 1377 * (O_LIMIT). When they are created, the parent is 1378 * increased by 1, and decreased on delete. In this case, 1379 * the third parameter is the parent rule and not the chain. 1380 * - "parent" rules for the above (O_LIMIT_PARENT). 1381 */ 1382static ipfw_dyn_rule * 1383add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule) 1384{ 1385 ipfw_dyn_rule *r; 1386 int i; 1387 1388 IPFW_DYN_LOCK_ASSERT(); 1389 1390 if (V_ipfw_dyn_v == NULL || 1391 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) { 1392 realloc_dynamic_table(); 1393 if (V_ipfw_dyn_v == NULL) 1394 return NULL; /* failed ! */ 1395 } 1396 i = hash_packet(id); 1397 1398 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO); 1399 if (r == NULL) { 1400 printf ("ipfw: sorry cannot allocate state\n"); 1401 return NULL; 1402 } 1403 1404 /* increase refcount on parent, and set pointer */ 1405 if (dyn_type == O_LIMIT) { 1406 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule; 1407 if ( parent->dyn_type != O_LIMIT_PARENT) 1408 panic("invalid parent"); 1409 parent->count++; 1410 r->parent = parent; 1411 rule = parent->rule; 1412 } 1413 1414 r->id = *id; 1415 r->expire = time_uptime + V_dyn_syn_lifetime; 1416 r->rule = rule; 1417 r->dyn_type = dyn_type; 1418 r->pcnt = r->bcnt = 0; 1419 r->count = 0; 1420 1421 r->bucket = i; 1422 r->next = V_ipfw_dyn_v[i]; 1423 V_ipfw_dyn_v[i] = r; 1424 V_dyn_count++; 1425 DEB({ 1426 struct in_addr da; 1427#ifdef INET6 1428 char src[INET6_ADDRSTRLEN]; 1429 char dst[INET6_ADDRSTRLEN]; 1430#else 1431 char src[INET_ADDRSTRLEN]; 1432 char dst[INET_ADDRSTRLEN]; 1433#endif 1434 1435#ifdef INET6 1436 if (IS_IP6_FLOW_ID(&(r->id))) { 1437 ip6_sprintf(src, &r->id.src_ip6); 1438 ip6_sprintf(dst, &r->id.dst_ip6); 1439 } else 1440#endif 1441 { 1442 da.s_addr = htonl(r->id.src_ip); 1443 inet_ntoa_r(da, src); 1444 da.s_addr = htonl(r->id.dst_ip); 1445 inet_ntoa_r(da, dst); 1446 } 1447 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n", 1448 dyn_type, src, r->id.src_port, dst, r->id.dst_port, 1449 V_dyn_count); 1450 }) 1451 return r; 1452} 1453 1454/** 1455 * lookup dynamic parent rule using pkt and rule as search keys. 1456 * If the lookup fails, then install one. 1457 */ 1458static ipfw_dyn_rule * 1459lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule) 1460{ 1461 ipfw_dyn_rule *q; 1462 int i; 1463 1464 IPFW_DYN_LOCK_ASSERT(); 1465 1466 if (V_ipfw_dyn_v) { 1467 int is_v6 = IS_IP6_FLOW_ID(pkt); 1468 i = hash_packet( pkt ); 1469 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next) 1470 if (q->dyn_type == O_LIMIT_PARENT && 1471 rule== q->rule && 1472 pkt->proto == q->id.proto && 1473 pkt->src_port == q->id.src_port && 1474 pkt->dst_port == q->id.dst_port && 1475 ( 1476 (is_v6 && 1477 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1478 &(q->id.src_ip6)) && 1479 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1480 &(q->id.dst_ip6))) || 1481 (!is_v6 && 1482 pkt->src_ip == q->id.src_ip && 1483 pkt->dst_ip == q->id.dst_ip) 1484 ) 1485 ) { 1486 q->expire = time_uptime + V_dyn_short_lifetime; 1487 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);) 1488 return q; 1489 } 1490 } 1491 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule); 1492} 1493 1494/** 1495 * Install dynamic state for rule type cmd->o.opcode 1496 * 1497 * Returns 1 (failure) if state is not installed because of errors or because 1498 * session limitations are enforced. 1499 */ 1500static int 1501install_state(struct ip_fw *rule, ipfw_insn_limit *cmd, 1502 struct ip_fw_args *args, uint32_t tablearg) 1503{ 1504 static int last_log; 1505 ipfw_dyn_rule *q; 1506 struct in_addr da; 1507#ifdef INET6 1508 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2]; 1509#else 1510 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN]; 1511#endif 1512 1513 src[0] = '\0'; 1514 dst[0] = '\0'; 1515 1516 IPFW_DYN_LOCK(); 1517 1518 DEB( 1519#ifdef INET6 1520 if (IS_IP6_FLOW_ID(&(args->f_id))) { 1521 ip6_sprintf(src, &args->f_id.src_ip6); 1522 ip6_sprintf(dst, &args->f_id.dst_ip6); 1523 } else 1524#endif 1525 { 1526 da.s_addr = htonl(args->f_id.src_ip); 1527 inet_ntoa_r(da, src); 1528 da.s_addr = htonl(args->f_id.dst_ip); 1529 inet_ntoa_r(da, dst); 1530 } 1531 printf("ipfw: %s: type %d %s %u -> %s %u\n", 1532 __func__, cmd->o.opcode, src, args->f_id.src_port, 1533 dst, args->f_id.dst_port); 1534 src[0] = '\0'; 1535 dst[0] = '\0'; 1536 ) 1537 1538 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL); 1539 1540 if (q != NULL) { /* should never occur */ 1541 if (last_log != time_uptime) { 1542 last_log = time_uptime; 1543 printf("ipfw: %s: entry already present, done\n", 1544 __func__); 1545 } 1546 IPFW_DYN_UNLOCK(); 1547 return (0); 1548 } 1549 1550 if (V_dyn_count >= V_dyn_max) 1551 /* Run out of slots, try to remove any expired rule. */ 1552 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1); 1553 1554 if (V_dyn_count >= V_dyn_max) { 1555 if (last_log != time_uptime) { 1556 last_log = time_uptime; 1557 printf("ipfw: %s: Too many dynamic rules\n", __func__); 1558 } 1559 IPFW_DYN_UNLOCK(); 1560 return (1); /* cannot install, notify caller */ 1561 } 1562 1563 switch (cmd->o.opcode) { 1564 case O_KEEP_STATE: /* bidir rule */ 1565 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule); 1566 break; 1567 1568 case O_LIMIT: { /* limit number of sessions */ 1569 struct ipfw_flow_id id; 1570 ipfw_dyn_rule *parent; 1571 uint32_t conn_limit; 1572 uint16_t limit_mask = cmd->limit_mask; 1573 1574 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ? 1575 tablearg : cmd->conn_limit; 1576 1577 DEB( 1578 if (cmd->conn_limit == IP_FW_TABLEARG) 1579 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u " 1580 "(tablearg)\n", __func__, conn_limit); 1581 else 1582 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n", 1583 __func__, conn_limit); 1584 ) 1585 1586 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0; 1587 id.proto = args->f_id.proto; 1588 id.addr_type = args->f_id.addr_type; 1589 id.fib = M_GETFIB(args->m); 1590 1591 if (IS_IP6_FLOW_ID (&(args->f_id))) { 1592 if (limit_mask & DYN_SRC_ADDR) 1593 id.src_ip6 = args->f_id.src_ip6; 1594 if (limit_mask & DYN_DST_ADDR) 1595 id.dst_ip6 = args->f_id.dst_ip6; 1596 } else { 1597 if (limit_mask & DYN_SRC_ADDR) 1598 id.src_ip = args->f_id.src_ip; 1599 if (limit_mask & DYN_DST_ADDR) 1600 id.dst_ip = args->f_id.dst_ip; 1601 } 1602 if (limit_mask & DYN_SRC_PORT) 1603 id.src_port = args->f_id.src_port; 1604 if (limit_mask & DYN_DST_PORT) 1605 id.dst_port = args->f_id.dst_port; 1606 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) { 1607 printf("ipfw: %s: add parent failed\n", __func__); 1608 IPFW_DYN_UNLOCK(); 1609 return (1); 1610 } 1611 1612 if (parent->count >= conn_limit) { 1613 /* See if we can remove some expired rule. */ 1614 remove_dyn_rule(rule, parent); 1615 if (parent->count >= conn_limit) { 1616 if (V_fw_verbose && last_log != time_uptime) { 1617 last_log = time_uptime; 1618#ifdef INET6 1619 /* 1620 * XXX IPv6 flows are not 1621 * supported yet. 1622 */ 1623 if (IS_IP6_FLOW_ID(&(args->f_id))) { 1624 char ip6buf[INET6_ADDRSTRLEN]; 1625 snprintf(src, sizeof(src), 1626 "[%s]", ip6_sprintf(ip6buf, 1627 &args->f_id.src_ip6)); 1628 snprintf(dst, sizeof(dst), 1629 "[%s]", ip6_sprintf(ip6buf, 1630 &args->f_id.dst_ip6)); 1631 } else 1632#endif 1633 { 1634 da.s_addr = 1635 htonl(args->f_id.src_ip); 1636 inet_ntoa_r(da, src); 1637 da.s_addr = 1638 htonl(args->f_id.dst_ip); 1639 inet_ntoa_r(da, dst); 1640 } 1641 log(LOG_SECURITY | LOG_DEBUG, 1642 "ipfw: %d %s %s:%u -> %s:%u, %s\n", 1643 parent->rule->rulenum, 1644 "drop session", 1645 src, (args->f_id.src_port), 1646 dst, (args->f_id.dst_port), 1647 "too many entries"); 1648 } 1649 IPFW_DYN_UNLOCK(); 1650 return (1); 1651 } 1652 } 1653 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent); 1654 break; 1655 } 1656 default: 1657 printf("ipfw: %s: unknown dynamic rule type %u\n", 1658 __func__, cmd->o.opcode); 1659 IPFW_DYN_UNLOCK(); 1660 return (1); 1661 } 1662 1663 /* XXX just set lifetime */ 1664 lookup_dyn_rule_locked(&args->f_id, NULL, NULL); 1665 1666 IPFW_DYN_UNLOCK(); 1667 return (0); 1668} 1669 1670/* 1671 * Generate a TCP packet, containing either a RST or a keepalive. 1672 * When flags & TH_RST, we are sending a RST packet, because of a 1673 * "reset" action matched the packet. 1674 * Otherwise we are sending a keepalive, and flags & TH_ 1675 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required 1676 * so that MAC can label the reply appropriately. 1677 */ 1678static struct mbuf * 1679send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq, 1680 u_int32_t ack, int flags) 1681{ 1682 struct mbuf *m; 1683 int len, dir; 1684 struct ip *h = NULL; /* stupid compiler */ 1685#ifdef INET6 1686 struct ip6_hdr *h6 = NULL; 1687#endif 1688 struct tcphdr *th = NULL; 1689 1690 MGETHDR(m, M_DONTWAIT, MT_DATA); 1691 if (m == NULL) 1692 return (NULL); 1693 1694 M_SETFIB(m, id->fib); 1695#ifdef MAC 1696 if (replyto != NULL) 1697 mac_netinet_firewall_reply(replyto, m); 1698 else 1699 mac_netinet_firewall_send(m); 1700#else 1701 (void)replyto; /* don't warn about unused arg */ 1702#endif 1703 1704 switch (id->addr_type) { 1705 case 4: 1706 len = sizeof(struct ip) + sizeof(struct tcphdr); 1707 break; 1708#ifdef INET6 1709 case 6: 1710 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 1711 break; 1712#endif 1713 default: 1714 /* XXX: log me?!? */ 1715 m_freem(m); 1716 return (NULL); 1717 } 1718 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN); 1719 1720 m->m_data += max_linkhdr; 1721 m->m_flags |= M_SKIP_FIREWALL; 1722 m->m_pkthdr.len = m->m_len = len; 1723 m->m_pkthdr.rcvif = NULL; 1724 bzero(m->m_data, len); 1725 1726 switch (id->addr_type) { 1727 case 4: 1728 h = mtod(m, struct ip *); 1729 1730 /* prepare for checksum */ 1731 h->ip_p = IPPROTO_TCP; 1732 h->ip_len = htons(sizeof(struct tcphdr)); 1733 if (dir) { 1734 h->ip_src.s_addr = htonl(id->src_ip); 1735 h->ip_dst.s_addr = htonl(id->dst_ip); 1736 } else { 1737 h->ip_src.s_addr = htonl(id->dst_ip); 1738 h->ip_dst.s_addr = htonl(id->src_ip); 1739 } 1740 1741 th = (struct tcphdr *)(h + 1); 1742 break; 1743#ifdef INET6 1744 case 6: 1745 h6 = mtod(m, struct ip6_hdr *); 1746 1747 /* prepare for checksum */ 1748 h6->ip6_nxt = IPPROTO_TCP; 1749 h6->ip6_plen = htons(sizeof(struct tcphdr)); 1750 if (dir) { 1751 h6->ip6_src = id->src_ip6; 1752 h6->ip6_dst = id->dst_ip6; 1753 } else { 1754 h6->ip6_src = id->dst_ip6; 1755 h6->ip6_dst = id->src_ip6; 1756 } 1757 1758 th = (struct tcphdr *)(h6 + 1); 1759 break; 1760#endif 1761 } 1762 1763 if (dir) { 1764 th->th_sport = htons(id->src_port); 1765 th->th_dport = htons(id->dst_port); 1766 } else { 1767 th->th_sport = htons(id->dst_port); 1768 th->th_dport = htons(id->src_port); 1769 } 1770 th->th_off = sizeof(struct tcphdr) >> 2; 1771 1772 if (flags & TH_RST) { 1773 if (flags & TH_ACK) { 1774 th->th_seq = htonl(ack); 1775 th->th_flags = TH_RST; 1776 } else { 1777 if (flags & TH_SYN) 1778 seq++; 1779 th->th_ack = htonl(seq); 1780 th->th_flags = TH_RST | TH_ACK; 1781 } 1782 } else { 1783 /* 1784 * Keepalive - use caller provided sequence numbers 1785 */ 1786 th->th_seq = htonl(seq); 1787 th->th_ack = htonl(ack); 1788 th->th_flags = TH_ACK; 1789 } 1790 1791 switch (id->addr_type) { 1792 case 4: 1793 th->th_sum = in_cksum(m, len); 1794 1795 /* finish the ip header */ 1796 h->ip_v = 4; 1797 h->ip_hl = sizeof(*h) >> 2; 1798 h->ip_tos = IPTOS_LOWDELAY; 1799 h->ip_off = 0; 1800 h->ip_len = len; 1801 h->ip_ttl = V_ip_defttl; 1802 h->ip_sum = 0; 1803 break; 1804#ifdef INET6 1805 case 6: 1806 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6), 1807 sizeof(struct tcphdr)); 1808 1809 /* finish the ip6 header */ 1810 h6->ip6_vfc |= IPV6_VERSION; 1811 h6->ip6_hlim = IPV6_DEFHLIM; 1812 break; 1813#endif 1814 } 1815 1816 return (m); 1817} 1818 1819/* 1820 * sends a reject message, consuming the mbuf passed as an argument. 1821 */ 1822static void 1823send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip) 1824{ 1825 1826#if 0 1827 /* XXX When ip is not guaranteed to be at mtod() we will 1828 * need to account for this */ 1829 * The mbuf will however be thrown away so we can adjust it. 1830 * Remember we did an m_pullup on it already so we 1831 * can make some assumptions about contiguousness. 1832 */ 1833 if (args->L3offset) 1834 m_adj(m, args->L3offset); 1835#endif 1836 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */ 1837 /* We need the IP header in host order for icmp_error(). */ 1838 if (args->eh != NULL) { 1839 ip->ip_len = ntohs(ip->ip_len); 1840 ip->ip_off = ntohs(ip->ip_off); 1841 } 1842 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0); 1843 } else if (args->f_id.proto == IPPROTO_TCP) { 1844 struct tcphdr *const tcp = 1845 L3HDR(struct tcphdr, mtod(args->m, struct ip *)); 1846 if ( (tcp->th_flags & TH_RST) == 0) { 1847 struct mbuf *m; 1848 m = send_pkt(args->m, &(args->f_id), 1849 ntohl(tcp->th_seq), ntohl(tcp->th_ack), 1850 tcp->th_flags | TH_RST); 1851 if (m != NULL) 1852 ip_output(m, NULL, NULL, 0, NULL, NULL); 1853 } 1854 m_freem(args->m); 1855 } else 1856 m_freem(args->m); 1857 args->m = NULL; 1858} 1859 1860/** 1861 * 1862 * Given an ip_fw *, lookup_next_rule will return a pointer 1863 * to the next rule, which can be either the jump 1864 * target (for skipto instructions) or the next one in the list (in 1865 * all other cases including a missing jump target). 1866 * The result is also written in the "next_rule" field of the rule. 1867 * Backward jumps are not allowed, so start looking from the next 1868 * rule... 1869 * 1870 * This never returns NULL -- in case we do not have an exact match, 1871 * the next rule is returned. When the ruleset is changed, 1872 * pointers are flushed so we are always correct. 1873 */ 1874 1875static struct ip_fw * 1876lookup_next_rule(struct ip_fw *me, u_int32_t tablearg) 1877{ 1878 struct ip_fw *rule = NULL; 1879 ipfw_insn *cmd; 1880 u_int16_t rulenum; 1881 1882 /* look for action, in case it is a skipto */ 1883 cmd = ACTION_PTR(me); 1884 if (cmd->opcode == O_LOG) 1885 cmd += F_LEN(cmd); 1886 if (cmd->opcode == O_ALTQ) 1887 cmd += F_LEN(cmd); 1888 if (cmd->opcode == O_TAG) 1889 cmd += F_LEN(cmd); 1890 if (cmd->opcode == O_SKIPTO ) { 1891 if (tablearg != 0) { 1892 rulenum = (u_int16_t)tablearg; 1893 } else { 1894 rulenum = cmd->arg1; 1895 } 1896 for (rule = me->next; rule ; rule = rule->next) { 1897 if (rule->rulenum >= rulenum) { 1898 break; 1899 } 1900 } 1901 } 1902 if (rule == NULL) /* failure or not a skipto */ 1903 rule = me->next; 1904 me->next_rule = rule; 1905 return rule; 1906} 1907 1908static int 1909add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 1910 uint8_t mlen, uint32_t value) 1911{ 1912 struct radix_node_head *rnh; 1913 struct table_entry *ent; 1914 struct radix_node *rn; 1915 1916 if (tbl >= IPFW_TABLES_MAX) 1917 return (EINVAL); 1918 rnh = ch->tables[tbl]; 1919 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO); 1920 if (ent == NULL) 1921 return (ENOMEM); 1922 ent->value = value; 1923 ent->addr.sin_len = ent->mask.sin_len = 8; 1924 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0); 1925 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr; 1926 IPFW_WLOCK(ch); 1927 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent); 1928 if (rn == NULL) { 1929 IPFW_WUNLOCK(ch); 1930 free(ent, M_IPFW_TBL); 1931 return (EEXIST); 1932 } 1933 IPFW_WUNLOCK(ch); 1934 return (0); 1935} 1936 1937static int 1938del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 1939 uint8_t mlen) 1940{ 1941 struct radix_node_head *rnh; 1942 struct table_entry *ent; 1943 struct sockaddr_in sa, mask; 1944 1945 if (tbl >= IPFW_TABLES_MAX) 1946 return (EINVAL); 1947 rnh = ch->tables[tbl]; 1948 sa.sin_len = mask.sin_len = 8; 1949 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0); 1950 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr; 1951 IPFW_WLOCK(ch); 1952 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh); 1953 if (ent == NULL) { 1954 IPFW_WUNLOCK(ch); 1955 return (ESRCH); 1956 } 1957 IPFW_WUNLOCK(ch); 1958 free(ent, M_IPFW_TBL); 1959 return (0); 1960} 1961 1962static int 1963flush_table_entry(struct radix_node *rn, void *arg) 1964{ 1965 struct radix_node_head * const rnh = arg; 1966 struct table_entry *ent; 1967 1968 ent = (struct table_entry *) 1969 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh); 1970 if (ent != NULL) 1971 free(ent, M_IPFW_TBL); 1972 return (0); 1973} 1974 1975static int 1976flush_table(struct ip_fw_chain *ch, uint16_t tbl) 1977{ 1978 struct radix_node_head *rnh; 1979 1980 IPFW_WLOCK_ASSERT(ch); 1981 1982 if (tbl >= IPFW_TABLES_MAX) 1983 return (EINVAL); 1984 rnh = ch->tables[tbl]; 1985 KASSERT(rnh != NULL, ("NULL IPFW table")); 1986 rnh->rnh_walktree(rnh, flush_table_entry, rnh); 1987 return (0); 1988} 1989 1990static void 1991flush_tables(struct ip_fw_chain *ch) 1992{ 1993 uint16_t tbl; 1994 1995 IPFW_WLOCK_ASSERT(ch); 1996 1997 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++) 1998 flush_table(ch, tbl); 1999} 2000 2001static int 2002init_tables(struct ip_fw_chain *ch) 2003{ 2004 int i; 2005 uint16_t j; 2006 2007 for (i = 0; i < IPFW_TABLES_MAX; i++) { 2008 if (!rn_inithead((void **)&ch->tables[i], 32)) { 2009 for (j = 0; j < i; j++) { 2010 (void) flush_table(ch, j); 2011 } 2012 return (ENOMEM); 2013 } 2014 } 2015 return (0); 2016} 2017 2018static int 2019lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 2020 uint32_t *val) 2021{ 2022 struct radix_node_head *rnh; 2023 struct table_entry *ent; 2024 struct sockaddr_in sa; 2025 2026 if (tbl >= IPFW_TABLES_MAX) 2027 return (0); 2028 rnh = ch->tables[tbl]; 2029 sa.sin_len = 8; 2030 sa.sin_addr.s_addr = addr; 2031 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh)); 2032 if (ent != NULL) { 2033 *val = ent->value; 2034 return (1); 2035 } 2036 return (0); 2037} 2038 2039static int 2040count_table_entry(struct radix_node *rn, void *arg) 2041{ 2042 u_int32_t * const cnt = arg; 2043 2044 (*cnt)++; 2045 return (0); 2046} 2047 2048static int 2049count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt) 2050{ 2051 struct radix_node_head *rnh; 2052 2053 if (tbl >= IPFW_TABLES_MAX) 2054 return (EINVAL); 2055 rnh = ch->tables[tbl]; 2056 *cnt = 0; 2057 rnh->rnh_walktree(rnh, count_table_entry, cnt); 2058 return (0); 2059} 2060 2061static int 2062dump_table_entry(struct radix_node *rn, void *arg) 2063{ 2064 struct table_entry * const n = (struct table_entry *)rn; 2065 ipfw_table * const tbl = arg; 2066 ipfw_table_entry *ent; 2067 2068 if (tbl->cnt == tbl->size) 2069 return (1); 2070 ent = &tbl->ent[tbl->cnt]; 2071 ent->tbl = tbl->tbl; 2072 if (in_nullhost(n->mask.sin_addr)) 2073 ent->masklen = 0; 2074 else 2075 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr)); 2076 ent->addr = n->addr.sin_addr.s_addr; 2077 ent->value = n->value; 2078 tbl->cnt++; 2079 return (0); 2080} 2081 2082static int 2083dump_table(struct ip_fw_chain *ch, ipfw_table *tbl) 2084{ 2085 struct radix_node_head *rnh; 2086 2087 if (tbl->tbl >= IPFW_TABLES_MAX) 2088 return (EINVAL); 2089 rnh = ch->tables[tbl->tbl]; 2090 tbl->cnt = 0; 2091 rnh->rnh_walktree(rnh, dump_table_entry, tbl); 2092 return (0); 2093} 2094 2095static int 2096check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif, 2097 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip, 2098 u_int16_t src_port, struct ucred **uc, int *ugid_lookupp, 2099 struct inpcb *inp) 2100{ 2101 struct inpcbinfo *pi; 2102 int wildcard; 2103 struct inpcb *pcb; 2104 int match; 2105 2106 /* 2107 * Check to see if the UDP or TCP stack supplied us with 2108 * the PCB. If so, rather then holding a lock and looking 2109 * up the PCB, we can use the one that was supplied. 2110 */ 2111 if (inp && *ugid_lookupp == 0) { 2112 INP_LOCK_ASSERT(inp); 2113 if (inp->inp_socket != NULL) { 2114 *uc = crhold(inp->inp_cred); 2115 *ugid_lookupp = 1; 2116 } else 2117 *ugid_lookupp = -1; 2118 } 2119 /* 2120 * If we have already been here and the packet has no 2121 * PCB entry associated with it, then we can safely 2122 * assume that this is a no match. 2123 */ 2124 if (*ugid_lookupp == -1) 2125 return (0); 2126 if (proto == IPPROTO_TCP) { 2127 wildcard = 0; 2128 pi = &V_tcbinfo; 2129 } else if (proto == IPPROTO_UDP) { 2130 wildcard = INPLOOKUP_WILDCARD; 2131 pi = &V_udbinfo; 2132 } else 2133 return 0; 2134 match = 0; 2135 if (*ugid_lookupp == 0) { 2136 INP_INFO_RLOCK(pi); 2137 pcb = (oif) ? 2138 in_pcblookup_hash(pi, 2139 dst_ip, htons(dst_port), 2140 src_ip, htons(src_port), 2141 wildcard, oif) : 2142 in_pcblookup_hash(pi, 2143 src_ip, htons(src_port), 2144 dst_ip, htons(dst_port), 2145 wildcard, NULL); 2146 if (pcb != NULL) { 2147 *uc = crhold(pcb->inp_cred); 2148 *ugid_lookupp = 1; 2149 } 2150 INP_INFO_RUNLOCK(pi); 2151 if (*ugid_lookupp == 0) { 2152 /* 2153 * If the lookup did not yield any results, there 2154 * is no sense in coming back and trying again. So 2155 * we can set lookup to -1 and ensure that we wont 2156 * bother the pcb system again. 2157 */ 2158 *ugid_lookupp = -1; 2159 return (0); 2160 } 2161 } 2162 if (insn->o.opcode == O_UID) 2163 match = ((*uc)->cr_uid == (uid_t)insn->d[0]); 2164 else if (insn->o.opcode == O_GID) 2165 match = groupmember((gid_t)insn->d[0], *uc); 2166 else if (insn->o.opcode == O_JAIL) 2167 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]); 2168 return match; 2169} 2170 2171/* 2172 * The main check routine for the firewall. 2173 * 2174 * All arguments are in args so we can modify them and return them 2175 * back to the caller. 2176 * 2177 * Parameters: 2178 * 2179 * args->m (in/out) The packet; we set to NULL when/if we nuke it. 2180 * Starts with the IP header. 2181 * args->eh (in) Mac header if present, or NULL for layer3 packet. 2182 * args->L3offset Number of bytes bypassed if we came from L2. 2183 * e.g. often sizeof(eh) ** NOTYET ** 2184 * args->oif Outgoing interface, or NULL if packet is incoming. 2185 * The incoming interface is in the mbuf. (in) 2186 * args->divert_rule (in/out) 2187 * Skip up to the first rule past this rule number; 2188 * upon return, non-zero port number for divert or tee. 2189 * 2190 * args->rule Pointer to the last matching rule (in/out) 2191 * args->next_hop Socket we are forwarding to (out). 2192 * args->f_id Addresses grabbed from the packet (out) 2193 * args->cookie a cookie depending on rule action 2194 * 2195 * Return value: 2196 * 2197 * IP_FW_PASS the packet must be accepted 2198 * IP_FW_DENY the packet must be dropped 2199 * IP_FW_DIVERT divert packet, port in m_tag 2200 * IP_FW_TEE tee packet, port in m_tag 2201 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie 2202 * IP_FW_NETGRAPH into netgraph, cookie args->cookie 2203 * 2204 */ 2205int 2206ipfw_chk(struct ip_fw_args *args) 2207{ 2208 2209 /* 2210 * Local variables holding state during the processing of a packet: 2211 * 2212 * IMPORTANT NOTE: to speed up the processing of rules, there 2213 * are some assumption on the values of the variables, which 2214 * are documented here. Should you change them, please check 2215 * the implementation of the various instructions to make sure 2216 * that they still work. 2217 * 2218 * args->eh The MAC header. It is non-null for a layer2 2219 * packet, it is NULL for a layer-3 packet. 2220 * **notyet** 2221 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header. 2222 * 2223 * m | args->m Pointer to the mbuf, as received from the caller. 2224 * It may change if ipfw_chk() does an m_pullup, or if it 2225 * consumes the packet because it calls send_reject(). 2226 * XXX This has to change, so that ipfw_chk() never modifies 2227 * or consumes the buffer. 2228 * ip is the beginning of the ip(4 or 6) header. 2229 * Calculated by adding the L3offset to the start of data. 2230 * (Until we start using L3offset, the packet is 2231 * supposed to start with the ip header). 2232 */ 2233 struct mbuf *m = args->m; 2234 struct ip *ip = mtod(m, struct ip *); 2235 2236 /* 2237 * For rules which contain uid/gid or jail constraints, cache 2238 * a copy of the users credentials after the pcb lookup has been 2239 * executed. This will speed up the processing of rules with 2240 * these types of constraints, as well as decrease contention 2241 * on pcb related locks. 2242 */ 2243 struct ucred *ucred_cache = NULL; 2244 int ucred_lookup = 0; 2245 2246 /* 2247 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG 2248 * associated with a packet input on a divert socket. This 2249 * will allow to distinguish traffic and its direction when 2250 * it originates from a divert socket. 2251 */ 2252 u_int divinput_flags = 0; 2253 2254 /* 2255 * oif | args->oif If NULL, ipfw_chk has been called on the 2256 * inbound path (ether_input, ip_input). 2257 * If non-NULL, ipfw_chk has been called on the outbound path 2258 * (ether_output, ip_output). 2259 */ 2260 struct ifnet *oif = args->oif; 2261 2262 struct ip_fw *f = NULL; /* matching rule */ 2263 int retval = 0; 2264 2265 /* 2266 * hlen The length of the IP header. 2267 */ 2268 u_int hlen = 0; /* hlen >0 means we have an IP pkt */ 2269 2270 /* 2271 * offset The offset of a fragment. offset != 0 means that 2272 * we have a fragment at this offset of an IPv4 packet. 2273 * offset == 0 means that (if this is an IPv4 packet) 2274 * this is the first or only fragment. 2275 * For IPv6 offset == 0 means there is no Fragment Header. 2276 * If offset != 0 for IPv6 always use correct mask to 2277 * get the correct offset because we add IP6F_MORE_FRAG 2278 * to be able to dectect the first fragment which would 2279 * otherwise have offset = 0. 2280 */ 2281 u_short offset = 0; 2282 2283 /* 2284 * Local copies of addresses. They are only valid if we have 2285 * an IP packet. 2286 * 2287 * proto The protocol. Set to 0 for non-ip packets, 2288 * or to the protocol read from the packet otherwise. 2289 * proto != 0 means that we have an IPv4 packet. 2290 * 2291 * src_port, dst_port port numbers, in HOST format. Only 2292 * valid for TCP and UDP packets. 2293 * 2294 * src_ip, dst_ip ip addresses, in NETWORK format. 2295 * Only valid for IPv4 packets. 2296 */ 2297 u_int8_t proto; 2298 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */ 2299 struct in_addr src_ip, dst_ip; /* NOTE: network format */ 2300 u_int16_t ip_len=0; 2301 int pktlen; 2302 u_int16_t etype = 0; /* Host order stored ether type */ 2303 2304 /* 2305 * dyn_dir = MATCH_UNKNOWN when rules unchecked, 2306 * MATCH_NONE when checked and not matched (q = NULL), 2307 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL) 2308 */ 2309 int dyn_dir = MATCH_UNKNOWN; 2310 ipfw_dyn_rule *q = NULL; 2311 struct ip_fw_chain *chain = &V_layer3_chain; 2312 struct m_tag *mtag; 2313 2314 /* 2315 * We store in ulp a pointer to the upper layer protocol header. 2316 * In the ipv4 case this is easy to determine from the header, 2317 * but for ipv6 we might have some additional headers in the middle. 2318 * ulp is NULL if not found. 2319 */ 2320 void *ulp = NULL; /* upper layer protocol pointer. */ 2321 /* XXX ipv6 variables */ 2322 int is_ipv6 = 0; 2323 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */ 2324 /* end of ipv6 variables */ 2325 int is_ipv4 = 0; 2326 2327 int done = 0; /* flag to exit the outer loop */ 2328 2329 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready)) 2330 return (IP_FW_PASS); /* accept */ 2331 2332 dst_ip.s_addr = 0; /* make sure it is initialized */ 2333 src_ip.s_addr = 0; /* make sure it is initialized */ 2334 pktlen = m->m_pkthdr.len; 2335 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */ 2336 proto = args->f_id.proto = 0; /* mark f_id invalid */ 2337 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */ 2338 2339/* 2340 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous, 2341 * then it sets p to point at the offset "len" in the mbuf. WARNING: the 2342 * pointer might become stale after other pullups (but we never use it 2343 * this way). 2344 */ 2345#define PULLUP_TO(_len, p, T) \ 2346do { \ 2347 int x = (_len) + sizeof(T); \ 2348 if ((m)->m_len < x) { \ 2349 args->m = m = m_pullup(m, x); \ 2350 if (m == NULL) \ 2351 goto pullup_failed; \ 2352 } \ 2353 p = (mtod(m, char *) + (_len)); \ 2354} while (0) 2355 2356 /* 2357 * if we have an ether header, 2358 */ 2359 if (args->eh) 2360 etype = ntohs(args->eh->ether_type); 2361 2362 /* Identify IP packets and fill up variables. */ 2363 if (pktlen >= sizeof(struct ip6_hdr) && 2364 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) { 2365 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip; 2366 is_ipv6 = 1; 2367 args->f_id.addr_type = 6; 2368 hlen = sizeof(struct ip6_hdr); 2369 proto = ip6->ip6_nxt; 2370 2371 /* Search extension headers to find upper layer protocols */ 2372 while (ulp == NULL) { 2373 switch (proto) { 2374 case IPPROTO_ICMPV6: 2375 PULLUP_TO(hlen, ulp, struct icmp6_hdr); 2376 args->f_id.flags = ICMP6(ulp)->icmp6_type; 2377 break; 2378 2379 case IPPROTO_TCP: 2380 PULLUP_TO(hlen, ulp, struct tcphdr); 2381 dst_port = TCP(ulp)->th_dport; 2382 src_port = TCP(ulp)->th_sport; 2383 args->f_id.flags = TCP(ulp)->th_flags; 2384 break; 2385 2386 case IPPROTO_SCTP: 2387 PULLUP_TO(hlen, ulp, struct sctphdr); 2388 src_port = SCTP(ulp)->src_port; 2389 dst_port = SCTP(ulp)->dest_port; 2390 break; 2391 2392 case IPPROTO_UDP: 2393 PULLUP_TO(hlen, ulp, struct udphdr); 2394 dst_port = UDP(ulp)->uh_dport; 2395 src_port = UDP(ulp)->uh_sport; 2396 break; 2397 2398 case IPPROTO_HOPOPTS: /* RFC 2460 */ 2399 PULLUP_TO(hlen, ulp, struct ip6_hbh); 2400 ext_hd |= EXT_HOPOPTS; 2401 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3; 2402 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt; 2403 ulp = NULL; 2404 break; 2405 2406 case IPPROTO_ROUTING: /* RFC 2460 */ 2407 PULLUP_TO(hlen, ulp, struct ip6_rthdr); 2408 switch (((struct ip6_rthdr *)ulp)->ip6r_type) { 2409 case 0: 2410 ext_hd |= EXT_RTHDR0; 2411 break; 2412 case 2: 2413 ext_hd |= EXT_RTHDR2; 2414 break; 2415 default: 2416 printf("IPFW2: IPV6 - Unknown Routing " 2417 "Header type(%d)\n", 2418 ((struct ip6_rthdr *)ulp)->ip6r_type); 2419 if (V_fw_deny_unknown_exthdrs) 2420 return (IP_FW_DENY); 2421 break; 2422 } 2423 ext_hd |= EXT_ROUTING; 2424 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3; 2425 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt; 2426 ulp = NULL; 2427 break; 2428 2429 case IPPROTO_FRAGMENT: /* RFC 2460 */ 2430 PULLUP_TO(hlen, ulp, struct ip6_frag); 2431 ext_hd |= EXT_FRAGMENT; 2432 hlen += sizeof (struct ip6_frag); 2433 proto = ((struct ip6_frag *)ulp)->ip6f_nxt; 2434 offset = ((struct ip6_frag *)ulp)->ip6f_offlg & 2435 IP6F_OFF_MASK; 2436 /* Add IP6F_MORE_FRAG for offset of first 2437 * fragment to be != 0. */ 2438 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg & 2439 IP6F_MORE_FRAG; 2440 if (offset == 0) { 2441 printf("IPFW2: IPV6 - Invalid Fragment " 2442 "Header\n"); 2443 if (V_fw_deny_unknown_exthdrs) 2444 return (IP_FW_DENY); 2445 break; 2446 } 2447 args->f_id.frag_id6 = 2448 ntohl(((struct ip6_frag *)ulp)->ip6f_ident); 2449 ulp = NULL; 2450 break; 2451 2452 case IPPROTO_DSTOPTS: /* RFC 2460 */ 2453 PULLUP_TO(hlen, ulp, struct ip6_hbh); 2454 ext_hd |= EXT_DSTOPTS; 2455 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3; 2456 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt; 2457 ulp = NULL; 2458 break; 2459 2460 case IPPROTO_AH: /* RFC 2402 */ 2461 PULLUP_TO(hlen, ulp, struct ip6_ext); 2462 ext_hd |= EXT_AH; 2463 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2; 2464 proto = ((struct ip6_ext *)ulp)->ip6e_nxt; 2465 ulp = NULL; 2466 break; 2467 2468 case IPPROTO_ESP: /* RFC 2406 */ 2469 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */ 2470 /* Anything past Seq# is variable length and 2471 * data past this ext. header is encrypted. */ 2472 ext_hd |= EXT_ESP; 2473 break; 2474 2475 case IPPROTO_NONE: /* RFC 2460 */ 2476 /* 2477 * Packet ends here, and IPv6 header has 2478 * already been pulled up. If ip6e_len!=0 2479 * then octets must be ignored. 2480 */ 2481 ulp = ip; /* non-NULL to get out of loop. */ 2482 break; 2483 2484 case IPPROTO_OSPFIGP: 2485 /* XXX OSPF header check? */ 2486 PULLUP_TO(hlen, ulp, struct ip6_ext); 2487 break; 2488 2489 case IPPROTO_PIM: 2490 /* XXX PIM header check? */ 2491 PULLUP_TO(hlen, ulp, struct pim); 2492 break; 2493 2494 case IPPROTO_CARP: 2495 PULLUP_TO(hlen, ulp, struct carp_header); 2496 if (((struct carp_header *)ulp)->carp_version != 2497 CARP_VERSION) 2498 return (IP_FW_DENY); 2499 if (((struct carp_header *)ulp)->carp_type != 2500 CARP_ADVERTISEMENT) 2501 return (IP_FW_DENY); 2502 break; 2503 2504 case IPPROTO_IPV6: /* RFC 2893 */ 2505 PULLUP_TO(hlen, ulp, struct ip6_hdr); 2506 break; 2507 2508 case IPPROTO_IPV4: /* RFC 2893 */ 2509 PULLUP_TO(hlen, ulp, struct ip); 2510 break; 2511 2512 default: 2513 printf("IPFW2: IPV6 - Unknown Extension " 2514 "Header(%d), ext_hd=%x\n", proto, ext_hd); 2515 if (V_fw_deny_unknown_exthdrs) 2516 return (IP_FW_DENY); 2517 PULLUP_TO(hlen, ulp, struct ip6_ext); 2518 break; 2519 } /*switch */ 2520 } 2521 ip = mtod(m, struct ip *); 2522 ip6 = (struct ip6_hdr *)ip; 2523 args->f_id.src_ip6 = ip6->ip6_src; 2524 args->f_id.dst_ip6 = ip6->ip6_dst; 2525 args->f_id.src_ip = 0; 2526 args->f_id.dst_ip = 0; 2527 args->f_id.flow_id6 = ntohl(ip6->ip6_flow); 2528 } else if (pktlen >= sizeof(struct ip) && 2529 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) { 2530 is_ipv4 = 1; 2531 hlen = ip->ip_hl << 2; 2532 args->f_id.addr_type = 4; 2533 2534 /* 2535 * Collect parameters into local variables for faster matching. 2536 */ 2537 proto = ip->ip_p; 2538 src_ip = ip->ip_src; 2539 dst_ip = ip->ip_dst; 2540 if (args->eh != NULL) { /* layer 2 packets are as on the wire */ 2541 offset = ntohs(ip->ip_off) & IP_OFFMASK; 2542 ip_len = ntohs(ip->ip_len); 2543 } else { 2544 offset = ip->ip_off & IP_OFFMASK; 2545 ip_len = ip->ip_len; 2546 } 2547 pktlen = ip_len < pktlen ? ip_len : pktlen; 2548 2549 if (offset == 0) { 2550 switch (proto) { 2551 case IPPROTO_TCP: 2552 PULLUP_TO(hlen, ulp, struct tcphdr); 2553 dst_port = TCP(ulp)->th_dport; 2554 src_port = TCP(ulp)->th_sport; 2555 args->f_id.flags = TCP(ulp)->th_flags; 2556 break; 2557 2558 case IPPROTO_UDP: 2559 PULLUP_TO(hlen, ulp, struct udphdr); 2560 dst_port = UDP(ulp)->uh_dport; 2561 src_port = UDP(ulp)->uh_sport; 2562 break; 2563 2564 case IPPROTO_ICMP: 2565 PULLUP_TO(hlen, ulp, struct icmphdr); 2566 args->f_id.flags = ICMP(ulp)->icmp_type; 2567 break; 2568 2569 default: 2570 break; 2571 } 2572 } 2573 2574 ip = mtod(m, struct ip *); 2575 args->f_id.src_ip = ntohl(src_ip.s_addr); 2576 args->f_id.dst_ip = ntohl(dst_ip.s_addr); 2577 } 2578#undef PULLUP_TO 2579 if (proto) { /* we may have port numbers, store them */ 2580 args->f_id.proto = proto; 2581 args->f_id.src_port = src_port = ntohs(src_port); 2582 args->f_id.dst_port = dst_port = ntohs(dst_port); 2583 } 2584 2585 IPFW_RLOCK(chain); 2586 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */ 2587 IPFW_RUNLOCK(chain); 2588 return (IP_FW_PASS); /* accept */ 2589 } 2590 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL); 2591 if (args->rule) { 2592 /* 2593 * Packet has already been tagged. Look for the next rule 2594 * to restart processing. Make sure that args->rule still 2595 * exists and not changed. 2596 * If fw_one_pass != 0 then just accept it. 2597 * XXX should not happen here, but optimized out in 2598 * the caller. 2599 */ 2600 if (V_fw_one_pass) { 2601 IPFW_RUNLOCK(chain); 2602 return (IP_FW_PASS); 2603 } 2604 if (chain->id != args->chain_id) { 2605 for (f = chain->rules; f != NULL; f = f->next) 2606 if (f == args->rule && f->id == args->rule_id) 2607 break; 2608 2609 if (f != NULL) 2610 f = f->next_rule; 2611 else 2612 f = ip_fw_default_rule; 2613 } else 2614 f = args->rule->next_rule; 2615 2616 if (f == NULL) 2617 f = lookup_next_rule(args->rule, 0); 2618 } else { 2619 /* 2620 * Find the starting rule. It can be either the first 2621 * one, or the one after divert_rule if asked so. 2622 */ 2623 int skipto = mtag ? divert_cookie(mtag) : 0; 2624 2625 f = chain->rules; 2626 if (args->eh == NULL && skipto != 0) { 2627 if (skipto >= IPFW_DEFAULT_RULE) { 2628 IPFW_RUNLOCK(chain); 2629 return (IP_FW_DENY); /* invalid */ 2630 } 2631 while (f && f->rulenum <= skipto) 2632 f = f->next; 2633 if (f == NULL) { /* drop packet */ 2634 IPFW_RUNLOCK(chain); 2635 return (IP_FW_DENY); 2636 } 2637 } 2638 } 2639 /* reset divert rule to avoid confusion later */ 2640 if (mtag) { 2641 divinput_flags = divert_info(mtag) & 2642 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG); 2643 m_tag_delete(m, mtag); 2644 } 2645 2646 /* 2647 * Now scan the rules, and parse microinstructions for each rule. 2648 * We have two nested loops and an inner switch. Sometimes we 2649 * need to break out of one or both loops, or re-enter one of 2650 * the loops with updated variables. Loop variables are: 2651 * 2652 * f (outer loop) points to the current rule. 2653 * On output it points to the matching rule. 2654 * done (outer loop) is used as a flag to break the loop. 2655 * l (inner loop) residual length of current rule. 2656 * cmd points to the current microinstruction. 2657 * 2658 * We break the inner loop by setting l=0 and possibly 2659 * cmdlen=0 if we don't want to advance cmd. 2660 * We break the outer loop by setting done=1 2661 * We can restart the inner loop by setting l>0 and f, cmd 2662 * as needed. 2663 */ 2664 for (; f; f = f->next) { 2665 ipfw_insn *cmd; 2666 uint32_t tablearg = 0; 2667 int l, cmdlen, skip_or; /* skip rest of OR block */ 2668 2669/* again: */ 2670 if (V_set_disable & (1 << f->set) ) 2671 continue; 2672 2673 skip_or = 0; 2674 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ; 2675 l -= cmdlen, cmd += cmdlen) { 2676 int match; 2677 2678 /* 2679 * check_body is a jump target used when we find a 2680 * CHECK_STATE, and need to jump to the body of 2681 * the target rule. 2682 */ 2683 2684/* check_body: */ 2685 cmdlen = F_LEN(cmd); 2686 /* 2687 * An OR block (insn_1 || .. || insn_n) has the 2688 * F_OR bit set in all but the last instruction. 2689 * The first match will set "skip_or", and cause 2690 * the following instructions to be skipped until 2691 * past the one with the F_OR bit clear. 2692 */ 2693 if (skip_or) { /* skip this instruction */ 2694 if ((cmd->len & F_OR) == 0) 2695 skip_or = 0; /* next one is good */ 2696 continue; 2697 } 2698 match = 0; /* set to 1 if we succeed */ 2699 2700 switch (cmd->opcode) { 2701 /* 2702 * The first set of opcodes compares the packet's 2703 * fields with some pattern, setting 'match' if a 2704 * match is found. At the end of the loop there is 2705 * logic to deal with F_NOT and F_OR flags associated 2706 * with the opcode. 2707 */ 2708 case O_NOP: 2709 match = 1; 2710 break; 2711 2712 case O_FORWARD_MAC: 2713 printf("ipfw: opcode %d unimplemented\n", 2714 cmd->opcode); 2715 break; 2716 2717 case O_GID: 2718 case O_UID: 2719 case O_JAIL: 2720 /* 2721 * We only check offset == 0 && proto != 0, 2722 * as this ensures that we have a 2723 * packet with the ports info. 2724 */ 2725 if (offset!=0) 2726 break; 2727 if (is_ipv6) /* XXX to be fixed later */ 2728 break; 2729 if (proto == IPPROTO_TCP || 2730 proto == IPPROTO_UDP) 2731 match = check_uidgid( 2732 (ipfw_insn_u32 *)cmd, 2733 proto, oif, 2734 dst_ip, dst_port, 2735 src_ip, src_port, &ucred_cache, 2736 &ucred_lookup, args->inp); 2737 break; 2738 2739 case O_RECV: 2740 match = iface_match(m->m_pkthdr.rcvif, 2741 (ipfw_insn_if *)cmd); 2742 break; 2743 2744 case O_XMIT: 2745 match = iface_match(oif, (ipfw_insn_if *)cmd); 2746 break; 2747 2748 case O_VIA: 2749 match = iface_match(oif ? oif : 2750 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd); 2751 break; 2752 2753 case O_MACADDR2: 2754 if (args->eh != NULL) { /* have MAC header */ 2755 u_int32_t *want = (u_int32_t *) 2756 ((ipfw_insn_mac *)cmd)->addr; 2757 u_int32_t *mask = (u_int32_t *) 2758 ((ipfw_insn_mac *)cmd)->mask; 2759 u_int32_t *hdr = (u_int32_t *)args->eh; 2760 2761 match = 2762 ( want[0] == (hdr[0] & mask[0]) && 2763 want[1] == (hdr[1] & mask[1]) && 2764 want[2] == (hdr[2] & mask[2]) ); 2765 } 2766 break; 2767 2768 case O_MAC_TYPE: 2769 if (args->eh != NULL) { 2770 u_int16_t *p = 2771 ((ipfw_insn_u16 *)cmd)->ports; 2772 int i; 2773 2774 for (i = cmdlen - 1; !match && i>0; 2775 i--, p += 2) 2776 match = (etype >= p[0] && 2777 etype <= p[1]); 2778 } 2779 break; 2780 2781 case O_FRAG: 2782 match = (offset != 0); 2783 break; 2784 2785 case O_IN: /* "out" is "not in" */ 2786 match = (oif == NULL); 2787 break; 2788 2789 case O_LAYER2: 2790 match = (args->eh != NULL); 2791 break; 2792 2793 case O_DIVERTED: 2794 match = (cmd->arg1 & 1 && divinput_flags & 2795 IP_FW_DIVERT_LOOPBACK_FLAG) || 2796 (cmd->arg1 & 2 && divinput_flags & 2797 IP_FW_DIVERT_OUTPUT_FLAG); 2798 break; 2799 2800 case O_PROTO: 2801 /* 2802 * We do not allow an arg of 0 so the 2803 * check of "proto" only suffices. 2804 */ 2805 match = (proto == cmd->arg1); 2806 break; 2807 2808 case O_IP_SRC: 2809 match = is_ipv4 && 2810 (((ipfw_insn_ip *)cmd)->addr.s_addr == 2811 src_ip.s_addr); 2812 break; 2813 2814 case O_IP_SRC_LOOKUP: 2815 case O_IP_DST_LOOKUP: 2816 if (is_ipv4) { 2817 uint32_t a = 2818 (cmd->opcode == O_IP_DST_LOOKUP) ? 2819 dst_ip.s_addr : src_ip.s_addr; 2820 uint32_t v = 0; 2821 2822 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) { 2823 /* generic lookup */ 2824 v = ((ipfw_insn_u32 *)cmd)->d[1]; 2825 if (v == 0) 2826 a = dst_ip.s_addr; 2827 else if (v == 1) 2828 a = src_ip.s_addr; 2829 else if (offset != 0) 2830 break; 2831 else if (proto != IPPROTO_TCP && 2832 proto != IPPROTO_UDP) 2833 break; 2834 else if (v == 2) 2835 a = dst_port; 2836 else if (v == 3) 2837 a = src_port; 2838 else if (v == 4 || v == 5) { 2839 check_uidgid( 2840 (ipfw_insn_u32 *)cmd, 2841 proto, oif, 2842 dst_ip, dst_port, 2843 src_ip, src_port, &ucred_cache, 2844 &ucred_lookup, args->inp); 2845 if (v == 4 /* O_UID */) 2846 a = ucred_cache->cr_uid; 2847 else if (v == 5 /* O_JAIL */) 2848 a = ucred_cache->cr_prison->pr_id; 2849 } else 2850 break; 2851 } 2852 match = lookup_table(chain, cmd->arg1, a, 2853 &v); 2854 if (!match) 2855 break; 2856 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) 2857 match = 2858 ((ipfw_insn_u32 *)cmd)->d[0] == v; 2859 else 2860 tablearg = v; 2861 } 2862 break; 2863 2864 case O_IP_SRC_MASK: 2865 case O_IP_DST_MASK: 2866 if (is_ipv4) { 2867 uint32_t a = 2868 (cmd->opcode == O_IP_DST_MASK) ? 2869 dst_ip.s_addr : src_ip.s_addr; 2870 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d; 2871 int i = cmdlen-1; 2872 2873 for (; !match && i>0; i-= 2, p+= 2) 2874 match = (p[0] == (a & p[1])); 2875 } 2876 break; 2877 2878 case O_IP_SRC_ME: 2879 if (is_ipv4) { 2880 struct ifnet *tif; 2881 2882 INADDR_TO_IFP(src_ip, tif); 2883 match = (tif != NULL); 2884 } 2885 break; 2886 2887 case O_IP_DST_SET: 2888 case O_IP_SRC_SET: 2889 if (is_ipv4) { 2890 u_int32_t *d = (u_int32_t *)(cmd+1); 2891 u_int32_t addr = 2892 cmd->opcode == O_IP_DST_SET ? 2893 args->f_id.dst_ip : 2894 args->f_id.src_ip; 2895 2896 if (addr < d[0]) 2897 break; 2898 addr -= d[0]; /* subtract base */ 2899 match = (addr < cmd->arg1) && 2900 ( d[ 1 + (addr>>5)] & 2901 (1<<(addr & 0x1f)) ); 2902 } 2903 break; 2904 2905 case O_IP_DST: 2906 match = is_ipv4 && 2907 (((ipfw_insn_ip *)cmd)->addr.s_addr == 2908 dst_ip.s_addr); 2909 break; 2910 2911 case O_IP_DST_ME: 2912 if (is_ipv4) { 2913 struct ifnet *tif; 2914 2915 INADDR_TO_IFP(dst_ip, tif); 2916 match = (tif != NULL); 2917 } 2918 break; 2919 2920 case O_IP_SRCPORT: 2921 case O_IP_DSTPORT: 2922 /* 2923 * offset == 0 && proto != 0 is enough 2924 * to guarantee that we have a 2925 * packet with port info. 2926 */ 2927 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP) 2928 && offset == 0) { 2929 u_int16_t x = 2930 (cmd->opcode == O_IP_SRCPORT) ? 2931 src_port : dst_port ; 2932 u_int16_t *p = 2933 ((ipfw_insn_u16 *)cmd)->ports; 2934 int i; 2935 2936 for (i = cmdlen - 1; !match && i>0; 2937 i--, p += 2) 2938 match = (x>=p[0] && x<=p[1]); 2939 } 2940 break; 2941 2942 case O_ICMPTYPE: 2943 match = (offset == 0 && proto==IPPROTO_ICMP && 2944 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) ); 2945 break; 2946 2947#ifdef INET6 2948 case O_ICMP6TYPE: 2949 match = is_ipv6 && offset == 0 && 2950 proto==IPPROTO_ICMPV6 && 2951 icmp6type_match( 2952 ICMP6(ulp)->icmp6_type, 2953 (ipfw_insn_u32 *)cmd); 2954 break; 2955#endif /* INET6 */ 2956 2957 case O_IPOPT: 2958 match = (is_ipv4 && 2959 ipopts_match(ip, cmd) ); 2960 break; 2961 2962 case O_IPVER: 2963 match = (is_ipv4 && 2964 cmd->arg1 == ip->ip_v); 2965 break; 2966 2967 case O_IPID: 2968 case O_IPLEN: 2969 case O_IPTTL: 2970 if (is_ipv4) { /* only for IP packets */ 2971 uint16_t x; 2972 uint16_t *p; 2973 int i; 2974 2975 if (cmd->opcode == O_IPLEN) 2976 x = ip_len; 2977 else if (cmd->opcode == O_IPTTL) 2978 x = ip->ip_ttl; 2979 else /* must be IPID */ 2980 x = ntohs(ip->ip_id); 2981 if (cmdlen == 1) { 2982 match = (cmd->arg1 == x); 2983 break; 2984 } 2985 /* otherwise we have ranges */ 2986 p = ((ipfw_insn_u16 *)cmd)->ports; 2987 i = cmdlen - 1; 2988 for (; !match && i>0; i--, p += 2) 2989 match = (x >= p[0] && x <= p[1]); 2990 } 2991 break; 2992 2993 case O_IPPRECEDENCE: 2994 match = (is_ipv4 && 2995 (cmd->arg1 == (ip->ip_tos & 0xe0)) ); 2996 break; 2997 2998 case O_IPTOS: 2999 match = (is_ipv4 && 3000 flags_match(cmd, ip->ip_tos)); 3001 break; 3002 3003 case O_TCPDATALEN: 3004 if (proto == IPPROTO_TCP && offset == 0) { 3005 struct tcphdr *tcp; 3006 uint16_t x; 3007 uint16_t *p; 3008 int i; 3009 3010 tcp = TCP(ulp); 3011 x = ip_len - 3012 ((ip->ip_hl + tcp->th_off) << 2); 3013 if (cmdlen == 1) { 3014 match = (cmd->arg1 == x); 3015 break; 3016 } 3017 /* otherwise we have ranges */ 3018 p = ((ipfw_insn_u16 *)cmd)->ports; 3019 i = cmdlen - 1; 3020 for (; !match && i>0; i--, p += 2) 3021 match = (x >= p[0] && x <= p[1]); 3022 } 3023 break; 3024 3025 case O_TCPFLAGS: 3026 match = (proto == IPPROTO_TCP && offset == 0 && 3027 flags_match(cmd, TCP(ulp)->th_flags)); 3028 break; 3029 3030 case O_TCPOPTS: 3031 match = (proto == IPPROTO_TCP && offset == 0 && 3032 tcpopts_match(TCP(ulp), cmd)); 3033 break; 3034 3035 case O_TCPSEQ: 3036 match = (proto == IPPROTO_TCP && offset == 0 && 3037 ((ipfw_insn_u32 *)cmd)->d[0] == 3038 TCP(ulp)->th_seq); 3039 break; 3040 3041 case O_TCPACK: 3042 match = (proto == IPPROTO_TCP && offset == 0 && 3043 ((ipfw_insn_u32 *)cmd)->d[0] == 3044 TCP(ulp)->th_ack); 3045 break; 3046 3047 case O_TCPWIN: 3048 match = (proto == IPPROTO_TCP && offset == 0 && 3049 cmd->arg1 == TCP(ulp)->th_win); 3050 break; 3051 3052 case O_ESTAB: 3053 /* reject packets which have SYN only */ 3054 /* XXX should i also check for TH_ACK ? */ 3055 match = (proto == IPPROTO_TCP && offset == 0 && 3056 (TCP(ulp)->th_flags & 3057 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN); 3058 break; 3059 3060 case O_ALTQ: { 3061 struct pf_mtag *at; 3062 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd; 3063 3064 match = 1; 3065 at = pf_find_mtag(m); 3066 if (at != NULL && at->qid != 0) 3067 break; 3068 at = pf_get_mtag(m); 3069 if (at == NULL) { 3070 /* 3071 * Let the packet fall back to the 3072 * default ALTQ. 3073 */ 3074 break; 3075 } 3076 at->qid = altq->qid; 3077 if (is_ipv4) 3078 at->af = AF_INET; 3079 else 3080 at->af = AF_LINK; 3081 at->hdr = ip; 3082 break; 3083 } 3084 3085 case O_LOG: 3086 if (V_fw_verbose) 3087 ipfw_log(f, hlen, args, m, 3088 oif, offset, tablearg, ip); 3089 match = 1; 3090 break; 3091 3092 case O_PROB: 3093 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]); 3094 break; 3095 3096 case O_VERREVPATH: 3097 /* Outgoing packets automatically pass/match */ 3098 match = ((oif != NULL) || 3099 (m->m_pkthdr.rcvif == NULL) || 3100 ( 3101#ifdef INET6 3102 is_ipv6 ? 3103 verify_path6(&(args->f_id.src_ip6), 3104 m->m_pkthdr.rcvif) : 3105#endif 3106 verify_path(src_ip, m->m_pkthdr.rcvif, 3107 args->f_id.fib))); 3108 break; 3109 3110 case O_VERSRCREACH: 3111 /* Outgoing packets automatically pass/match */ 3112 match = (hlen > 0 && ((oif != NULL) || 3113#ifdef INET6 3114 is_ipv6 ? 3115 verify_path6(&(args->f_id.src_ip6), 3116 NULL) : 3117#endif 3118 verify_path(src_ip, NULL, args->f_id.fib))); 3119 break; 3120 3121 case O_ANTISPOOF: 3122 /* Outgoing packets automatically pass/match */ 3123 if (oif == NULL && hlen > 0 && 3124 ( (is_ipv4 && in_localaddr(src_ip)) 3125#ifdef INET6 3126 || (is_ipv6 && 3127 in6_localaddr(&(args->f_id.src_ip6))) 3128#endif 3129 )) 3130 match = 3131#ifdef INET6 3132 is_ipv6 ? verify_path6( 3133 &(args->f_id.src_ip6), 3134 m->m_pkthdr.rcvif) : 3135#endif 3136 verify_path(src_ip, 3137 m->m_pkthdr.rcvif, 3138 args->f_id.fib); 3139 else 3140 match = 1; 3141 break; 3142 3143 case O_IPSEC: 3144#ifdef IPSEC 3145 match = (m_tag_find(m, 3146 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL); 3147#endif 3148 /* otherwise no match */ 3149 break; 3150 3151#ifdef INET6 3152 case O_IP6_SRC: 3153 match = is_ipv6 && 3154 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6, 3155 &((ipfw_insn_ip6 *)cmd)->addr6); 3156 break; 3157 3158 case O_IP6_DST: 3159 match = is_ipv6 && 3160 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6, 3161 &((ipfw_insn_ip6 *)cmd)->addr6); 3162 break; 3163 case O_IP6_SRC_MASK: 3164 case O_IP6_DST_MASK: 3165 if (is_ipv6) { 3166 int i = cmdlen - 1; 3167 struct in6_addr p; 3168 struct in6_addr *d = 3169 &((ipfw_insn_ip6 *)cmd)->addr6; 3170 3171 for (; !match && i > 0; d += 2, 3172 i -= F_INSN_SIZE(struct in6_addr) 3173 * 2) { 3174 p = (cmd->opcode == 3175 O_IP6_SRC_MASK) ? 3176 args->f_id.src_ip6: 3177 args->f_id.dst_ip6; 3178 APPLY_MASK(&p, &d[1]); 3179 match = 3180 IN6_ARE_ADDR_EQUAL(&d[0], 3181 &p); 3182 } 3183 } 3184 break; 3185 3186 case O_IP6_SRC_ME: 3187 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6); 3188 break; 3189 3190 case O_IP6_DST_ME: 3191 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6); 3192 break; 3193 3194 case O_FLOW6ID: 3195 match = is_ipv6 && 3196 flow6id_match(args->f_id.flow_id6, 3197 (ipfw_insn_u32 *) cmd); 3198 break; 3199 3200 case O_EXT_HDR: 3201 match = is_ipv6 && 3202 (ext_hd & ((ipfw_insn *) cmd)->arg1); 3203 break; 3204 3205 case O_IP6: 3206 match = is_ipv6; 3207 break; 3208#endif 3209 3210 case O_IP4: 3211 match = is_ipv4; 3212 break; 3213 3214 case O_TAG: { 3215 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ? 3216 tablearg : cmd->arg1; 3217 3218 /* Packet is already tagged with this tag? */ 3219 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL); 3220 3221 /* We have `untag' action when F_NOT flag is 3222 * present. And we must remove this mtag from 3223 * mbuf and reset `match' to zero (`match' will 3224 * be inversed later). 3225 * Otherwise we should allocate new mtag and 3226 * push it into mbuf. 3227 */ 3228 if (cmd->len & F_NOT) { /* `untag' action */ 3229 if (mtag != NULL) 3230 m_tag_delete(m, mtag); 3231 } else if (mtag == NULL) { 3232 if ((mtag = m_tag_alloc(MTAG_IPFW, 3233 tag, 0, M_NOWAIT)) != NULL) 3234 m_tag_prepend(m, mtag); 3235 } 3236 match = (cmd->len & F_NOT) ? 0: 1; 3237 break; 3238 } 3239 3240 case O_FIB: /* try match the specified fib */ 3241 if (args->f_id.fib == cmd->arg1) 3242 match = 1; 3243 break; 3244 3245 case O_TAGGED: { 3246 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ? 3247 tablearg : cmd->arg1; 3248 3249 if (cmdlen == 1) { 3250 match = m_tag_locate(m, MTAG_IPFW, 3251 tag, NULL) != NULL; 3252 break; 3253 } 3254 3255 /* we have ranges */ 3256 for (mtag = m_tag_first(m); 3257 mtag != NULL && !match; 3258 mtag = m_tag_next(m, mtag)) { 3259 uint16_t *p; 3260 int i; 3261 3262 if (mtag->m_tag_cookie != MTAG_IPFW) 3263 continue; 3264 3265 p = ((ipfw_insn_u16 *)cmd)->ports; 3266 i = cmdlen - 1; 3267 for(; !match && i > 0; i--, p += 2) 3268 match = 3269 mtag->m_tag_id >= p[0] && 3270 mtag->m_tag_id <= p[1]; 3271 } 3272 break; 3273 } 3274 3275 /* 3276 * The second set of opcodes represents 'actions', 3277 * i.e. the terminal part of a rule once the packet 3278 * matches all previous patterns. 3279 * Typically there is only one action for each rule, 3280 * and the opcode is stored at the end of the rule 3281 * (but there are exceptions -- see below). 3282 * 3283 * In general, here we set retval and terminate the 3284 * outer loop (would be a 'break 3' in some language, 3285 * but we need to set l=0, done=1) 3286 * 3287 * Exceptions: 3288 * O_COUNT and O_SKIPTO actions: 3289 * instead of terminating, we jump to the next rule 3290 * (setting l=0), or to the SKIPTO target (by 3291 * setting f, cmd and l as needed), respectively. 3292 * 3293 * O_TAG, O_LOG and O_ALTQ action parameters: 3294 * perform some action and set match = 1; 3295 * 3296 * O_LIMIT and O_KEEP_STATE: these opcodes are 3297 * not real 'actions', and are stored right 3298 * before the 'action' part of the rule. 3299 * These opcodes try to install an entry in the 3300 * state tables; if successful, we continue with 3301 * the next opcode (match=1; break;), otherwise 3302 * the packet must be dropped (set retval, 3303 * break loops with l=0, done=1) 3304 * 3305 * O_PROBE_STATE and O_CHECK_STATE: these opcodes 3306 * cause a lookup of the state table, and a jump 3307 * to the 'action' part of the parent rule 3308 * if an entry is found, or 3309 * (CHECK_STATE only) a jump to the next rule if 3310 * the entry is not found. 3311 * The result of the lookup is cached so that 3312 * further instances of these opcodes become NOPs. 3313 * The jump to the next rule is done by setting 3314 * l=0, cmdlen=0. 3315 */ 3316 case O_LIMIT: 3317 case O_KEEP_STATE: 3318 if (install_state(f, 3319 (ipfw_insn_limit *)cmd, args, tablearg)) { 3320 /* error or limit violation */ 3321 retval = IP_FW_DENY; 3322 l = 0; /* exit inner loop */ 3323 done = 1; /* exit outer loop */ 3324 } 3325 match = 1; 3326 break; 3327 3328 case O_PROBE_STATE: 3329 case O_CHECK_STATE: 3330 /* 3331 * dynamic rules are checked at the first 3332 * keep-state or check-state occurrence, 3333 * with the result being stored in dyn_dir. 3334 * The compiler introduces a PROBE_STATE 3335 * instruction for us when we have a 3336 * KEEP_STATE (because PROBE_STATE needs 3337 * to be run first). 3338 */ 3339 if (dyn_dir == MATCH_UNKNOWN && 3340 (q = lookup_dyn_rule(&args->f_id, 3341 &dyn_dir, proto == IPPROTO_TCP ? 3342 TCP(ulp) : NULL)) 3343 != NULL) { 3344 /* 3345 * Found dynamic entry, update stats 3346 * and jump to the 'action' part of 3347 * the parent rule by setting 3348 * f, cmd, l and clearing cmdlen. 3349 */ 3350 q->pcnt++; 3351 q->bcnt += pktlen; 3352 f = q->rule; 3353 cmd = ACTION_PTR(f); 3354 l = f->cmd_len - f->act_ofs; 3355 IPFW_DYN_UNLOCK(); 3356 cmdlen = 0; 3357 match = 1; 3358 break; 3359 } 3360 /* 3361 * Dynamic entry not found. If CHECK_STATE, 3362 * skip to next rule, if PROBE_STATE just 3363 * ignore and continue with next opcode. 3364 */ 3365 if (cmd->opcode == O_CHECK_STATE) 3366 l = 0; /* exit inner loop */ 3367 match = 1; 3368 break; 3369 3370 case O_ACCEPT: 3371 retval = 0; /* accept */ 3372 l = 0; /* exit inner loop */ 3373 done = 1; /* exit outer loop */ 3374 break; 3375 3376 case O_PIPE: 3377 case O_QUEUE: 3378 args->rule = f; /* report matching rule */ 3379 args->rule_id = f->id; 3380 args->chain_id = chain->id; 3381 if (cmd->arg1 == IP_FW_TABLEARG) 3382 args->cookie = tablearg; 3383 else 3384 args->cookie = cmd->arg1; 3385 retval = IP_FW_DUMMYNET; 3386 l = 0; /* exit inner loop */ 3387 done = 1; /* exit outer loop */ 3388 break; 3389 3390 case O_DIVERT: 3391 case O_TEE: 3392 if (args->eh) /* not on layer 2 */ 3393 break; 3394 /* otherwise this is terminal */ 3395 l = 0; /* exit inner loop */ 3396 done = 1; /* exit outer loop */ 3397 mtag = m_tag_get(PACKET_TAG_DIVERT, 3398 sizeof(struct divert_tag), 3399 M_NOWAIT); 3400 if (mtag == NULL) { 3401 retval = IP_FW_DENY; 3402 } else { 3403 struct divert_tag *dt; 3404 dt = (struct divert_tag *)(mtag+1); 3405 dt->cookie = f->rulenum; 3406 if (cmd->arg1 == IP_FW_TABLEARG) 3407 dt->info = tablearg; 3408 else 3409 dt->info = cmd->arg1; 3410 m_tag_prepend(m, mtag); 3411 retval = (cmd->opcode == O_DIVERT) ? 3412 IP_FW_DIVERT : IP_FW_TEE; 3413 } 3414 break; 3415 3416 case O_COUNT: 3417 case O_SKIPTO: 3418 f->pcnt++; /* update stats */ 3419 f->bcnt += pktlen; 3420 f->timestamp = time_uptime; 3421 if (cmd->opcode == O_COUNT) { 3422 l = 0; /* exit inner loop */ 3423 break; 3424 } 3425 /* handle skipto */ 3426 if (cmd->arg1 == IP_FW_TABLEARG) { 3427 f = lookup_next_rule(f, tablearg); 3428 } else { 3429 if (f->next_rule == NULL) 3430 lookup_next_rule(f, 0); 3431 f = f->next_rule; 3432 } 3433 /* 3434 * Skip disabled rules, and 3435 * re-enter the inner loop 3436 * with the correct f, l and cmd. 3437 * Also clear cmdlen and skip_or 3438 */ 3439 while (f && (V_set_disable & (1 << f->set))) 3440 f = f->next; 3441 if (f) { /* found a valid rule */ 3442 l = f->cmd_len; 3443 cmd = f->cmd; 3444 } else { 3445 l = 0; /* exit inner loop */ 3446 } 3447 match = 1; 3448 cmdlen = 0; 3449 skip_or = 0; 3450 break; 3451 3452 case O_REJECT: 3453 /* 3454 * Drop the packet and send a reject notice 3455 * if the packet is not ICMP (or is an ICMP 3456 * query), and it is not multicast/broadcast. 3457 */ 3458 if (hlen > 0 && is_ipv4 && offset == 0 && 3459 (proto != IPPROTO_ICMP || 3460 is_icmp_query(ICMP(ulp))) && 3461 !(m->m_flags & (M_BCAST|M_MCAST)) && 3462 !IN_MULTICAST(ntohl(dst_ip.s_addr))) { 3463 send_reject(args, cmd->arg1, ip_len, ip); 3464 m = args->m; 3465 } 3466 /* FALLTHROUGH */ 3467#ifdef INET6 3468 case O_UNREACH6: 3469 if (hlen > 0 && is_ipv6 && 3470 ((offset & IP6F_OFF_MASK) == 0) && 3471 (proto != IPPROTO_ICMPV6 || 3472 (is_icmp6_query(args->f_id.flags) == 1)) && 3473 !(m->m_flags & (M_BCAST|M_MCAST)) && 3474 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) { 3475 send_reject6( 3476 args, cmd->arg1, hlen, 3477 (struct ip6_hdr *)ip); 3478 m = args->m; 3479 } 3480 /* FALLTHROUGH */ 3481#endif 3482 case O_DENY: 3483 retval = IP_FW_DENY; 3484 l = 0; /* exit inner loop */ 3485 done = 1; /* exit outer loop */ 3486 break; 3487 3488 case O_FORWARD_IP: 3489 if (args->eh) /* not valid on layer2 pkts */ 3490 break; 3491 if (!q || dyn_dir == MATCH_FORWARD) { 3492 struct sockaddr_in *sa; 3493 sa = &(((ipfw_insn_sa *)cmd)->sa); 3494 if (sa->sin_addr.s_addr == INADDR_ANY) { 3495 bcopy(sa, &args->hopstore, 3496 sizeof(*sa)); 3497 args->hopstore.sin_addr.s_addr = 3498 htonl(tablearg); 3499 args->next_hop = &args->hopstore; 3500 } else { 3501 args->next_hop = sa; 3502 } 3503 } 3504 retval = IP_FW_PASS; 3505 l = 0; /* exit inner loop */ 3506 done = 1; /* exit outer loop */ 3507 break; 3508 3509 case O_NETGRAPH: 3510 case O_NGTEE: 3511 args->rule = f; /* report matching rule */ 3512 args->rule_id = f->id; 3513 args->chain_id = chain->id; 3514 if (cmd->arg1 == IP_FW_TABLEARG) 3515 args->cookie = tablearg; 3516 else 3517 args->cookie = cmd->arg1; 3518 retval = (cmd->opcode == O_NETGRAPH) ? 3519 IP_FW_NETGRAPH : IP_FW_NGTEE; 3520 l = 0; /* exit inner loop */ 3521 done = 1; /* exit outer loop */ 3522 break; 3523 3524 case O_SETFIB: 3525 f->pcnt++; /* update stats */ 3526 f->bcnt += pktlen; 3527 f->timestamp = time_uptime; 3528 M_SETFIB(m, cmd->arg1); 3529 args->f_id.fib = cmd->arg1; 3530 l = 0; /* exit inner loop */ 3531 break; 3532 3533 case O_NAT: 3534 if (!IPFW_NAT_LOADED) { 3535 retval = IP_FW_DENY; 3536 } else { 3537 struct cfg_nat *t; 3538 int nat_id; 3539 3540 args->rule = f; /* Report matching rule. */ 3541 args->rule_id = f->id; 3542 args->chain_id = chain->id; 3543 t = ((ipfw_insn_nat *)cmd)->nat; 3544 if (t == NULL) { 3545 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ? 3546 tablearg : cmd->arg1; 3547 LOOKUP_NAT(V_layer3_chain, nat_id, t); 3548 if (t == NULL) { 3549 retval = IP_FW_DENY; 3550 l = 0; /* exit inner loop */ 3551 done = 1; /* exit outer loop */ 3552 break; 3553 } 3554 if (cmd->arg1 != IP_FW_TABLEARG) 3555 ((ipfw_insn_nat *)cmd)->nat = t; 3556 } 3557 retval = ipfw_nat_ptr(args, t, m); 3558 } 3559 l = 0; /* exit inner loop */ 3560 done = 1; /* exit outer loop */ 3561 break; 3562 3563 case O_REASS: { 3564 int ip_off; 3565 3566 f->pcnt++; 3567 f->bcnt += pktlen; 3568 l = 0; /* in any case exit inner loop */ 3569 3570 ip_off = (args->eh != NULL) ? 3571 ntohs(ip->ip_off) : ip->ip_off; 3572 /* if not fragmented, go to next rule */ 3573 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0) 3574 break; 3575 /* 3576 * ip_reass() expects len & off in host 3577 * byte order: fix them in case we come 3578 * from layer2. 3579 */ 3580 if (args->eh != NULL) { 3581 ip->ip_len = ntohs(ip->ip_len); 3582 ip->ip_off = ntohs(ip->ip_off); 3583 } 3584 3585 args->m = m = ip_reass(m); 3586 3587 /* 3588 * IP header checksum fixup after 3589 * reassembly and leave header 3590 * in network byte order. 3591 */ 3592 if (m == NULL) { /* fragment got swallowed */ 3593 retval = IP_FW_DENY; 3594 } else { /* good, packet complete */ 3595 int hlen; 3596 3597 ip = mtod(m, struct ip *); 3598 hlen = ip->ip_hl << 2; 3599 /* revert len & off for layer2 pkts */ 3600 if (args->eh != NULL) 3601 ip->ip_len = htons(ip->ip_len); 3602 ip->ip_sum = 0; 3603 if (hlen == sizeof(struct ip)) 3604 ip->ip_sum = in_cksum_hdr(ip); 3605 else 3606 ip->ip_sum = in_cksum(m, hlen); 3607 retval = IP_FW_REASS; 3608 args->rule = f; 3609 args->rule_id = f->id; 3610 args->chain_id = chain->id; 3611 } 3612 done = 1; /* exit outer loop */ 3613 break; 3614 } 3615 3616 default: 3617 panic("-- unknown opcode %d\n", cmd->opcode); 3618 } /* end of switch() on opcodes */ 3619 /* 3620 * if we get here with l=0, then match is irrelevant. 3621 */ 3622 3623 if (cmd->len & F_NOT) 3624 match = !match; 3625 3626 if (match) { 3627 if (cmd->len & F_OR) 3628 skip_or = 1; 3629 } else { 3630 if (!(cmd->len & F_OR)) /* not an OR block, */ 3631 break; /* try next rule */ 3632 } 3633 3634 } /* end of inner loop, scan opcodes */ 3635 3636 if (done) 3637 break; 3638 3639/* next_rule:; */ /* try next rule */ 3640 3641 } /* end of outer for, scan rules */ 3642 3643 if (done) { 3644 /* Update statistics */ 3645 f->pcnt++; 3646 f->bcnt += pktlen; 3647 f->timestamp = time_uptime; 3648 } else { 3649 retval = IP_FW_DENY; 3650 printf("ipfw: ouch!, skip past end of rules, denying packet\n"); 3651 } 3652 IPFW_RUNLOCK(chain); 3653 if (ucred_cache != NULL) 3654 crfree(ucred_cache); 3655 return (retval); 3656 3657pullup_failed: 3658 if (V_fw_verbose) 3659 printf("ipfw: pullup failed\n"); 3660 return (IP_FW_DENY); 3661} 3662 3663/* 3664 * When a rule is added/deleted, clear the next_rule pointers in all rules. 3665 * These will be reconstructed on the fly as packets are matched. 3666 */ 3667static void 3668flush_rule_ptrs(struct ip_fw_chain *chain) 3669{ 3670 struct ip_fw *rule; 3671 3672 IPFW_WLOCK_ASSERT(chain); 3673 3674 chain->id++; 3675 3676 for (rule = chain->rules; rule; rule = rule->next) 3677 rule->next_rule = NULL; 3678} 3679 3680/* 3681 * Add a new rule to the list. Copy the rule into a malloc'ed area, then 3682 * possibly create a rule number and add the rule to the list. 3683 * Update the rule_number in the input struct so the caller knows it as well. 3684 */ 3685static int 3686add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule) 3687{ 3688 struct ip_fw *rule, *f, *prev; 3689 int l = RULESIZE(input_rule); 3690 3691 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE) 3692 return (EINVAL); 3693 3694 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO); 3695 if (rule == NULL) 3696 return (ENOSPC); 3697 3698 bcopy(input_rule, rule, l); 3699 3700 rule->next = NULL; 3701 rule->next_rule = NULL; 3702 3703 rule->pcnt = 0; 3704 rule->bcnt = 0; 3705 rule->timestamp = 0; 3706 3707 IPFW_WLOCK(chain); 3708 3709 if (chain->rules == NULL) { /* default rule */ 3710 chain->rules = rule; 3711 rule->id = ++chain->id; 3712 goto done; 3713 } 3714 3715 /* 3716 * If rulenum is 0, find highest numbered rule before the 3717 * default rule, and add autoinc_step 3718 */ 3719 if (V_autoinc_step < 1) 3720 V_autoinc_step = 1; 3721 else if (V_autoinc_step > 1000) 3722 V_autoinc_step = 1000; 3723 if (rule->rulenum == 0) { 3724 /* 3725 * locate the highest numbered rule before default 3726 */ 3727 for (f = chain->rules; f; f = f->next) { 3728 if (f->rulenum == IPFW_DEFAULT_RULE) 3729 break; 3730 rule->rulenum = f->rulenum; 3731 } 3732 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step) 3733 rule->rulenum += V_autoinc_step; 3734 input_rule->rulenum = rule->rulenum; 3735 } 3736 3737 /* 3738 * Now insert the new rule in the right place in the sorted list. 3739 */ 3740 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) { 3741 if (f->rulenum > rule->rulenum) { /* found the location */ 3742 if (prev) { 3743 rule->next = f; 3744 prev->next = rule; 3745 } else { /* head insert */ 3746 rule->next = chain->rules; 3747 chain->rules = rule; 3748 } 3749 break; 3750 } 3751 } 3752 flush_rule_ptrs(chain); 3753 /* chain->id incremented inside flush_rule_ptrs() */ 3754 rule->id = chain->id; 3755done: 3756 V_static_count++; 3757 V_static_len += l; 3758 IPFW_WUNLOCK(chain); 3759 DEB(printf("ipfw: installed rule %d, static count now %d\n", 3760 rule->rulenum, V_static_count);) 3761 return (0); 3762} 3763 3764/** 3765 * Remove a static rule (including derived * dynamic rules) 3766 * and place it on the ``reap list'' for later reclamation. 3767 * The caller is in charge of clearing rule pointers to avoid 3768 * dangling pointers. 3769 * @return a pointer to the next entry. 3770 * Arguments are not checked, so they better be correct. 3771 */ 3772static struct ip_fw * 3773remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, 3774 struct ip_fw *prev) 3775{ 3776 struct ip_fw *n; 3777 int l = RULESIZE(rule); 3778 3779 IPFW_WLOCK_ASSERT(chain); 3780 3781 n = rule->next; 3782 IPFW_DYN_LOCK(); 3783 remove_dyn_rule(rule, NULL /* force removal */); 3784 IPFW_DYN_UNLOCK(); 3785 if (prev == NULL) 3786 chain->rules = n; 3787 else 3788 prev->next = n; 3789 V_static_count--; 3790 V_static_len -= l; 3791 3792 rule->next = chain->reap; 3793 chain->reap = rule; 3794 3795 return n; 3796} 3797 3798/* 3799 * Reclaim storage associated with a list of rules. This is 3800 * typically the list created using remove_rule. 3801 * A NULL pointer on input is handled correctly. 3802 */ 3803static void 3804reap_rules(struct ip_fw *head) 3805{ 3806 struct ip_fw *rule; 3807 3808 while ((rule = head) != NULL) { 3809 head = head->next; 3810 free(rule, M_IPFW); 3811 } 3812} 3813 3814/* 3815 * Remove all rules from a chain (except rules in set RESVD_SET 3816 * unless kill_default = 1). The caller is responsible for 3817 * reclaiming storage for the rules left in chain->reap. 3818 */ 3819static void 3820free_chain(struct ip_fw_chain *chain, int kill_default) 3821{ 3822 struct ip_fw *prev, *rule; 3823 3824 IPFW_WLOCK_ASSERT(chain); 3825 3826 chain->reap = NULL; 3827 flush_rule_ptrs(chain); /* more efficient to do outside the loop */ 3828 for (prev = NULL, rule = chain->rules; rule ; ) 3829 if (kill_default || rule->set != RESVD_SET) 3830 rule = remove_rule(chain, rule, prev); 3831 else { 3832 prev = rule; 3833 rule = rule->next; 3834 } 3835} 3836 3837/** 3838 * Remove all rules with given number, and also do set manipulation. 3839 * Assumes chain != NULL && *chain != NULL. 3840 * 3841 * The argument is an u_int32_t. The low 16 bit are the rule or set number, 3842 * the next 8 bits are the new set, the top 8 bits are the command: 3843 * 3844 * 0 delete rules with given number 3845 * 1 delete rules with given set number 3846 * 2 move rules with given number to new set 3847 * 3 move rules with given set number to new set 3848 * 4 swap sets with given numbers 3849 * 5 delete rules with given number and with given set number 3850 */ 3851static int 3852del_entry(struct ip_fw_chain *chain, u_int32_t arg) 3853{ 3854 struct ip_fw *prev = NULL, *rule; 3855 u_int16_t rulenum; /* rule or old_set */ 3856 u_int8_t cmd, new_set; 3857 3858 rulenum = arg & 0xffff; 3859 cmd = (arg >> 24) & 0xff; 3860 new_set = (arg >> 16) & 0xff; 3861 3862 if (cmd > 5 || new_set > RESVD_SET) 3863 return EINVAL; 3864 if (cmd == 0 || cmd == 2 || cmd == 5) { 3865 if (rulenum >= IPFW_DEFAULT_RULE) 3866 return EINVAL; 3867 } else { 3868 if (rulenum > RESVD_SET) /* old_set */ 3869 return EINVAL; 3870 } 3871 3872 IPFW_WLOCK(chain); 3873 rule = chain->rules; /* common starting point */ 3874 chain->reap = NULL; /* prepare for deletions */ 3875 switch (cmd) { 3876 case 0: /* delete rules with given number */ 3877 /* 3878 * locate first rule to delete 3879 */ 3880 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next) 3881 ; 3882 if (rule->rulenum != rulenum) { 3883 IPFW_WUNLOCK(chain); 3884 return EINVAL; 3885 } 3886 3887 /* 3888 * flush pointers outside the loop, then delete all matching 3889 * rules. prev remains the same throughout the cycle. 3890 */ 3891 flush_rule_ptrs(chain); 3892 while (rule->rulenum == rulenum) 3893 rule = remove_rule(chain, rule, prev); 3894 break; 3895 3896 case 1: /* delete all rules with given set number */ 3897 flush_rule_ptrs(chain); 3898 while (rule->rulenum < IPFW_DEFAULT_RULE) { 3899 if (rule->set == rulenum) 3900 rule = remove_rule(chain, rule, prev); 3901 else { 3902 prev = rule; 3903 rule = rule->next; 3904 } 3905 } 3906 break; 3907 3908 case 2: /* move rules with given number to new set */ 3909 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3910 if (rule->rulenum == rulenum) 3911 rule->set = new_set; 3912 break; 3913 3914 case 3: /* move rules with given set number to new set */ 3915 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3916 if (rule->set == rulenum) 3917 rule->set = new_set; 3918 break; 3919 3920 case 4: /* swap two sets */ 3921 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3922 if (rule->set == rulenum) 3923 rule->set = new_set; 3924 else if (rule->set == new_set) 3925 rule->set = rulenum; 3926 break; 3927 3928 case 5: /* delete rules with given number and with given set number. 3929 * rulenum - given rule number; 3930 * new_set - given set number. 3931 */ 3932 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next) 3933 ; 3934 if (rule->rulenum != rulenum) { 3935 IPFW_WUNLOCK(chain); 3936 return (EINVAL); 3937 } 3938 flush_rule_ptrs(chain); 3939 while (rule->rulenum == rulenum) { 3940 if (rule->set == new_set) 3941 rule = remove_rule(chain, rule, prev); 3942 else { 3943 prev = rule; 3944 rule = rule->next; 3945 } 3946 } 3947 } 3948 /* 3949 * Look for rules to reclaim. We grab the list before 3950 * releasing the lock then reclaim them w/o the lock to 3951 * avoid a LOR with dummynet. 3952 */ 3953 rule = chain->reap; 3954 IPFW_WUNLOCK(chain); 3955 reap_rules(rule); 3956 return 0; 3957} 3958 3959/* 3960 * Clear counters for a specific rule. 3961 * The enclosing "table" is assumed locked. 3962 */ 3963static void 3964clear_counters(struct ip_fw *rule, int log_only) 3965{ 3966 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule); 3967 3968 if (log_only == 0) { 3969 rule->bcnt = rule->pcnt = 0; 3970 rule->timestamp = 0; 3971 } 3972 if (l->o.opcode == O_LOG) 3973 l->log_left = l->max_log; 3974} 3975 3976/** 3977 * Reset some or all counters on firewall rules. 3978 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number, 3979 * the next 8 bits are the set number, the top 8 bits are the command: 3980 * 0 work with rules from all set's; 3981 * 1 work with rules only from specified set. 3982 * Specified rule number is zero if we want to clear all entries. 3983 * log_only is 1 if we only want to reset logs, zero otherwise. 3984 */ 3985static int 3986zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only) 3987{ 3988 struct ip_fw *rule; 3989 char *msg; 3990 3991 uint16_t rulenum = arg & 0xffff; 3992 uint8_t set = (arg >> 16) & 0xff; 3993 uint8_t cmd = (arg >> 24) & 0xff; 3994 3995 if (cmd > 1) 3996 return (EINVAL); 3997 if (cmd == 1 && set > RESVD_SET) 3998 return (EINVAL); 3999 4000 IPFW_WLOCK(chain); 4001 if (rulenum == 0) { 4002 V_norule_counter = 0; 4003 for (rule = chain->rules; rule; rule = rule->next) { 4004 /* Skip rules from another set. */ 4005 if (cmd == 1 && rule->set != set) 4006 continue; 4007 clear_counters(rule, log_only); 4008 } 4009 msg = log_only ? "All logging counts reset" : 4010 "Accounting cleared"; 4011 } else { 4012 int cleared = 0; 4013 /* 4014 * We can have multiple rules with the same number, so we 4015 * need to clear them all. 4016 */ 4017 for (rule = chain->rules; rule; rule = rule->next) 4018 if (rule->rulenum == rulenum) { 4019 while (rule && rule->rulenum == rulenum) { 4020 if (cmd == 0 || rule->set == set) 4021 clear_counters(rule, log_only); 4022 rule = rule->next; 4023 } 4024 cleared = 1; 4025 break; 4026 } 4027 if (!cleared) { /* we did not find any matching rules */ 4028 IPFW_WUNLOCK(chain); 4029 return (EINVAL); 4030 } 4031 msg = log_only ? "logging count reset" : "cleared"; 4032 } 4033 IPFW_WUNLOCK(chain); 4034 4035 if (V_fw_verbose) { 4036 int lev = LOG_SECURITY | LOG_NOTICE; 4037 4038 if (rulenum) 4039 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg); 4040 else 4041 log(lev, "ipfw: %s.\n", msg); 4042 } 4043 return (0); 4044} 4045 4046/* 4047 * Check validity of the structure before insert. 4048 * Fortunately rules are simple, so this mostly need to check rule sizes. 4049 */ 4050static int 4051check_ipfw_struct(struct ip_fw *rule, int size) 4052{ 4053 int l, cmdlen = 0; 4054 int have_action=0; 4055 ipfw_insn *cmd; 4056 4057 if (size < sizeof(*rule)) { 4058 printf("ipfw: rule too short\n"); 4059 return (EINVAL); 4060 } 4061 /* first, check for valid size */ 4062 l = RULESIZE(rule); 4063 if (l != size) { 4064 printf("ipfw: size mismatch (have %d want %d)\n", size, l); 4065 return (EINVAL); 4066 } 4067 if (rule->act_ofs >= rule->cmd_len) { 4068 printf("ipfw: bogus action offset (%u > %u)\n", 4069 rule->act_ofs, rule->cmd_len - 1); 4070 return (EINVAL); 4071 } 4072 /* 4073 * Now go for the individual checks. Very simple ones, basically only 4074 * instruction sizes. 4075 */ 4076 for (l = rule->cmd_len, cmd = rule->cmd ; 4077 l > 0 ; l -= cmdlen, cmd += cmdlen) { 4078 cmdlen = F_LEN(cmd); 4079 if (cmdlen > l) { 4080 printf("ipfw: opcode %d size truncated\n", 4081 cmd->opcode); 4082 return EINVAL; 4083 } 4084 DEB(printf("ipfw: opcode %d\n", cmd->opcode);) 4085 switch (cmd->opcode) { 4086 case O_PROBE_STATE: 4087 case O_KEEP_STATE: 4088 case O_PROTO: 4089 case O_IP_SRC_ME: 4090 case O_IP_DST_ME: 4091 case O_LAYER2: 4092 case O_IN: 4093 case O_FRAG: 4094 case O_DIVERTED: 4095 case O_IPOPT: 4096 case O_IPTOS: 4097 case O_IPPRECEDENCE: 4098 case O_IPVER: 4099 case O_TCPWIN: 4100 case O_TCPFLAGS: 4101 case O_TCPOPTS: 4102 case O_ESTAB: 4103 case O_VERREVPATH: 4104 case O_VERSRCREACH: 4105 case O_ANTISPOOF: 4106 case O_IPSEC: 4107#ifdef INET6 4108 case O_IP6_SRC_ME: 4109 case O_IP6_DST_ME: 4110 case O_EXT_HDR: 4111 case O_IP6: 4112#endif 4113 case O_IP4: 4114 case O_TAG: 4115 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4116 goto bad_size; 4117 break; 4118 4119 case O_FIB: 4120 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4121 goto bad_size; 4122 if (cmd->arg1 >= rt_numfibs) { 4123 printf("ipfw: invalid fib number %d\n", 4124 cmd->arg1); 4125 return EINVAL; 4126 } 4127 break; 4128 4129 case O_SETFIB: 4130 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4131 goto bad_size; 4132 if (cmd->arg1 >= rt_numfibs) { 4133 printf("ipfw: invalid fib number %d\n", 4134 cmd->arg1); 4135 return EINVAL; 4136 } 4137 goto check_action; 4138 4139 case O_UID: 4140 case O_GID: 4141 case O_JAIL: 4142 case O_IP_SRC: 4143 case O_IP_DST: 4144 case O_TCPSEQ: 4145 case O_TCPACK: 4146 case O_PROB: 4147 case O_ICMPTYPE: 4148 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32)) 4149 goto bad_size; 4150 break; 4151 4152 case O_LIMIT: 4153 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit)) 4154 goto bad_size; 4155 break; 4156 4157 case O_LOG: 4158 if (cmdlen != F_INSN_SIZE(ipfw_insn_log)) 4159 goto bad_size; 4160 4161 ((ipfw_insn_log *)cmd)->log_left = 4162 ((ipfw_insn_log *)cmd)->max_log; 4163 4164 break; 4165 4166 case O_IP_SRC_MASK: 4167 case O_IP_DST_MASK: 4168 /* only odd command lengths */ 4169 if ( !(cmdlen & 1) || cmdlen > 31) 4170 goto bad_size; 4171 break; 4172 4173 case O_IP_SRC_SET: 4174 case O_IP_DST_SET: 4175 if (cmd->arg1 == 0 || cmd->arg1 > 256) { 4176 printf("ipfw: invalid set size %d\n", 4177 cmd->arg1); 4178 return EINVAL; 4179 } 4180 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 4181 (cmd->arg1+31)/32 ) 4182 goto bad_size; 4183 break; 4184 4185 case O_IP_SRC_LOOKUP: 4186 case O_IP_DST_LOOKUP: 4187 if (cmd->arg1 >= IPFW_TABLES_MAX) { 4188 printf("ipfw: invalid table number %d\n", 4189 cmd->arg1); 4190 return (EINVAL); 4191 } 4192 if (cmdlen != F_INSN_SIZE(ipfw_insn) && 4193 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 && 4194 cmdlen != F_INSN_SIZE(ipfw_insn_u32)) 4195 goto bad_size; 4196 break; 4197 4198 case O_MACADDR2: 4199 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac)) 4200 goto bad_size; 4201 break; 4202 4203 case O_NOP: 4204 case O_IPID: 4205 case O_IPTTL: 4206 case O_IPLEN: 4207 case O_TCPDATALEN: 4208 case O_TAGGED: 4209 if (cmdlen < 1 || cmdlen > 31) 4210 goto bad_size; 4211 break; 4212 4213 case O_MAC_TYPE: 4214 case O_IP_SRCPORT: 4215 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */ 4216 if (cmdlen < 2 || cmdlen > 31) 4217 goto bad_size; 4218 break; 4219 4220 case O_RECV: 4221 case O_XMIT: 4222 case O_VIA: 4223 if (cmdlen != F_INSN_SIZE(ipfw_insn_if)) 4224 goto bad_size; 4225 break; 4226 4227 case O_ALTQ: 4228 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq)) 4229 goto bad_size; 4230 break; 4231 4232 case O_PIPE: 4233 case O_QUEUE: 4234 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4235 goto bad_size; 4236 goto check_action; 4237 4238 case O_FORWARD_IP: 4239#ifdef IPFIREWALL_FORWARD 4240 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) 4241 goto bad_size; 4242 goto check_action; 4243#else 4244 return EINVAL; 4245#endif 4246 4247 case O_DIVERT: 4248 case O_TEE: 4249 if (ip_divert_ptr == NULL) 4250 return EINVAL; 4251 else 4252 goto check_size; 4253 case O_NETGRAPH: 4254 case O_NGTEE: 4255 if (!NG_IPFW_LOADED) 4256 return EINVAL; 4257 else 4258 goto check_size; 4259 case O_NAT: 4260 if (!IPFW_NAT_LOADED) 4261 return EINVAL; 4262 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat)) 4263 goto bad_size; 4264 goto check_action; 4265 case O_FORWARD_MAC: /* XXX not implemented yet */ 4266 case O_CHECK_STATE: 4267 case O_COUNT: 4268 case O_ACCEPT: 4269 case O_DENY: 4270 case O_REJECT: 4271#ifdef INET6 4272 case O_UNREACH6: 4273#endif 4274 case O_SKIPTO: 4275 case O_REASS: 4276check_size: 4277 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4278 goto bad_size; 4279check_action: 4280 if (have_action) { 4281 printf("ipfw: opcode %d, multiple actions" 4282 " not allowed\n", 4283 cmd->opcode); 4284 return EINVAL; 4285 } 4286 have_action = 1; 4287 if (l != cmdlen) { 4288 printf("ipfw: opcode %d, action must be" 4289 " last opcode\n", 4290 cmd->opcode); 4291 return EINVAL; 4292 } 4293 break; 4294#ifdef INET6 4295 case O_IP6_SRC: 4296 case O_IP6_DST: 4297 if (cmdlen != F_INSN_SIZE(struct in6_addr) + 4298 F_INSN_SIZE(ipfw_insn)) 4299 goto bad_size; 4300 break; 4301 4302 case O_FLOW6ID: 4303 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 4304 ((ipfw_insn_u32 *)cmd)->o.arg1) 4305 goto bad_size; 4306 break; 4307 4308 case O_IP6_SRC_MASK: 4309 case O_IP6_DST_MASK: 4310 if ( !(cmdlen & 1) || cmdlen > 127) 4311 goto bad_size; 4312 break; 4313 case O_ICMP6TYPE: 4314 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) ) 4315 goto bad_size; 4316 break; 4317#endif 4318 4319 default: 4320 switch (cmd->opcode) { 4321#ifndef INET6 4322 case O_IP6_SRC_ME: 4323 case O_IP6_DST_ME: 4324 case O_EXT_HDR: 4325 case O_IP6: 4326 case O_UNREACH6: 4327 case O_IP6_SRC: 4328 case O_IP6_DST: 4329 case O_FLOW6ID: 4330 case O_IP6_SRC_MASK: 4331 case O_IP6_DST_MASK: 4332 case O_ICMP6TYPE: 4333 printf("ipfw: no IPv6 support in kernel\n"); 4334 return EPROTONOSUPPORT; 4335#endif 4336 default: 4337 printf("ipfw: opcode %d, unknown opcode\n", 4338 cmd->opcode); 4339 return EINVAL; 4340 } 4341 } 4342 } 4343 if (have_action == 0) { 4344 printf("ipfw: missing action\n"); 4345 return EINVAL; 4346 } 4347 return 0; 4348 4349bad_size: 4350 printf("ipfw: opcode %d size %d wrong\n", 4351 cmd->opcode, cmdlen); 4352 return EINVAL; 4353} 4354 4355/* 4356 * Copy the static and dynamic rules to the supplied buffer 4357 * and return the amount of space actually used. 4358 */ 4359static size_t 4360ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space) 4361{ 4362 char *bp = buf; 4363 char *ep = bp + space; 4364 struct ip_fw *rule; 4365 int i; 4366 time_t boot_seconds; 4367 4368 boot_seconds = boottime.tv_sec; 4369 /* XXX this can take a long time and locking will block packet flow */ 4370 IPFW_RLOCK(chain); 4371 for (rule = chain->rules; rule ; rule = rule->next) { 4372 /* 4373 * Verify the entry fits in the buffer in case the 4374 * rules changed between calculating buffer space and 4375 * now. This would be better done using a generation 4376 * number but should suffice for now. 4377 */ 4378 i = RULESIZE(rule); 4379 if (bp + i <= ep) { 4380 bcopy(rule, bp, i); 4381 /* 4382 * XXX HACK. Store the disable mask in the "next" 4383 * pointer in a wild attempt to keep the ABI the same. 4384 * Why do we do this on EVERY rule? 4385 */ 4386 bcopy(&V_set_disable, 4387 &(((struct ip_fw *)bp)->next_rule), 4388 sizeof(V_set_disable)); 4389 if (((struct ip_fw *)bp)->timestamp) 4390 ((struct ip_fw *)bp)->timestamp += boot_seconds; 4391 bp += i; 4392 } 4393 } 4394 IPFW_RUNLOCK(chain); 4395 if (V_ipfw_dyn_v) { 4396 ipfw_dyn_rule *p, *last = NULL; 4397 4398 IPFW_DYN_LOCK(); 4399 for (i = 0 ; i < V_curr_dyn_buckets; i++) 4400 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) { 4401 if (bp + sizeof *p <= ep) { 4402 ipfw_dyn_rule *dst = 4403 (ipfw_dyn_rule *)bp; 4404 bcopy(p, dst, sizeof *p); 4405 bcopy(&(p->rule->rulenum), &(dst->rule), 4406 sizeof(p->rule->rulenum)); 4407 /* 4408 * store set number into high word of 4409 * dst->rule pointer. 4410 */ 4411 bcopy(&(p->rule->set), 4412 (char *)&dst->rule + 4413 sizeof(p->rule->rulenum), 4414 sizeof(p->rule->set)); 4415 /* 4416 * store a non-null value in "next". 4417 * The userland code will interpret a 4418 * NULL here as a marker 4419 * for the last dynamic rule. 4420 */ 4421 bcopy(&dst, &dst->next, sizeof(dst)); 4422 last = dst; 4423 dst->expire = 4424 TIME_LEQ(dst->expire, time_uptime) ? 4425 0 : dst->expire - time_uptime ; 4426 bp += sizeof(ipfw_dyn_rule); 4427 } 4428 } 4429 IPFW_DYN_UNLOCK(); 4430 if (last != NULL) /* mark last dynamic rule */ 4431 bzero(&last->next, sizeof(last)); 4432 } 4433 return (bp - (char *)buf); 4434} 4435 4436 4437/** 4438 * {set|get}sockopt parser. 4439 */ 4440static int 4441ipfw_ctl(struct sockopt *sopt) 4442{ 4443#define RULE_MAXSIZE (256*sizeof(u_int32_t)) 4444 int error; 4445 size_t size; 4446 struct ip_fw *buf, *rule; 4447 u_int32_t rulenum[2]; 4448 4449 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW); 4450 if (error) 4451 return (error); 4452 4453 /* 4454 * Disallow modifications in really-really secure mode, but still allow 4455 * the logging counters to be reset. 4456 */ 4457 if (sopt->sopt_name == IP_FW_ADD || 4458 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) { 4459 error = securelevel_ge(sopt->sopt_td->td_ucred, 3); 4460 if (error) 4461 return (error); 4462 } 4463 4464 error = 0; 4465 4466 switch (sopt->sopt_name) { 4467 case IP_FW_GET: 4468 /* 4469 * pass up a copy of the current rules. Static rules 4470 * come first (the last of which has number IPFW_DEFAULT_RULE), 4471 * followed by a possibly empty list of dynamic rule. 4472 * The last dynamic rule has NULL in the "next" field. 4473 * 4474 * Note that the calculated size is used to bound the 4475 * amount of data returned to the user. The rule set may 4476 * change between calculating the size and returning the 4477 * data in which case we'll just return what fits. 4478 */ 4479 size = V_static_len; /* size of static rules */ 4480 if (V_ipfw_dyn_v) /* add size of dyn.rules */ 4481 size += (V_dyn_count * sizeof(ipfw_dyn_rule)); 4482 4483 if (size >= sopt->sopt_valsize) 4484 break; 4485 /* 4486 * XXX todo: if the user passes a short length just to know 4487 * how much room is needed, do not bother filling up the 4488 * buffer, just jump to the sooptcopyout. 4489 */ 4490 buf = malloc(size, M_TEMP, M_WAITOK); 4491 error = sooptcopyout(sopt, buf, 4492 ipfw_getrules(&V_layer3_chain, buf, size)); 4493 free(buf, M_TEMP); 4494 break; 4495 4496 case IP_FW_FLUSH: 4497 /* 4498 * Normally we cannot release the lock on each iteration. 4499 * We could do it here only because we start from the head all 4500 * the times so there is no risk of missing some entries. 4501 * On the other hand, the risk is that we end up with 4502 * a very inconsistent ruleset, so better keep the lock 4503 * around the whole cycle. 4504 * 4505 * XXX this code can be improved by resetting the head of 4506 * the list to point to the default rule, and then freeing 4507 * the old list without the need for a lock. 4508 */ 4509 4510 IPFW_WLOCK(&V_layer3_chain); 4511 free_chain(&V_layer3_chain, 0 /* keep default rule */); 4512 rule = V_layer3_chain.reap; 4513 IPFW_WUNLOCK(&V_layer3_chain); 4514 reap_rules(rule); 4515 break; 4516 4517 case IP_FW_ADD: 4518 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK); 4519 error = sooptcopyin(sopt, rule, RULE_MAXSIZE, 4520 sizeof(struct ip_fw) ); 4521 if (error == 0) 4522 error = check_ipfw_struct(rule, sopt->sopt_valsize); 4523 if (error == 0) { 4524 error = add_rule(&V_layer3_chain, rule); 4525 size = RULESIZE(rule); 4526 if (!error && sopt->sopt_dir == SOPT_GET) 4527 error = sooptcopyout(sopt, rule, size); 4528 } 4529 free(rule, M_TEMP); 4530 break; 4531 4532 case IP_FW_DEL: 4533 /* 4534 * IP_FW_DEL is used for deleting single rules or sets, 4535 * and (ab)used to atomically manipulate sets. Argument size 4536 * is used to distinguish between the two: 4537 * sizeof(u_int32_t) 4538 * delete single rule or set of rules, 4539 * or reassign rules (or sets) to a different set. 4540 * 2*sizeof(u_int32_t) 4541 * atomic disable/enable sets. 4542 * first u_int32_t contains sets to be disabled, 4543 * second u_int32_t contains sets to be enabled. 4544 */ 4545 error = sooptcopyin(sopt, rulenum, 4546 2*sizeof(u_int32_t), sizeof(u_int32_t)); 4547 if (error) 4548 break; 4549 size = sopt->sopt_valsize; 4550 if (size == sizeof(u_int32_t)) /* delete or reassign */ 4551 error = del_entry(&V_layer3_chain, rulenum[0]); 4552 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */ 4553 V_set_disable = 4554 (V_set_disable | rulenum[0]) & ~rulenum[1] & 4555 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */ 4556 else 4557 error = EINVAL; 4558 break; 4559 4560 case IP_FW_ZERO: 4561 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */ 4562 rulenum[0] = 0; 4563 if (sopt->sopt_val != 0) { 4564 error = sooptcopyin(sopt, rulenum, 4565 sizeof(u_int32_t), sizeof(u_int32_t)); 4566 if (error) 4567 break; 4568 } 4569 error = zero_entry(&V_layer3_chain, rulenum[0], 4570 sopt->sopt_name == IP_FW_RESETLOG); 4571 break; 4572 4573 case IP_FW_TABLE_ADD: 4574 { 4575 ipfw_table_entry ent; 4576 4577 error = sooptcopyin(sopt, &ent, 4578 sizeof(ent), sizeof(ent)); 4579 if (error) 4580 break; 4581 error = add_table_entry(&V_layer3_chain, ent.tbl, 4582 ent.addr, ent.masklen, ent.value); 4583 } 4584 break; 4585 4586 case IP_FW_TABLE_DEL: 4587 { 4588 ipfw_table_entry ent; 4589 4590 error = sooptcopyin(sopt, &ent, 4591 sizeof(ent), sizeof(ent)); 4592 if (error) 4593 break; 4594 error = del_table_entry(&V_layer3_chain, ent.tbl, 4595 ent.addr, ent.masklen); 4596 } 4597 break; 4598 4599 case IP_FW_TABLE_FLUSH: 4600 { 4601 u_int16_t tbl; 4602 4603 error = sooptcopyin(sopt, &tbl, 4604 sizeof(tbl), sizeof(tbl)); 4605 if (error) 4606 break; 4607 IPFW_WLOCK(&V_layer3_chain); 4608 error = flush_table(&V_layer3_chain, tbl); 4609 IPFW_WUNLOCK(&V_layer3_chain); 4610 } 4611 break; 4612 4613 case IP_FW_TABLE_GETSIZE: 4614 { 4615 u_int32_t tbl, cnt; 4616 4617 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl), 4618 sizeof(tbl)))) 4619 break; 4620 IPFW_RLOCK(&V_layer3_chain); 4621 error = count_table(&V_layer3_chain, tbl, &cnt); 4622 IPFW_RUNLOCK(&V_layer3_chain); 4623 if (error) 4624 break; 4625 error = sooptcopyout(sopt, &cnt, sizeof(cnt)); 4626 } 4627 break; 4628 4629 case IP_FW_TABLE_LIST: 4630 { 4631 ipfw_table *tbl; 4632 4633 if (sopt->sopt_valsize < sizeof(*tbl)) { 4634 error = EINVAL; 4635 break; 4636 } 4637 size = sopt->sopt_valsize; 4638 tbl = malloc(size, M_TEMP, M_WAITOK); 4639 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl)); 4640 if (error) { 4641 free(tbl, M_TEMP); 4642 break; 4643 } 4644 tbl->size = (size - sizeof(*tbl)) / 4645 sizeof(ipfw_table_entry); 4646 IPFW_RLOCK(&V_layer3_chain); 4647 error = dump_table(&V_layer3_chain, tbl); 4648 IPFW_RUNLOCK(&V_layer3_chain); 4649 if (error) { 4650 free(tbl, M_TEMP); 4651 break; 4652 } 4653 error = sooptcopyout(sopt, tbl, size); 4654 free(tbl, M_TEMP); 4655 } 4656 break; 4657 4658 case IP_FW_NAT_CFG: 4659 if (IPFW_NAT_LOADED) 4660 error = ipfw_nat_cfg_ptr(sopt); 4661 else { 4662 printf("IP_FW_NAT_CFG: %s\n", 4663 "ipfw_nat not present, please load it"); 4664 error = EINVAL; 4665 } 4666 break; 4667 4668 case IP_FW_NAT_DEL: 4669 if (IPFW_NAT_LOADED) 4670 error = ipfw_nat_del_ptr(sopt); 4671 else { 4672 printf("IP_FW_NAT_DEL: %s\n", 4673 "ipfw_nat not present, please load it"); 4674 error = EINVAL; 4675 } 4676 break; 4677 4678 case IP_FW_NAT_GET_CONFIG: 4679 if (IPFW_NAT_LOADED) 4680 error = ipfw_nat_get_cfg_ptr(sopt); 4681 else { 4682 printf("IP_FW_NAT_GET_CFG: %s\n", 4683 "ipfw_nat not present, please load it"); 4684 error = EINVAL; 4685 } 4686 break; 4687 4688 case IP_FW_NAT_GET_LOG: 4689 if (IPFW_NAT_LOADED) 4690 error = ipfw_nat_get_log_ptr(sopt); 4691 else { 4692 printf("IP_FW_NAT_GET_LOG: %s\n", 4693 "ipfw_nat not present, please load it"); 4694 error = EINVAL; 4695 } 4696 break; 4697 4698 default: 4699 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name); 4700 error = EINVAL; 4701 } 4702 4703 return (error); 4704#undef RULE_MAXSIZE 4705} 4706 4707 4708/* 4709 * This procedure is only used to handle keepalives. It is invoked 4710 * every dyn_keepalive_period 4711 */ 4712static void 4713ipfw_tick(void * vnetx) 4714{ 4715 struct mbuf *m0, *m, *mnext, **mtailp; 4716#ifdef INET6 4717 struct mbuf *m6, **m6_tailp; 4718#endif 4719 int i; 4720 ipfw_dyn_rule *q; 4721#ifdef VIMAGE 4722 struct vnet *vp = vnetx; 4723#endif 4724 4725 CURVNET_SET(vp); 4726 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0) 4727 goto done; 4728 4729 /* 4730 * We make a chain of packets to go out here -- not deferring 4731 * until after we drop the IPFW dynamic rule lock would result 4732 * in a lock order reversal with the normal packet input -> ipfw 4733 * call stack. 4734 */ 4735 m0 = NULL; 4736 mtailp = &m0; 4737#ifdef INET6 4738 m6 = NULL; 4739 m6_tailp = &m6; 4740#endif 4741 IPFW_DYN_LOCK(); 4742 for (i = 0 ; i < V_curr_dyn_buckets ; i++) { 4743 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) { 4744 if (q->dyn_type == O_LIMIT_PARENT) 4745 continue; 4746 if (q->id.proto != IPPROTO_TCP) 4747 continue; 4748 if ( (q->state & BOTH_SYN) != BOTH_SYN) 4749 continue; 4750 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval, 4751 q->expire)) 4752 continue; /* too early */ 4753 if (TIME_LEQ(q->expire, time_uptime)) 4754 continue; /* too late, rule expired */ 4755 4756 m = send_pkt(NULL, &(q->id), q->ack_rev - 1, 4757 q->ack_fwd, TH_SYN); 4758 mnext = send_pkt(NULL, &(q->id), q->ack_fwd - 1, 4759 q->ack_rev, 0); 4760 4761 switch (q->id.addr_type) { 4762 case 4: 4763 if (m != NULL) { 4764 *mtailp = m; 4765 mtailp = &(*mtailp)->m_nextpkt; 4766 } 4767 if (mnext != NULL) { 4768 *mtailp = mnext; 4769 mtailp = &(*mtailp)->m_nextpkt; 4770 } 4771 break; 4772#ifdef INET6 4773 case 6: 4774 if (m != NULL) { 4775 *m6_tailp = m; 4776 m6_tailp = &(*m6_tailp)->m_nextpkt; 4777 } 4778 if (mnext != NULL) { 4779 *m6_tailp = mnext; 4780 m6_tailp = &(*m6_tailp)->m_nextpkt; 4781 } 4782 break; 4783#endif 4784 } 4785 4786 m = mnext = NULL; 4787 } 4788 } 4789 IPFW_DYN_UNLOCK(); 4790 for (m = mnext = m0; m != NULL; m = mnext) { 4791 mnext = m->m_nextpkt; 4792 m->m_nextpkt = NULL; 4793 ip_output(m, NULL, NULL, 0, NULL, NULL); 4794 } 4795#ifdef INET6 4796 for (m = mnext = m6; m != NULL; m = mnext) { 4797 mnext = m->m_nextpkt; 4798 m->m_nextpkt = NULL; 4799 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL); 4800 } 4801#endif 4802done: 4803 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz, 4804 ipfw_tick, vnetx); 4805 CURVNET_RESTORE(); 4806} 4807 4808/**************** 4809 * Stuff that must be initialised only on boot or module load 4810 */ 4811static int 4812ipfw_init(void) 4813{ 4814 int error = 0; 4815 4816 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule", 4817 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL, 4818 UMA_ALIGN_PTR, 0); 4819 4820 IPFW_DYN_LOCK_INIT(); 4821 /* 4822 * Only print out this stuff the first time around, 4823 * when called from the sysinit code. 4824 */ 4825 printf("ipfw2 " 4826#ifdef INET6 4827 "(+ipv6) " 4828#endif 4829 "initialized, divert %s, nat %s, " 4830 "rule-based forwarding " 4831#ifdef IPFIREWALL_FORWARD 4832 "enabled, " 4833#else 4834 "disabled, " 4835#endif 4836 "default to %s, logging ", 4837#ifdef IPDIVERT 4838 "enabled", 4839#else 4840 "loadable", 4841#endif 4842#ifdef IPFIREWALL_NAT 4843 "enabled", 4844#else 4845 "loadable", 4846#endif 4847 default_to_accept ? "accept" : "deny"); 4848 4849 /* 4850 * Note: V_xxx variables can be accessed here but the vnet specific 4851 * initializer may not have been called yet for the VIMAGE case. 4852 * Tuneables will have been processed. We will print out values for 4853 * the default vnet. 4854 * XXX This should all be rationalized AFTER 8.0 4855 */ 4856 if (V_fw_verbose == 0) 4857 printf("disabled\n"); 4858 else if (V_verbose_limit == 0) 4859 printf("unlimited\n"); 4860 else 4861 printf("limited to %d packets/entry by default\n", 4862 V_verbose_limit); 4863 4864 return (error); 4865} 4866 4867/********************** 4868 * Called for the removal of the last instance only on module unload. 4869 */ 4870static void 4871ipfw_destroy(void) 4872{ 4873 4874 uma_zdestroy(ipfw_dyn_rule_zone); 4875 IPFW_DYN_LOCK_DESTROY(); 4876 printf("IP firewall unloaded\n"); 4877} 4878 4879/**************** 4880 * Stuff that must be initialized for every instance 4881 * (including the first of course). 4882 */ 4883static int 4884vnet_ipfw_init(const void *unused) 4885{ 4886 int error; 4887 struct ip_fw default_rule; 4888 4889 /* First set up some values that are compile time options */ 4890#ifdef IPFIREWALL_VERBOSE 4891 V_fw_verbose = 1; 4892#endif 4893#ifdef IPFIREWALL_VERBOSE_LIMIT 4894 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT; 4895#endif 4896 4897 error = init_tables(&V_layer3_chain); 4898 if (error) { 4899 panic("init_tables"); /* XXX Marko fix this ! */ 4900 } 4901#ifdef IPFIREWALL_NAT 4902 LIST_INIT(&V_layer3_chain.nat); 4903#endif 4904 4905 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */ 4906 4907 V_ipfw_dyn_v = NULL; 4908 V_dyn_buckets = 256; /* must be power of 2 */ 4909 V_curr_dyn_buckets = 256; /* must be power of 2 */ 4910 4911 V_dyn_ack_lifetime = 300; 4912 V_dyn_syn_lifetime = 20; 4913 V_dyn_fin_lifetime = 1; 4914 V_dyn_rst_lifetime = 1; 4915 V_dyn_udp_lifetime = 10; 4916 V_dyn_short_lifetime = 5; 4917 4918 V_dyn_keepalive_interval = 20; 4919 V_dyn_keepalive_period = 5; 4920 V_dyn_keepalive = 1; /* do send keepalives */ 4921 4922 V_dyn_max = 4096; /* max # of dynamic rules */ 4923 4924 V_fw_deny_unknown_exthdrs = 1; 4925 4926 V_layer3_chain.rules = NULL; 4927 IPFW_LOCK_INIT(&V_layer3_chain); 4928 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE); 4929 4930 bzero(&default_rule, sizeof default_rule); 4931 default_rule.act_ofs = 0; 4932 default_rule.rulenum = IPFW_DEFAULT_RULE; 4933 default_rule.cmd_len = 1; 4934 default_rule.set = RESVD_SET; 4935 default_rule.cmd[0].len = 1; 4936 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY; 4937 error = add_rule(&V_layer3_chain, &default_rule); 4938 4939 if (error != 0) { 4940 printf("ipfw2: error %u initializing default rule " 4941 "(support disabled)\n", error); 4942 IPFW_LOCK_DESTROY(&V_layer3_chain); 4943 printf("leaving ipfw_iattach (1) with error %d\n", error); 4944 return (error); 4945 } 4946 4947 ip_fw_default_rule = V_layer3_chain.rules; 4948 4949 /* curvnet is NULL in the !VIMAGE case */ 4950 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet); 4951 4952 /* First set up some values that are compile time options */ 4953 V_ipfw_vnet_ready = 1; /* Open for business */ 4954 4955 /* 4956 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr) 4957 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail 4958 * we still keep the module alive because the sockopt and 4959 * layer2 paths are still useful. 4960 * ipfw[6]_hook return 0 on success, ENOENT on failure, 4961 * so we can ignore the exact return value and just set a flag. 4962 * 4963 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so 4964 * changes in the underlying (per-vnet) variables trigger 4965 * immediate hook()/unhook() calls. 4966 * In layer2 we have the same behaviour, except that V_ether_ipfw 4967 * is checked on each packet because there are no pfil hooks. 4968 */ 4969 V_ip_fw_ctl_ptr = ipfw_ctl; 4970 V_ip_fw_chk_ptr = ipfw_chk; 4971 if (V_fw_enable && ipfw_hook() != 0) { 4972 error = ENOENT; /* see ip_fw_pfil.c::ipfw_hook() */ 4973 printf("ipfw_hook() error\n"); 4974 } 4975#ifdef INET6 4976 if (V_fw6_enable && ipfw6_hook() != 0) { 4977 error = ENOENT; 4978 printf("ipfw6_hook() error\n"); 4979 } 4980#endif 4981 return (error); 4982} 4983 4984/*********************** 4985 * Called for the removal of each instance. 4986 */ 4987static int 4988vnet_ipfw_uninit(const void *unused) 4989{ 4990 struct ip_fw *reap; 4991 4992 V_ipfw_vnet_ready = 0; /* tell new callers to go away */ 4993 /* 4994 * disconnect from ipv4, ipv6, layer2 and sockopt. 4995 * Then grab, release and grab again the WLOCK so we make 4996 * sure the update is propagated and nobody will be in. 4997 */ 4998 ipfw_unhook(); 4999#ifdef INET6 5000 ipfw6_unhook(); 5001#endif 5002 V_ip_fw_chk_ptr = NULL; 5003 V_ip_fw_ctl_ptr = NULL; 5004 5005 IPFW_WLOCK(&V_layer3_chain); 5006 /* We wait on the wlock here until the last user leaves */ 5007 IPFW_WUNLOCK(&V_layer3_chain); 5008 IPFW_WLOCK(&V_layer3_chain); 5009 5010 callout_drain(&V_ipfw_timeout); 5011 flush_tables(&V_layer3_chain); 5012 V_layer3_chain.reap = NULL; 5013 free_chain(&V_layer3_chain, 1 /* kill default rule */); 5014 reap = V_layer3_chain.reap; 5015 V_layer3_chain.reap = NULL; 5016 IPFW_WUNLOCK(&V_layer3_chain); 5017 if (reap != NULL) 5018 reap_rules(reap); 5019 IPFW_LOCK_DESTROY(&V_layer3_chain); 5020 if (V_ipfw_dyn_v != NULL) 5021 free(V_ipfw_dyn_v, M_IPFW); 5022 return 0; 5023} 5024 5025/* 5026 * Module event handler. 5027 * In general we have the choice of handling most of these events by the 5028 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to 5029 * use the SYSINIT handlers as they are more capable of expressing the 5030 * flow of control during module and vnet operations, so this is just 5031 * a skeleton. Note there is no SYSINIT equivalent of the module 5032 * SHUTDOWN handler, but we don't have anything to do in that case anyhow. 5033 */ 5034static int 5035ipfw_modevent(module_t mod, int type, void *unused) 5036{ 5037 int err = 0; 5038 5039 switch (type) { 5040 case MOD_LOAD: 5041 /* Called once at module load or 5042 * system boot if compiled in. */ 5043 break; 5044 case MOD_QUIESCE: 5045 /* Called before unload. May veto unloading. */ 5046 break; 5047 case MOD_UNLOAD: 5048 /* Called during unload. */ 5049 break; 5050 case MOD_SHUTDOWN: 5051 /* Called during system shutdown. */ 5052 break; 5053 default: 5054 err = EOPNOTSUPP; 5055 break; 5056 } 5057 return err; 5058} 5059 5060static moduledata_t ipfwmod = { 5061 "ipfw", 5062 ipfw_modevent, 5063 0 5064}; 5065 5066/* Define startup order. */ 5067#define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN 5068#define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */ 5069#define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */ 5070#define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */ 5071 5072DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER); 5073MODULE_VERSION(ipfw, 2); 5074/* should declare some dependencies here */ 5075 5076/* 5077 * Starting up. Done in order after ipfwmod() has been called. 5078 * VNET_SYSINIT is also called for each existing vnet and each new vnet. 5079 */ 5080SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER, 5081 ipfw_init, NULL); 5082VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER, 5083 vnet_ipfw_init, NULL); 5084 5085/* 5086 * Closing up shop. These are done in REVERSE ORDER, but still 5087 * after ipfwmod() has been called. Not called on reboot. 5088 * VNET_SYSUNINIT is also called for each exiting vnet as it exits. 5089 * or when the module is unloaded. 5090 */ 5091SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER, 5092 ipfw_destroy, NULL); 5093VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER, 5094 vnet_ipfw_uninit, NULL); 5095 5096