ip_fw2.c revision 200055
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 200055 2009-12-03 11:16:53Z ume $"); 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 char src[48], dst[48]; 903 struct icmphdr *icmp; 904 struct tcphdr *tcp; 905 struct udphdr *udp; 906#ifdef INET6 907 struct ip6_hdr *ip6 = NULL; 908 struct icmp6_hdr *icmp6; 909#endif 910 src[0] = '\0'; 911 dst[0] = '\0'; 912#ifdef INET6 913 if (IS_IP6_FLOW_ID(&(args->f_id))) { 914 char ip6buf[INET6_ADDRSTRLEN]; 915 snprintf(src, sizeof(src), "[%s]", 916 ip6_sprintf(ip6buf, &args->f_id.src_ip6)); 917 snprintf(dst, sizeof(dst), "[%s]", 918 ip6_sprintf(ip6buf, &args->f_id.dst_ip6)); 919 920 ip6 = (struct ip6_hdr *)ip; 921 tcp = (struct tcphdr *)(((char *)ip) + hlen); 922 udp = (struct udphdr *)(((char *)ip) + hlen); 923 } else 924#endif 925 { 926 tcp = L3HDR(struct tcphdr, ip); 927 udp = L3HDR(struct udphdr, ip); 928 929 inet_ntoa_r(ip->ip_src, src); 930 inet_ntoa_r(ip->ip_dst, dst); 931 } 932 933 switch (args->f_id.proto) { 934 case IPPROTO_TCP: 935 len = snprintf(SNPARGS(proto, 0), "TCP %s", src); 936 if (offset == 0) 937 snprintf(SNPARGS(proto, len), ":%d %s:%d", 938 ntohs(tcp->th_sport), 939 dst, 940 ntohs(tcp->th_dport)); 941 else 942 snprintf(SNPARGS(proto, len), " %s", dst); 943 break; 944 945 case IPPROTO_UDP: 946 len = snprintf(SNPARGS(proto, 0), "UDP %s", src); 947 if (offset == 0) 948 snprintf(SNPARGS(proto, len), ":%d %s:%d", 949 ntohs(udp->uh_sport), 950 dst, 951 ntohs(udp->uh_dport)); 952 else 953 snprintf(SNPARGS(proto, len), " %s", dst); 954 break; 955 956 case IPPROTO_ICMP: 957 icmp = L3HDR(struct icmphdr, ip); 958 if (offset == 0) 959 len = snprintf(SNPARGS(proto, 0), 960 "ICMP:%u.%u ", 961 icmp->icmp_type, icmp->icmp_code); 962 else 963 len = snprintf(SNPARGS(proto, 0), "ICMP "); 964 len += snprintf(SNPARGS(proto, len), "%s", src); 965 snprintf(SNPARGS(proto, len), " %s", dst); 966 break; 967#ifdef INET6 968 case IPPROTO_ICMPV6: 969 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen); 970 if (offset == 0) 971 len = snprintf(SNPARGS(proto, 0), 972 "ICMPv6:%u.%u ", 973 icmp6->icmp6_type, icmp6->icmp6_code); 974 else 975 len = snprintf(SNPARGS(proto, 0), "ICMPv6 "); 976 len += snprintf(SNPARGS(proto, len), "%s", src); 977 snprintf(SNPARGS(proto, len), " %s", dst); 978 break; 979#endif 980 default: 981 len = snprintf(SNPARGS(proto, 0), "P:%d %s", 982 args->f_id.proto, src); 983 snprintf(SNPARGS(proto, len), " %s", dst); 984 break; 985 } 986 987#ifdef INET6 988 if (IS_IP6_FLOW_ID(&(args->f_id))) { 989 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG)) 990 snprintf(SNPARGS(fragment, 0), 991 " (frag %08x:%d@%d%s)", 992 args->f_id.frag_id6, 993 ntohs(ip6->ip6_plen) - hlen, 994 ntohs(offset & IP6F_OFF_MASK) << 3, 995 (offset & IP6F_MORE_FRAG) ? "+" : ""); 996 } else 997#endif 998 { 999 int ip_off, ip_len; 1000 if (eh != NULL) { /* layer 2 packets are as on the wire */ 1001 ip_off = ntohs(ip->ip_off); 1002 ip_len = ntohs(ip->ip_len); 1003 } else { 1004 ip_off = ip->ip_off; 1005 ip_len = ip->ip_len; 1006 } 1007 if (ip_off & (IP_MF | IP_OFFMASK)) 1008 snprintf(SNPARGS(fragment, 0), 1009 " (frag %d:%d@%d%s)", 1010 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2), 1011 offset << 3, 1012 (ip_off & IP_MF) ? "+" : ""); 1013 } 1014 } 1015 if (oif || m->m_pkthdr.rcvif) 1016 log(LOG_SECURITY | LOG_INFO, 1017 "ipfw: %d %s %s %s via %s%s\n", 1018 f ? f->rulenum : -1, 1019 action, proto, oif ? "out" : "in", 1020 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname, 1021 fragment); 1022 else 1023 log(LOG_SECURITY | LOG_INFO, 1024 "ipfw: %d %s %s [no if info]%s\n", 1025 f ? f->rulenum : -1, 1026 action, proto, fragment); 1027 if (limit_reached) 1028 log(LOG_SECURITY | LOG_NOTICE, 1029 "ipfw: limit %d reached on entry %d\n", 1030 limit_reached, f ? f->rulenum : -1); 1031} 1032 1033/* 1034 * IMPORTANT: the hash function for dynamic rules must be commutative 1035 * in source and destination (ip,port), because rules are bidirectional 1036 * and we want to find both in the same bucket. 1037 */ 1038static __inline int 1039hash_packet(struct ipfw_flow_id *id) 1040{ 1041 u_int32_t i; 1042 1043#ifdef INET6 1044 if (IS_IP6_FLOW_ID(id)) 1045 i = hash_packet6(id); 1046 else 1047#endif /* INET6 */ 1048 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port); 1049 i &= (V_curr_dyn_buckets - 1); 1050 return i; 1051} 1052 1053static __inline void 1054unlink_dyn_rule_print(struct ipfw_flow_id *id) 1055{ 1056 struct in_addr da; 1057 char src[48], dst[48]; 1058 1059#ifdef INET6 1060 if (IS_IP6_FLOW_ID(id)) { 1061 ip6_sprintf(src, &id->src_ip6); 1062 ip6_sprintf(dst, &id->dst_ip6); 1063 } else 1064#endif 1065 { 1066 da.s_addr = htonl(id->src_ip); 1067 inet_ntoa_r(da, src); 1068 da.s_addr = htonl(id->dst_ip); 1069 inet_ntoa_r(da, dst); 1070 } 1071 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n", 1072 src, id->src_port, dst, id->dst_port, V_dyn_count - 1); 1073} 1074 1075/** 1076 * unlink a dynamic rule from a chain. prev is a pointer to 1077 * the previous one, q is a pointer to the rule to delete, 1078 * head is a pointer to the head of the queue. 1079 * Modifies q and potentially also head. 1080 */ 1081#define UNLINK_DYN_RULE(prev, head, q) { \ 1082 ipfw_dyn_rule *old_q = q; \ 1083 \ 1084 /* remove a refcount to the parent */ \ 1085 if (q->dyn_type == O_LIMIT) \ 1086 q->parent->count--; \ 1087 DEB(unlink_dyn_rule_print(&q->id);) \ 1088 if (prev != NULL) \ 1089 prev->next = q = q->next; \ 1090 else \ 1091 head = q = q->next; \ 1092 V_dyn_count--; \ 1093 uma_zfree(ipfw_dyn_rule_zone, old_q); } 1094 1095#define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0) 1096 1097/** 1098 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL. 1099 * 1100 * If keep_me == NULL, rules are deleted even if not expired, 1101 * otherwise only expired rules are removed. 1102 * 1103 * The value of the second parameter is also used to point to identify 1104 * a rule we absolutely do not want to remove (e.g. because we are 1105 * holding a reference to it -- this is the case with O_LIMIT_PARENT 1106 * rules). The pointer is only used for comparison, so any non-null 1107 * value will do. 1108 */ 1109static void 1110remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me) 1111{ 1112 static u_int32_t last_remove = 0; 1113 1114#define FORCE (keep_me == NULL) 1115 1116 ipfw_dyn_rule *prev, *q; 1117 int i, pass = 0, max_pass = 0; 1118 1119 IPFW_DYN_LOCK_ASSERT(); 1120 1121 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0) 1122 return; 1123 /* do not expire more than once per second, it is useless */ 1124 if (!FORCE && last_remove == time_uptime) 1125 return; 1126 last_remove = time_uptime; 1127 1128 /* 1129 * because O_LIMIT refer to parent rules, during the first pass only 1130 * remove child and mark any pending LIMIT_PARENT, and remove 1131 * them in a second pass. 1132 */ 1133next_pass: 1134 for (i = 0 ; i < V_curr_dyn_buckets ; i++) { 1135 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) { 1136 /* 1137 * Logic can become complex here, so we split tests. 1138 */ 1139 if (q == keep_me) 1140 goto next; 1141 if (rule != NULL && rule != q->rule) 1142 goto next; /* not the one we are looking for */ 1143 if (q->dyn_type == O_LIMIT_PARENT) { 1144 /* 1145 * handle parent in the second pass, 1146 * record we need one. 1147 */ 1148 max_pass = 1; 1149 if (pass == 0) 1150 goto next; 1151 if (FORCE && q->count != 0 ) { 1152 /* XXX should not happen! */ 1153 printf("ipfw: OUCH! cannot remove rule," 1154 " count %d\n", q->count); 1155 } 1156 } else { 1157 if (!FORCE && 1158 !TIME_LEQ( q->expire, time_uptime )) 1159 goto next; 1160 } 1161 if (q->dyn_type != O_LIMIT_PARENT || !q->count) { 1162 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q); 1163 continue; 1164 } 1165next: 1166 prev=q; 1167 q=q->next; 1168 } 1169 } 1170 if (pass++ < max_pass) 1171 goto next_pass; 1172} 1173 1174 1175/** 1176 * lookup a dynamic rule. 1177 */ 1178static ipfw_dyn_rule * 1179lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction, 1180 struct tcphdr *tcp) 1181{ 1182 /* 1183 * stateful ipfw extensions. 1184 * Lookup into dynamic session queue 1185 */ 1186#define MATCH_REVERSE 0 1187#define MATCH_FORWARD 1 1188#define MATCH_NONE 2 1189#define MATCH_UNKNOWN 3 1190 int i, dir = MATCH_NONE; 1191 ipfw_dyn_rule *prev, *q=NULL; 1192 1193 IPFW_DYN_LOCK_ASSERT(); 1194 1195 if (V_ipfw_dyn_v == NULL) 1196 goto done; /* not found */ 1197 i = hash_packet( pkt ); 1198 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) { 1199 if (q->dyn_type == O_LIMIT_PARENT && q->count) 1200 goto next; 1201 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */ 1202 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q); 1203 continue; 1204 } 1205 if (pkt->proto == q->id.proto && 1206 q->dyn_type != O_LIMIT_PARENT) { 1207 if (IS_IP6_FLOW_ID(pkt)) { 1208 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1209 &(q->id.src_ip6)) && 1210 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1211 &(q->id.dst_ip6)) && 1212 pkt->src_port == q->id.src_port && 1213 pkt->dst_port == q->id.dst_port ) { 1214 dir = MATCH_FORWARD; 1215 break; 1216 } 1217 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1218 &(q->id.dst_ip6)) && 1219 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1220 &(q->id.src_ip6)) && 1221 pkt->src_port == q->id.dst_port && 1222 pkt->dst_port == q->id.src_port ) { 1223 dir = MATCH_REVERSE; 1224 break; 1225 } 1226 } else { 1227 if (pkt->src_ip == q->id.src_ip && 1228 pkt->dst_ip == q->id.dst_ip && 1229 pkt->src_port == q->id.src_port && 1230 pkt->dst_port == q->id.dst_port ) { 1231 dir = MATCH_FORWARD; 1232 break; 1233 } 1234 if (pkt->src_ip == q->id.dst_ip && 1235 pkt->dst_ip == q->id.src_ip && 1236 pkt->src_port == q->id.dst_port && 1237 pkt->dst_port == q->id.src_port ) { 1238 dir = MATCH_REVERSE; 1239 break; 1240 } 1241 } 1242 } 1243next: 1244 prev = q; 1245 q = q->next; 1246 } 1247 if (q == NULL) 1248 goto done; /* q = NULL, not found */ 1249 1250 if ( prev != NULL) { /* found and not in front */ 1251 prev->next = q->next; 1252 q->next = V_ipfw_dyn_v[i]; 1253 V_ipfw_dyn_v[i] = q; 1254 } 1255 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */ 1256 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST); 1257 1258#define BOTH_SYN (TH_SYN | (TH_SYN << 8)) 1259#define BOTH_FIN (TH_FIN | (TH_FIN << 8)) 1260 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8); 1261 switch (q->state) { 1262 case TH_SYN: /* opening */ 1263 q->expire = time_uptime + V_dyn_syn_lifetime; 1264 break; 1265 1266 case BOTH_SYN: /* move to established */ 1267 case BOTH_SYN | TH_FIN : /* one side tries to close */ 1268 case BOTH_SYN | (TH_FIN << 8) : 1269 if (tcp) { 1270#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0) 1271 u_int32_t ack = ntohl(tcp->th_ack); 1272 if (dir == MATCH_FORWARD) { 1273 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd)) 1274 q->ack_fwd = ack; 1275 else { /* ignore out-of-sequence */ 1276 break; 1277 } 1278 } else { 1279 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev)) 1280 q->ack_rev = ack; 1281 else { /* ignore out-of-sequence */ 1282 break; 1283 } 1284 } 1285 } 1286 q->expire = time_uptime + V_dyn_ack_lifetime; 1287 break; 1288 1289 case BOTH_SYN | BOTH_FIN: /* both sides closed */ 1290 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period) 1291 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1; 1292 q->expire = time_uptime + V_dyn_fin_lifetime; 1293 break; 1294 1295 default: 1296#if 0 1297 /* 1298 * reset or some invalid combination, but can also 1299 * occur if we use keep-state the wrong way. 1300 */ 1301 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0) 1302 printf("invalid state: 0x%x\n", q->state); 1303#endif 1304 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period) 1305 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1; 1306 q->expire = time_uptime + V_dyn_rst_lifetime; 1307 break; 1308 } 1309 } else if (pkt->proto == IPPROTO_UDP) { 1310 q->expire = time_uptime + V_dyn_udp_lifetime; 1311 } else { 1312 /* other protocols */ 1313 q->expire = time_uptime + V_dyn_short_lifetime; 1314 } 1315done: 1316 if (match_direction) 1317 *match_direction = dir; 1318 return q; 1319} 1320 1321static ipfw_dyn_rule * 1322lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction, 1323 struct tcphdr *tcp) 1324{ 1325 ipfw_dyn_rule *q; 1326 1327 IPFW_DYN_LOCK(); 1328 q = lookup_dyn_rule_locked(pkt, match_direction, tcp); 1329 if (q == NULL) 1330 IPFW_DYN_UNLOCK(); 1331 /* NB: return table locked when q is not NULL */ 1332 return q; 1333} 1334 1335static void 1336realloc_dynamic_table(void) 1337{ 1338 IPFW_DYN_LOCK_ASSERT(); 1339 1340 /* 1341 * Try reallocation, make sure we have a power of 2 and do 1342 * not allow more than 64k entries. In case of overflow, 1343 * default to 1024. 1344 */ 1345 1346 if (V_dyn_buckets > 65536) 1347 V_dyn_buckets = 1024; 1348 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */ 1349 V_dyn_buckets = V_curr_dyn_buckets; /* reset */ 1350 return; 1351 } 1352 V_curr_dyn_buckets = V_dyn_buckets; 1353 if (V_ipfw_dyn_v != NULL) 1354 free(V_ipfw_dyn_v, M_IPFW); 1355 for (;;) { 1356 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *), 1357 M_IPFW, M_NOWAIT | M_ZERO); 1358 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2) 1359 break; 1360 V_curr_dyn_buckets /= 2; 1361 } 1362} 1363 1364/** 1365 * Install state of type 'type' for a dynamic session. 1366 * The hash table contains two type of rules: 1367 * - regular rules (O_KEEP_STATE) 1368 * - rules for sessions with limited number of sess per user 1369 * (O_LIMIT). When they are created, the parent is 1370 * increased by 1, and decreased on delete. In this case, 1371 * the third parameter is the parent rule and not the chain. 1372 * - "parent" rules for the above (O_LIMIT_PARENT). 1373 */ 1374static ipfw_dyn_rule * 1375add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule) 1376{ 1377 ipfw_dyn_rule *r; 1378 int i; 1379 1380 IPFW_DYN_LOCK_ASSERT(); 1381 1382 if (V_ipfw_dyn_v == NULL || 1383 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) { 1384 realloc_dynamic_table(); 1385 if (V_ipfw_dyn_v == NULL) 1386 return NULL; /* failed ! */ 1387 } 1388 i = hash_packet(id); 1389 1390 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO); 1391 if (r == NULL) { 1392 printf ("ipfw: sorry cannot allocate state\n"); 1393 return NULL; 1394 } 1395 1396 /* increase refcount on parent, and set pointer */ 1397 if (dyn_type == O_LIMIT) { 1398 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule; 1399 if ( parent->dyn_type != O_LIMIT_PARENT) 1400 panic("invalid parent"); 1401 parent->count++; 1402 r->parent = parent; 1403 rule = parent->rule; 1404 } 1405 1406 r->id = *id; 1407 r->expire = time_uptime + V_dyn_syn_lifetime; 1408 r->rule = rule; 1409 r->dyn_type = dyn_type; 1410 r->pcnt = r->bcnt = 0; 1411 r->count = 0; 1412 1413 r->bucket = i; 1414 r->next = V_ipfw_dyn_v[i]; 1415 V_ipfw_dyn_v[i] = r; 1416 V_dyn_count++; 1417 DEB({ 1418 struct in_addr da; 1419 char src[48]; 1420 char dst[48]; 1421#ifdef INET6 1422 if (IS_IP6_FLOW_ID(&(r->id))) { 1423 ip6_sprintf(src, &r->id.src_ip6); 1424 ip6_sprintf(dst, &r->id.dst_ip6); 1425 } else 1426#endif 1427 { 1428 da.s_addr = htonl(r->id.src_ip); 1429 inet_ntoa_r(da, src); 1430 da.s_addr = htonl(r->id.dst_ip); 1431 inet_ntoa_r(da, dst); 1432 } 1433 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n", 1434 dyn_type, src, r->id.src_port, dst, r->id.dst_port, 1435 V_dyn_count); 1436 }) 1437 return r; 1438} 1439 1440/** 1441 * lookup dynamic parent rule using pkt and rule as search keys. 1442 * If the lookup fails, then install one. 1443 */ 1444static ipfw_dyn_rule * 1445lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule) 1446{ 1447 ipfw_dyn_rule *q; 1448 int i; 1449 1450 IPFW_DYN_LOCK_ASSERT(); 1451 1452 if (V_ipfw_dyn_v) { 1453 int is_v6 = IS_IP6_FLOW_ID(pkt); 1454 i = hash_packet( pkt ); 1455 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next) 1456 if (q->dyn_type == O_LIMIT_PARENT && 1457 rule== q->rule && 1458 pkt->proto == q->id.proto && 1459 pkt->src_port == q->id.src_port && 1460 pkt->dst_port == q->id.dst_port && 1461 ( 1462 (is_v6 && 1463 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6), 1464 &(q->id.src_ip6)) && 1465 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6), 1466 &(q->id.dst_ip6))) || 1467 (!is_v6 && 1468 pkt->src_ip == q->id.src_ip && 1469 pkt->dst_ip == q->id.dst_ip) 1470 ) 1471 ) { 1472 q->expire = time_uptime + V_dyn_short_lifetime; 1473 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);) 1474 return q; 1475 } 1476 } 1477 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule); 1478} 1479 1480/** 1481 * Install dynamic state for rule type cmd->o.opcode 1482 * 1483 * Returns 1 (failure) if state is not installed because of errors or because 1484 * session limitations are enforced. 1485 */ 1486static int 1487install_state(struct ip_fw *rule, ipfw_insn_limit *cmd, 1488 struct ip_fw_args *args, uint32_t tablearg) 1489{ 1490 static int last_log; 1491 ipfw_dyn_rule *q; 1492 struct in_addr da; 1493 char src[48], dst[48]; 1494 1495 src[0] = '\0'; 1496 dst[0] = '\0'; 1497 1498 IPFW_DYN_LOCK(); 1499 1500 DEB( 1501#ifdef INET6 1502 if (IS_IP6_FLOW_ID(&(args->f_id))) { 1503 ip6_sprintf(src, &args->f_id.src_ip6); 1504 ip6_sprintf(dst, &args->f_id.dst_ip6); 1505 } else 1506#endif 1507 { 1508 da.s_addr = htonl(args->f_id.src_ip); 1509 inet_ntoa_r(da, src); 1510 da.s_addr = htonl(args->f_id.dst_ip); 1511 inet_ntoa_r(da, dst); 1512 } 1513 printf("ipfw: %s: type %d %s %u -> %s %u\n", 1514 __func__, cmd->o.opcode, src, args->f_id.src_port, 1515 dst, args->f_id.dst_port); 1516 src[0] = '\0'; 1517 dst[0] = '\0'; 1518 ) 1519 1520 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL); 1521 1522 if (q != NULL) { /* should never occur */ 1523 if (last_log != time_uptime) { 1524 last_log = time_uptime; 1525 printf("ipfw: %s: entry already present, done\n", 1526 __func__); 1527 } 1528 IPFW_DYN_UNLOCK(); 1529 return (0); 1530 } 1531 1532 if (V_dyn_count >= V_dyn_max) 1533 /* Run out of slots, try to remove any expired rule. */ 1534 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1); 1535 1536 if (V_dyn_count >= V_dyn_max) { 1537 if (last_log != time_uptime) { 1538 last_log = time_uptime; 1539 printf("ipfw: %s: Too many dynamic rules\n", __func__); 1540 } 1541 IPFW_DYN_UNLOCK(); 1542 return (1); /* cannot install, notify caller */ 1543 } 1544 1545 switch (cmd->o.opcode) { 1546 case O_KEEP_STATE: /* bidir rule */ 1547 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule); 1548 break; 1549 1550 case O_LIMIT: { /* limit number of sessions */ 1551 struct ipfw_flow_id id; 1552 ipfw_dyn_rule *parent; 1553 uint32_t conn_limit; 1554 uint16_t limit_mask = cmd->limit_mask; 1555 1556 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ? 1557 tablearg : cmd->conn_limit; 1558 1559 DEB( 1560 if (cmd->conn_limit == IP_FW_TABLEARG) 1561 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u " 1562 "(tablearg)\n", __func__, conn_limit); 1563 else 1564 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n", 1565 __func__, conn_limit); 1566 ) 1567 1568 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0; 1569 id.proto = args->f_id.proto; 1570 id.addr_type = args->f_id.addr_type; 1571 id.fib = M_GETFIB(args->m); 1572 1573 if (IS_IP6_FLOW_ID (&(args->f_id))) { 1574 if (limit_mask & DYN_SRC_ADDR) 1575 id.src_ip6 = args->f_id.src_ip6; 1576 if (limit_mask & DYN_DST_ADDR) 1577 id.dst_ip6 = args->f_id.dst_ip6; 1578 } else { 1579 if (limit_mask & DYN_SRC_ADDR) 1580 id.src_ip = args->f_id.src_ip; 1581 if (limit_mask & DYN_DST_ADDR) 1582 id.dst_ip = args->f_id.dst_ip; 1583 } 1584 if (limit_mask & DYN_SRC_PORT) 1585 id.src_port = args->f_id.src_port; 1586 if (limit_mask & DYN_DST_PORT) 1587 id.dst_port = args->f_id.dst_port; 1588 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) { 1589 printf("ipfw: %s: add parent failed\n", __func__); 1590 IPFW_DYN_UNLOCK(); 1591 return (1); 1592 } 1593 1594 if (parent->count >= conn_limit) { 1595 /* See if we can remove some expired rule. */ 1596 remove_dyn_rule(rule, parent); 1597 if (parent->count >= conn_limit) { 1598 if (V_fw_verbose && last_log != time_uptime) { 1599 last_log = time_uptime; 1600#ifdef INET6 1601 /* 1602 * XXX IPv6 flows are not 1603 * supported yet. 1604 */ 1605 if (IS_IP6_FLOW_ID(&(args->f_id))) { 1606 char ip6buf[INET6_ADDRSTRLEN]; 1607 snprintf(src, sizeof(src), 1608 "[%s]", ip6_sprintf(ip6buf, 1609 &args->f_id.src_ip6)); 1610 snprintf(dst, sizeof(dst), 1611 "[%s]", ip6_sprintf(ip6buf, 1612 &args->f_id.dst_ip6)); 1613 } else 1614#endif 1615 { 1616 da.s_addr = 1617 htonl(args->f_id.src_ip); 1618 inet_ntoa_r(da, src); 1619 da.s_addr = 1620 htonl(args->f_id.dst_ip); 1621 inet_ntoa_r(da, dst); 1622 } 1623 log(LOG_SECURITY | LOG_DEBUG, 1624 "ipfw: %d %s %s:%u -> %s:%u, %s\n", 1625 parent->rule->rulenum, 1626 "drop session", 1627 src, (args->f_id.src_port), 1628 dst, (args->f_id.dst_port), 1629 "too many entries"); 1630 } 1631 IPFW_DYN_UNLOCK(); 1632 return (1); 1633 } 1634 } 1635 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent); 1636 break; 1637 } 1638 default: 1639 printf("ipfw: %s: unknown dynamic rule type %u\n", 1640 __func__, cmd->o.opcode); 1641 IPFW_DYN_UNLOCK(); 1642 return (1); 1643 } 1644 1645 /* XXX just set lifetime */ 1646 lookup_dyn_rule_locked(&args->f_id, NULL, NULL); 1647 1648 IPFW_DYN_UNLOCK(); 1649 return (0); 1650} 1651 1652/* 1653 * Generate a TCP packet, containing either a RST or a keepalive. 1654 * When flags & TH_RST, we are sending a RST packet, because of a 1655 * "reset" action matched the packet. 1656 * Otherwise we are sending a keepalive, and flags & TH_ 1657 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required 1658 * so that MAC can label the reply appropriately. 1659 */ 1660static struct mbuf * 1661send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq, 1662 u_int32_t ack, int flags) 1663{ 1664 struct mbuf *m; 1665 int len, dir; 1666 struct ip *h = NULL; /* stupid compiler */ 1667#ifdef INET6 1668 struct ip6_hdr *h6 = NULL; 1669#endif 1670 struct tcphdr *th = NULL; 1671 1672 MGETHDR(m, M_DONTWAIT, MT_DATA); 1673 if (m == NULL) 1674 return (NULL); 1675 1676 M_SETFIB(m, id->fib); 1677#ifdef MAC 1678 if (replyto != NULL) 1679 mac_netinet_firewall_reply(replyto, m); 1680 else 1681 mac_netinet_firewall_send(m); 1682#else 1683 (void)replyto; /* don't warn about unused arg */ 1684#endif 1685 1686 switch (id->addr_type) { 1687 case 4: 1688 len = sizeof(struct ip) + sizeof(struct tcphdr); 1689 break; 1690#ifdef INET6 1691 case 6: 1692 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 1693 break; 1694#endif 1695 default: 1696 /* XXX: log me?!? */ 1697 m_freem(m); 1698 return (NULL); 1699 } 1700 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN); 1701 1702 m->m_data += max_linkhdr; 1703 m->m_flags |= M_SKIP_FIREWALL; 1704 m->m_pkthdr.len = m->m_len = len; 1705 m->m_pkthdr.rcvif = NULL; 1706 bzero(m->m_data, len); 1707 1708 switch (id->addr_type) { 1709 case 4: 1710 h = mtod(m, struct ip *); 1711 1712 /* prepare for checksum */ 1713 h->ip_p = IPPROTO_TCP; 1714 h->ip_len = htons(sizeof(struct tcphdr)); 1715 if (dir) { 1716 h->ip_src.s_addr = htonl(id->src_ip); 1717 h->ip_dst.s_addr = htonl(id->dst_ip); 1718 } else { 1719 h->ip_src.s_addr = htonl(id->dst_ip); 1720 h->ip_dst.s_addr = htonl(id->src_ip); 1721 } 1722 1723 th = (struct tcphdr *)(h + 1); 1724 break; 1725#ifdef INET6 1726 case 6: 1727 h6 = mtod(m, struct ip6_hdr *); 1728 1729 /* prepare for checksum */ 1730 h6->ip6_nxt = IPPROTO_TCP; 1731 h6->ip6_plen = htons(sizeof(struct tcphdr)); 1732 if (dir) { 1733 h6->ip6_src = id->src_ip6; 1734 h6->ip6_dst = id->dst_ip6; 1735 } else { 1736 h6->ip6_src = id->dst_ip6; 1737 h6->ip6_dst = id->src_ip6; 1738 } 1739 1740 th = (struct tcphdr *)(h6 + 1); 1741 break; 1742#endif 1743 } 1744 1745 if (dir) { 1746 th->th_sport = htons(id->src_port); 1747 th->th_dport = htons(id->dst_port); 1748 } else { 1749 th->th_sport = htons(id->dst_port); 1750 th->th_dport = htons(id->src_port); 1751 } 1752 th->th_off = sizeof(struct tcphdr) >> 2; 1753 1754 if (flags & TH_RST) { 1755 if (flags & TH_ACK) { 1756 th->th_seq = htonl(ack); 1757 th->th_flags = TH_RST; 1758 } else { 1759 if (flags & TH_SYN) 1760 seq++; 1761 th->th_ack = htonl(seq); 1762 th->th_flags = TH_RST | TH_ACK; 1763 } 1764 } else { 1765 /* 1766 * Keepalive - use caller provided sequence numbers 1767 */ 1768 th->th_seq = htonl(seq); 1769 th->th_ack = htonl(ack); 1770 th->th_flags = TH_ACK; 1771 } 1772 1773 switch (id->addr_type) { 1774 case 4: 1775 th->th_sum = in_cksum(m, len); 1776 1777 /* finish the ip header */ 1778 h->ip_v = 4; 1779 h->ip_hl = sizeof(*h) >> 2; 1780 h->ip_tos = IPTOS_LOWDELAY; 1781 h->ip_off = 0; 1782 h->ip_len = len; 1783 h->ip_ttl = V_ip_defttl; 1784 h->ip_sum = 0; 1785 break; 1786#ifdef INET6 1787 case 6: 1788 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6), 1789 sizeof(struct tcphdr)); 1790 1791 /* finish the ip6 header */ 1792 h6->ip6_vfc |= IPV6_VERSION; 1793 h6->ip6_hlim = IPV6_DEFHLIM; 1794 break; 1795#endif 1796 } 1797 1798 return (m); 1799} 1800 1801/* 1802 * sends a reject message, consuming the mbuf passed as an argument. 1803 */ 1804static void 1805send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip) 1806{ 1807 1808#if 0 1809 /* XXX When ip is not guaranteed to be at mtod() we will 1810 * need to account for this */ 1811 * The mbuf will however be thrown away so we can adjust it. 1812 * Remember we did an m_pullup on it already so we 1813 * can make some assumptions about contiguousness. 1814 */ 1815 if (args->L3offset) 1816 m_adj(m, args->L3offset); 1817#endif 1818 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */ 1819 /* We need the IP header in host order for icmp_error(). */ 1820 if (args->eh != NULL) { 1821 ip->ip_len = ntohs(ip->ip_len); 1822 ip->ip_off = ntohs(ip->ip_off); 1823 } 1824 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0); 1825 } else if (args->f_id.proto == IPPROTO_TCP) { 1826 struct tcphdr *const tcp = 1827 L3HDR(struct tcphdr, mtod(args->m, struct ip *)); 1828 if ( (tcp->th_flags & TH_RST) == 0) { 1829 struct mbuf *m; 1830 m = send_pkt(args->m, &(args->f_id), 1831 ntohl(tcp->th_seq), ntohl(tcp->th_ack), 1832 tcp->th_flags | TH_RST); 1833 if (m != NULL) 1834 ip_output(m, NULL, NULL, 0, NULL, NULL); 1835 } 1836 m_freem(args->m); 1837 } else 1838 m_freem(args->m); 1839 args->m = NULL; 1840} 1841 1842/** 1843 * 1844 * Given an ip_fw *, lookup_next_rule will return a pointer 1845 * to the next rule, which can be either the jump 1846 * target (for skipto instructions) or the next one in the list (in 1847 * all other cases including a missing jump target). 1848 * The result is also written in the "next_rule" field of the rule. 1849 * Backward jumps are not allowed, so start looking from the next 1850 * rule... 1851 * 1852 * This never returns NULL -- in case we do not have an exact match, 1853 * the next rule is returned. When the ruleset is changed, 1854 * pointers are flushed so we are always correct. 1855 */ 1856 1857static struct ip_fw * 1858lookup_next_rule(struct ip_fw *me, u_int32_t tablearg) 1859{ 1860 struct ip_fw *rule = NULL; 1861 ipfw_insn *cmd; 1862 u_int16_t rulenum; 1863 1864 /* look for action, in case it is a skipto */ 1865 cmd = ACTION_PTR(me); 1866 if (cmd->opcode == O_LOG) 1867 cmd += F_LEN(cmd); 1868 if (cmd->opcode == O_ALTQ) 1869 cmd += F_LEN(cmd); 1870 if (cmd->opcode == O_TAG) 1871 cmd += F_LEN(cmd); 1872 if (cmd->opcode == O_SKIPTO ) { 1873 if (tablearg != 0) { 1874 rulenum = (u_int16_t)tablearg; 1875 } else { 1876 rulenum = cmd->arg1; 1877 } 1878 for (rule = me->next; rule ; rule = rule->next) { 1879 if (rule->rulenum >= rulenum) { 1880 break; 1881 } 1882 } 1883 } 1884 if (rule == NULL) /* failure or not a skipto */ 1885 rule = me->next; 1886 me->next_rule = rule; 1887 return rule; 1888} 1889 1890static int 1891add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 1892 uint8_t mlen, uint32_t value) 1893{ 1894 struct radix_node_head *rnh; 1895 struct table_entry *ent; 1896 struct radix_node *rn; 1897 1898 if (tbl >= IPFW_TABLES_MAX) 1899 return (EINVAL); 1900 rnh = ch->tables[tbl]; 1901 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO); 1902 if (ent == NULL) 1903 return (ENOMEM); 1904 ent->value = value; 1905 ent->addr.sin_len = ent->mask.sin_len = 8; 1906 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0); 1907 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr; 1908 IPFW_WLOCK(ch); 1909 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent); 1910 if (rn == NULL) { 1911 IPFW_WUNLOCK(ch); 1912 free(ent, M_IPFW_TBL); 1913 return (EEXIST); 1914 } 1915 IPFW_WUNLOCK(ch); 1916 return (0); 1917} 1918 1919static int 1920del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 1921 uint8_t mlen) 1922{ 1923 struct radix_node_head *rnh; 1924 struct table_entry *ent; 1925 struct sockaddr_in sa, mask; 1926 1927 if (tbl >= IPFW_TABLES_MAX) 1928 return (EINVAL); 1929 rnh = ch->tables[tbl]; 1930 sa.sin_len = mask.sin_len = 8; 1931 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0); 1932 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr; 1933 IPFW_WLOCK(ch); 1934 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh); 1935 if (ent == NULL) { 1936 IPFW_WUNLOCK(ch); 1937 return (ESRCH); 1938 } 1939 IPFW_WUNLOCK(ch); 1940 free(ent, M_IPFW_TBL); 1941 return (0); 1942} 1943 1944static int 1945flush_table_entry(struct radix_node *rn, void *arg) 1946{ 1947 struct radix_node_head * const rnh = arg; 1948 struct table_entry *ent; 1949 1950 ent = (struct table_entry *) 1951 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh); 1952 if (ent != NULL) 1953 free(ent, M_IPFW_TBL); 1954 return (0); 1955} 1956 1957static int 1958flush_table(struct ip_fw_chain *ch, uint16_t tbl) 1959{ 1960 struct radix_node_head *rnh; 1961 1962 IPFW_WLOCK_ASSERT(ch); 1963 1964 if (tbl >= IPFW_TABLES_MAX) 1965 return (EINVAL); 1966 rnh = ch->tables[tbl]; 1967 KASSERT(rnh != NULL, ("NULL IPFW table")); 1968 rnh->rnh_walktree(rnh, flush_table_entry, rnh); 1969 return (0); 1970} 1971 1972static void 1973flush_tables(struct ip_fw_chain *ch) 1974{ 1975 uint16_t tbl; 1976 1977 IPFW_WLOCK_ASSERT(ch); 1978 1979 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++) 1980 flush_table(ch, tbl); 1981} 1982 1983static int 1984init_tables(struct ip_fw_chain *ch) 1985{ 1986 int i; 1987 uint16_t j; 1988 1989 for (i = 0; i < IPFW_TABLES_MAX; i++) { 1990 if (!rn_inithead((void **)&ch->tables[i], 32)) { 1991 for (j = 0; j < i; j++) { 1992 (void) flush_table(ch, j); 1993 } 1994 return (ENOMEM); 1995 } 1996 } 1997 return (0); 1998} 1999 2000static int 2001lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr, 2002 uint32_t *val) 2003{ 2004 struct radix_node_head *rnh; 2005 struct table_entry *ent; 2006 struct sockaddr_in sa; 2007 2008 if (tbl >= IPFW_TABLES_MAX) 2009 return (0); 2010 rnh = ch->tables[tbl]; 2011 sa.sin_len = 8; 2012 sa.sin_addr.s_addr = addr; 2013 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh)); 2014 if (ent != NULL) { 2015 *val = ent->value; 2016 return (1); 2017 } 2018 return (0); 2019} 2020 2021static int 2022count_table_entry(struct radix_node *rn, void *arg) 2023{ 2024 u_int32_t * const cnt = arg; 2025 2026 (*cnt)++; 2027 return (0); 2028} 2029 2030static int 2031count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt) 2032{ 2033 struct radix_node_head *rnh; 2034 2035 if (tbl >= IPFW_TABLES_MAX) 2036 return (EINVAL); 2037 rnh = ch->tables[tbl]; 2038 *cnt = 0; 2039 rnh->rnh_walktree(rnh, count_table_entry, cnt); 2040 return (0); 2041} 2042 2043static int 2044dump_table_entry(struct radix_node *rn, void *arg) 2045{ 2046 struct table_entry * const n = (struct table_entry *)rn; 2047 ipfw_table * const tbl = arg; 2048 ipfw_table_entry *ent; 2049 2050 if (tbl->cnt == tbl->size) 2051 return (1); 2052 ent = &tbl->ent[tbl->cnt]; 2053 ent->tbl = tbl->tbl; 2054 if (in_nullhost(n->mask.sin_addr)) 2055 ent->masklen = 0; 2056 else 2057 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr)); 2058 ent->addr = n->addr.sin_addr.s_addr; 2059 ent->value = n->value; 2060 tbl->cnt++; 2061 return (0); 2062} 2063 2064static int 2065dump_table(struct ip_fw_chain *ch, ipfw_table *tbl) 2066{ 2067 struct radix_node_head *rnh; 2068 2069 if (tbl->tbl >= IPFW_TABLES_MAX) 2070 return (EINVAL); 2071 rnh = ch->tables[tbl->tbl]; 2072 tbl->cnt = 0; 2073 rnh->rnh_walktree(rnh, dump_table_entry, tbl); 2074 return (0); 2075} 2076 2077static int 2078check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif, 2079 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip, 2080 u_int16_t src_port, struct ucred **uc, int *ugid_lookupp, 2081 struct inpcb *inp) 2082{ 2083 struct inpcbinfo *pi; 2084 int wildcard; 2085 struct inpcb *pcb; 2086 int match; 2087 2088 /* 2089 * Check to see if the UDP or TCP stack supplied us with 2090 * the PCB. If so, rather then holding a lock and looking 2091 * up the PCB, we can use the one that was supplied. 2092 */ 2093 if (inp && *ugid_lookupp == 0) { 2094 INP_LOCK_ASSERT(inp); 2095 if (inp->inp_socket != NULL) { 2096 *uc = crhold(inp->inp_cred); 2097 *ugid_lookupp = 1; 2098 } else 2099 *ugid_lookupp = -1; 2100 } 2101 /* 2102 * If we have already been here and the packet has no 2103 * PCB entry associated with it, then we can safely 2104 * assume that this is a no match. 2105 */ 2106 if (*ugid_lookupp == -1) 2107 return (0); 2108 if (proto == IPPROTO_TCP) { 2109 wildcard = 0; 2110 pi = &V_tcbinfo; 2111 } else if (proto == IPPROTO_UDP) { 2112 wildcard = INPLOOKUP_WILDCARD; 2113 pi = &V_udbinfo; 2114 } else 2115 return 0; 2116 match = 0; 2117 if (*ugid_lookupp == 0) { 2118 INP_INFO_RLOCK(pi); 2119 pcb = (oif) ? 2120 in_pcblookup_hash(pi, 2121 dst_ip, htons(dst_port), 2122 src_ip, htons(src_port), 2123 wildcard, oif) : 2124 in_pcblookup_hash(pi, 2125 src_ip, htons(src_port), 2126 dst_ip, htons(dst_port), 2127 wildcard, NULL); 2128 if (pcb != NULL) { 2129 *uc = crhold(pcb->inp_cred); 2130 *ugid_lookupp = 1; 2131 } 2132 INP_INFO_RUNLOCK(pi); 2133 if (*ugid_lookupp == 0) { 2134 /* 2135 * If the lookup did not yield any results, there 2136 * is no sense in coming back and trying again. So 2137 * we can set lookup to -1 and ensure that we wont 2138 * bother the pcb system again. 2139 */ 2140 *ugid_lookupp = -1; 2141 return (0); 2142 } 2143 } 2144 if (insn->o.opcode == O_UID) 2145 match = ((*uc)->cr_uid == (uid_t)insn->d[0]); 2146 else if (insn->o.opcode == O_GID) 2147 match = groupmember((gid_t)insn->d[0], *uc); 2148 else if (insn->o.opcode == O_JAIL) 2149 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]); 2150 return match; 2151} 2152 2153/* 2154 * The main check routine for the firewall. 2155 * 2156 * All arguments are in args so we can modify them and return them 2157 * back to the caller. 2158 * 2159 * Parameters: 2160 * 2161 * args->m (in/out) The packet; we set to NULL when/if we nuke it. 2162 * Starts with the IP header. 2163 * args->eh (in) Mac header if present, or NULL for layer3 packet. 2164 * args->L3offset Number of bytes bypassed if we came from L2. 2165 * e.g. often sizeof(eh) ** NOTYET ** 2166 * args->oif Outgoing interface, or NULL if packet is incoming. 2167 * The incoming interface is in the mbuf. (in) 2168 * args->divert_rule (in/out) 2169 * Skip up to the first rule past this rule number; 2170 * upon return, non-zero port number for divert or tee. 2171 * 2172 * args->rule Pointer to the last matching rule (in/out) 2173 * args->next_hop Socket we are forwarding to (out). 2174 * args->f_id Addresses grabbed from the packet (out) 2175 * args->cookie a cookie depending on rule action 2176 * 2177 * Return value: 2178 * 2179 * IP_FW_PASS the packet must be accepted 2180 * IP_FW_DENY the packet must be dropped 2181 * IP_FW_DIVERT divert packet, port in m_tag 2182 * IP_FW_TEE tee packet, port in m_tag 2183 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie 2184 * IP_FW_NETGRAPH into netgraph, cookie args->cookie 2185 * 2186 */ 2187int 2188ipfw_chk(struct ip_fw_args *args) 2189{ 2190 2191 /* 2192 * Local variables holding state during the processing of a packet: 2193 * 2194 * IMPORTANT NOTE: to speed up the processing of rules, there 2195 * are some assumption on the values of the variables, which 2196 * are documented here. Should you change them, please check 2197 * the implementation of the various instructions to make sure 2198 * that they still work. 2199 * 2200 * args->eh The MAC header. It is non-null for a layer2 2201 * packet, it is NULL for a layer-3 packet. 2202 * **notyet** 2203 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header. 2204 * 2205 * m | args->m Pointer to the mbuf, as received from the caller. 2206 * It may change if ipfw_chk() does an m_pullup, or if it 2207 * consumes the packet because it calls send_reject(). 2208 * XXX This has to change, so that ipfw_chk() never modifies 2209 * or consumes the buffer. 2210 * ip is the beginning of the ip(4 or 6) header. 2211 * Calculated by adding the L3offset to the start of data. 2212 * (Until we start using L3offset, the packet is 2213 * supposed to start with the ip header). 2214 */ 2215 struct mbuf *m = args->m; 2216 struct ip *ip = mtod(m, struct ip *); 2217 2218 /* 2219 * For rules which contain uid/gid or jail constraints, cache 2220 * a copy of the users credentials after the pcb lookup has been 2221 * executed. This will speed up the processing of rules with 2222 * these types of constraints, as well as decrease contention 2223 * on pcb related locks. 2224 */ 2225 struct ucred *ucred_cache = NULL; 2226 int ucred_lookup = 0; 2227 2228 /* 2229 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG 2230 * associated with a packet input on a divert socket. This 2231 * will allow to distinguish traffic and its direction when 2232 * it originates from a divert socket. 2233 */ 2234 u_int divinput_flags = 0; 2235 2236 /* 2237 * oif | args->oif If NULL, ipfw_chk has been called on the 2238 * inbound path (ether_input, ip_input). 2239 * If non-NULL, ipfw_chk has been called on the outbound path 2240 * (ether_output, ip_output). 2241 */ 2242 struct ifnet *oif = args->oif; 2243 2244 struct ip_fw *f = NULL; /* matching rule */ 2245 int retval = 0; 2246 2247 /* 2248 * hlen The length of the IP header. 2249 */ 2250 u_int hlen = 0; /* hlen >0 means we have an IP pkt */ 2251 2252 /* 2253 * offset The offset of a fragment. offset != 0 means that 2254 * we have a fragment at this offset of an IPv4 packet. 2255 * offset == 0 means that (if this is an IPv4 packet) 2256 * this is the first or only fragment. 2257 * For IPv6 offset == 0 means there is no Fragment Header. 2258 * If offset != 0 for IPv6 always use correct mask to 2259 * get the correct offset because we add IP6F_MORE_FRAG 2260 * to be able to dectect the first fragment which would 2261 * otherwise have offset = 0. 2262 */ 2263 u_short offset = 0; 2264 2265 /* 2266 * Local copies of addresses. They are only valid if we have 2267 * an IP packet. 2268 * 2269 * proto The protocol. Set to 0 for non-ip packets, 2270 * or to the protocol read from the packet otherwise. 2271 * proto != 0 means that we have an IPv4 packet. 2272 * 2273 * src_port, dst_port port numbers, in HOST format. Only 2274 * valid for TCP and UDP packets. 2275 * 2276 * src_ip, dst_ip ip addresses, in NETWORK format. 2277 * Only valid for IPv4 packets. 2278 */ 2279 u_int8_t proto; 2280 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */ 2281 struct in_addr src_ip, dst_ip; /* NOTE: network format */ 2282 u_int16_t ip_len=0; 2283 int pktlen; 2284 u_int16_t etype = 0; /* Host order stored ether type */ 2285 2286 /* 2287 * dyn_dir = MATCH_UNKNOWN when rules unchecked, 2288 * MATCH_NONE when checked and not matched (q = NULL), 2289 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL) 2290 */ 2291 int dyn_dir = MATCH_UNKNOWN; 2292 ipfw_dyn_rule *q = NULL; 2293 struct ip_fw_chain *chain = &V_layer3_chain; 2294 struct m_tag *mtag; 2295 2296 /* 2297 * We store in ulp a pointer to the upper layer protocol header. 2298 * In the ipv4 case this is easy to determine from the header, 2299 * but for ipv6 we might have some additional headers in the middle. 2300 * ulp is NULL if not found. 2301 */ 2302 void *ulp = NULL; /* upper layer protocol pointer. */ 2303 /* XXX ipv6 variables */ 2304 int is_ipv6 = 0; 2305 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */ 2306 /* end of ipv6 variables */ 2307 int is_ipv4 = 0; 2308 2309 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready)) 2310 return (IP_FW_PASS); /* accept */ 2311 2312 dst_ip.s_addr = 0; /* make sure it is initialized */ 2313 src_ip.s_addr = 0; /* make sure it is initialized */ 2314 pktlen = m->m_pkthdr.len; 2315 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */ 2316 proto = args->f_id.proto = 0; /* mark f_id invalid */ 2317 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */ 2318 2319/* 2320 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous, 2321 * then it sets p to point at the offset "len" in the mbuf. WARNING: the 2322 * pointer might become stale after other pullups (but we never use it 2323 * this way). 2324 */ 2325#define PULLUP_TO(_len, p, T) \ 2326do { \ 2327 int x = (_len) + sizeof(T); \ 2328 if ((m)->m_len < x) { \ 2329 args->m = m = m_pullup(m, x); \ 2330 if (m == NULL) \ 2331 goto pullup_failed; \ 2332 } \ 2333 p = (mtod(m, char *) + (_len)); \ 2334} while (0) 2335 2336 /* 2337 * if we have an ether header, 2338 */ 2339 if (args->eh) 2340 etype = ntohs(args->eh->ether_type); 2341 2342 /* Identify IP packets and fill up variables. */ 2343 if (pktlen >= sizeof(struct ip6_hdr) && 2344 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) { 2345 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip; 2346 is_ipv6 = 1; 2347 args->f_id.addr_type = 6; 2348 hlen = sizeof(struct ip6_hdr); 2349 proto = ip6->ip6_nxt; 2350 2351 /* Search extension headers to find upper layer protocols */ 2352 while (ulp == NULL) { 2353 switch (proto) { 2354 case IPPROTO_ICMPV6: 2355 PULLUP_TO(hlen, ulp, struct icmp6_hdr); 2356 args->f_id.flags = ICMP6(ulp)->icmp6_type; 2357 break; 2358 2359 case IPPROTO_TCP: 2360 PULLUP_TO(hlen, ulp, struct tcphdr); 2361 dst_port = TCP(ulp)->th_dport; 2362 src_port = TCP(ulp)->th_sport; 2363 args->f_id.flags = TCP(ulp)->th_flags; 2364 break; 2365 2366 case IPPROTO_SCTP: 2367 PULLUP_TO(hlen, ulp, struct sctphdr); 2368 src_port = SCTP(ulp)->src_port; 2369 dst_port = SCTP(ulp)->dest_port; 2370 break; 2371 2372 case IPPROTO_UDP: 2373 PULLUP_TO(hlen, ulp, struct udphdr); 2374 dst_port = UDP(ulp)->uh_dport; 2375 src_port = UDP(ulp)->uh_sport; 2376 break; 2377 2378 case IPPROTO_HOPOPTS: /* RFC 2460 */ 2379 PULLUP_TO(hlen, ulp, struct ip6_hbh); 2380 ext_hd |= EXT_HOPOPTS; 2381 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3; 2382 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt; 2383 ulp = NULL; 2384 break; 2385 2386 case IPPROTO_ROUTING: /* RFC 2460 */ 2387 PULLUP_TO(hlen, ulp, struct ip6_rthdr); 2388 switch (((struct ip6_rthdr *)ulp)->ip6r_type) { 2389 case 0: 2390 ext_hd |= EXT_RTHDR0; 2391 break; 2392 case 2: 2393 ext_hd |= EXT_RTHDR2; 2394 break; 2395 default: 2396 printf("IPFW2: IPV6 - Unknown Routing " 2397 "Header type(%d)\n", 2398 ((struct ip6_rthdr *)ulp)->ip6r_type); 2399 if (V_fw_deny_unknown_exthdrs) 2400 return (IP_FW_DENY); 2401 break; 2402 } 2403 ext_hd |= EXT_ROUTING; 2404 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3; 2405 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt; 2406 ulp = NULL; 2407 break; 2408 2409 case IPPROTO_FRAGMENT: /* RFC 2460 */ 2410 PULLUP_TO(hlen, ulp, struct ip6_frag); 2411 ext_hd |= EXT_FRAGMENT; 2412 hlen += sizeof (struct ip6_frag); 2413 proto = ((struct ip6_frag *)ulp)->ip6f_nxt; 2414 offset = ((struct ip6_frag *)ulp)->ip6f_offlg & 2415 IP6F_OFF_MASK; 2416 /* Add IP6F_MORE_FRAG for offset of first 2417 * fragment to be != 0. */ 2418 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg & 2419 IP6F_MORE_FRAG; 2420 if (offset == 0) { 2421 printf("IPFW2: IPV6 - Invalid Fragment " 2422 "Header\n"); 2423 if (V_fw_deny_unknown_exthdrs) 2424 return (IP_FW_DENY); 2425 break; 2426 } 2427 args->f_id.frag_id6 = 2428 ntohl(((struct ip6_frag *)ulp)->ip6f_ident); 2429 ulp = NULL; 2430 break; 2431 2432 case IPPROTO_DSTOPTS: /* RFC 2460 */ 2433 PULLUP_TO(hlen, ulp, struct ip6_hbh); 2434 ext_hd |= EXT_DSTOPTS; 2435 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3; 2436 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt; 2437 ulp = NULL; 2438 break; 2439 2440 case IPPROTO_AH: /* RFC 2402 */ 2441 PULLUP_TO(hlen, ulp, struct ip6_ext); 2442 ext_hd |= EXT_AH; 2443 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2; 2444 proto = ((struct ip6_ext *)ulp)->ip6e_nxt; 2445 ulp = NULL; 2446 break; 2447 2448 case IPPROTO_ESP: /* RFC 2406 */ 2449 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */ 2450 /* Anything past Seq# is variable length and 2451 * data past this ext. header is encrypted. */ 2452 ext_hd |= EXT_ESP; 2453 break; 2454 2455 case IPPROTO_NONE: /* RFC 2460 */ 2456 /* 2457 * Packet ends here, and IPv6 header has 2458 * already been pulled up. If ip6e_len!=0 2459 * then octets must be ignored. 2460 */ 2461 ulp = ip; /* non-NULL to get out of loop. */ 2462 break; 2463 2464 case IPPROTO_OSPFIGP: 2465 /* XXX OSPF header check? */ 2466 PULLUP_TO(hlen, ulp, struct ip6_ext); 2467 break; 2468 2469 case IPPROTO_PIM: 2470 /* XXX PIM header check? */ 2471 PULLUP_TO(hlen, ulp, struct pim); 2472 break; 2473 2474 case IPPROTO_CARP: 2475 PULLUP_TO(hlen, ulp, struct carp_header); 2476 if (((struct carp_header *)ulp)->carp_version != 2477 CARP_VERSION) 2478 return (IP_FW_DENY); 2479 if (((struct carp_header *)ulp)->carp_type != 2480 CARP_ADVERTISEMENT) 2481 return (IP_FW_DENY); 2482 break; 2483 2484 case IPPROTO_IPV6: /* RFC 2893 */ 2485 PULLUP_TO(hlen, ulp, struct ip6_hdr); 2486 break; 2487 2488 case IPPROTO_IPV4: /* RFC 2893 */ 2489 PULLUP_TO(hlen, ulp, struct ip); 2490 break; 2491 2492 default: 2493 printf("IPFW2: IPV6 - Unknown Extension " 2494 "Header(%d), ext_hd=%x\n", proto, ext_hd); 2495 if (V_fw_deny_unknown_exthdrs) 2496 return (IP_FW_DENY); 2497 PULLUP_TO(hlen, ulp, struct ip6_ext); 2498 break; 2499 } /*switch */ 2500 } 2501 ip = mtod(m, struct ip *); 2502 ip6 = (struct ip6_hdr *)ip; 2503 args->f_id.src_ip6 = ip6->ip6_src; 2504 args->f_id.dst_ip6 = ip6->ip6_dst; 2505 args->f_id.src_ip = 0; 2506 args->f_id.dst_ip = 0; 2507 args->f_id.flow_id6 = ntohl(ip6->ip6_flow); 2508 } else if (pktlen >= sizeof(struct ip) && 2509 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) { 2510 is_ipv4 = 1; 2511 hlen = ip->ip_hl << 2; 2512 args->f_id.addr_type = 4; 2513 2514 /* 2515 * Collect parameters into local variables for faster matching. 2516 */ 2517 proto = ip->ip_p; 2518 src_ip = ip->ip_src; 2519 dst_ip = ip->ip_dst; 2520 if (args->eh != NULL) { /* layer 2 packets are as on the wire */ 2521 offset = ntohs(ip->ip_off) & IP_OFFMASK; 2522 ip_len = ntohs(ip->ip_len); 2523 } else { 2524 offset = ip->ip_off & IP_OFFMASK; 2525 ip_len = ip->ip_len; 2526 } 2527 pktlen = ip_len < pktlen ? ip_len : pktlen; 2528 2529 if (offset == 0) { 2530 switch (proto) { 2531 case IPPROTO_TCP: 2532 PULLUP_TO(hlen, ulp, struct tcphdr); 2533 dst_port = TCP(ulp)->th_dport; 2534 src_port = TCP(ulp)->th_sport; 2535 args->f_id.flags = TCP(ulp)->th_flags; 2536 break; 2537 2538 case IPPROTO_UDP: 2539 PULLUP_TO(hlen, ulp, struct udphdr); 2540 dst_port = UDP(ulp)->uh_dport; 2541 src_port = UDP(ulp)->uh_sport; 2542 break; 2543 2544 case IPPROTO_ICMP: 2545 PULLUP_TO(hlen, ulp, struct icmphdr); 2546 args->f_id.flags = ICMP(ulp)->icmp_type; 2547 break; 2548 2549 default: 2550 break; 2551 } 2552 } 2553 2554 ip = mtod(m, struct ip *); 2555 args->f_id.src_ip = ntohl(src_ip.s_addr); 2556 args->f_id.dst_ip = ntohl(dst_ip.s_addr); 2557 } 2558#undef PULLUP_TO 2559 if (proto) { /* we may have port numbers, store them */ 2560 args->f_id.proto = proto; 2561 args->f_id.src_port = src_port = ntohs(src_port); 2562 args->f_id.dst_port = dst_port = ntohs(dst_port); 2563 } 2564 2565 IPFW_RLOCK(chain); 2566 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */ 2567 IPFW_RUNLOCK(chain); 2568 return (IP_FW_PASS); /* accept */ 2569 } 2570 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL); 2571 if (args->rule) { 2572 /* 2573 * Packet has already been tagged. Look for the next rule 2574 * to restart processing. Make sure that args->rule still 2575 * exists and not changed. 2576 */ 2577 if (chain->id != args->chain_id) { 2578 for (f = chain->rules; f != NULL; f = f->next) 2579 if (f == args->rule && f->id == args->rule_id) 2580 break; 2581 2582 if (f != NULL) 2583 f = f->next_rule; 2584 else 2585 f = ip_fw_default_rule; 2586 } else 2587 f = args->rule->next_rule; 2588 2589 if (f == NULL) 2590 f = lookup_next_rule(args->rule, 0); 2591 } else { 2592 /* 2593 * Find the starting rule. It can be either the first 2594 * one, or the one after divert_rule if asked so. 2595 */ 2596 int skipto = mtag ? divert_cookie(mtag) : 0; 2597 2598 f = chain->rules; 2599 if (args->eh == NULL && skipto != 0) { 2600 if (skipto >= IPFW_DEFAULT_RULE) { 2601 IPFW_RUNLOCK(chain); 2602 return (IP_FW_DENY); /* invalid */ 2603 } 2604 while (f && f->rulenum <= skipto) 2605 f = f->next; 2606 if (f == NULL) { /* drop packet */ 2607 IPFW_RUNLOCK(chain); 2608 return (IP_FW_DENY); 2609 } 2610 } 2611 } 2612 /* reset divert rule to avoid confusion later */ 2613 if (mtag) { 2614 divinput_flags = divert_info(mtag) & 2615 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG); 2616 m_tag_delete(m, mtag); 2617 } 2618 2619 /* 2620 * Now scan the rules, and parse microinstructions for each rule. 2621 */ 2622 for (; f; f = f->next) { 2623 ipfw_insn *cmd; 2624 uint32_t tablearg = 0; 2625 int l, cmdlen, skip_or; /* skip rest of OR block */ 2626 2627again: 2628 if (V_set_disable & (1 << f->set) ) 2629 continue; 2630 2631 skip_or = 0; 2632 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ; 2633 l -= cmdlen, cmd += cmdlen) { 2634 int match; 2635 2636 /* 2637 * check_body is a jump target used when we find a 2638 * CHECK_STATE, and need to jump to the body of 2639 * the target rule. 2640 */ 2641 2642check_body: 2643 cmdlen = F_LEN(cmd); 2644 /* 2645 * An OR block (insn_1 || .. || insn_n) has the 2646 * F_OR bit set in all but the last instruction. 2647 * The first match will set "skip_or", and cause 2648 * the following instructions to be skipped until 2649 * past the one with the F_OR bit clear. 2650 */ 2651 if (skip_or) { /* skip this instruction */ 2652 if ((cmd->len & F_OR) == 0) 2653 skip_or = 0; /* next one is good */ 2654 continue; 2655 } 2656 match = 0; /* set to 1 if we succeed */ 2657 2658 switch (cmd->opcode) { 2659 /* 2660 * The first set of opcodes compares the packet's 2661 * fields with some pattern, setting 'match' if a 2662 * match is found. At the end of the loop there is 2663 * logic to deal with F_NOT and F_OR flags associated 2664 * with the opcode. 2665 */ 2666 case O_NOP: 2667 match = 1; 2668 break; 2669 2670 case O_FORWARD_MAC: 2671 printf("ipfw: opcode %d unimplemented\n", 2672 cmd->opcode); 2673 break; 2674 2675 case O_GID: 2676 case O_UID: 2677 case O_JAIL: 2678 /* 2679 * We only check offset == 0 && proto != 0, 2680 * as this ensures that we have a 2681 * packet with the ports info. 2682 */ 2683 if (offset!=0) 2684 break; 2685 if (is_ipv6) /* XXX to be fixed later */ 2686 break; 2687 if (proto == IPPROTO_TCP || 2688 proto == IPPROTO_UDP) 2689 match = check_uidgid( 2690 (ipfw_insn_u32 *)cmd, 2691 proto, oif, 2692 dst_ip, dst_port, 2693 src_ip, src_port, &ucred_cache, 2694 &ucred_lookup, args->inp); 2695 break; 2696 2697 case O_RECV: 2698 match = iface_match(m->m_pkthdr.rcvif, 2699 (ipfw_insn_if *)cmd); 2700 break; 2701 2702 case O_XMIT: 2703 match = iface_match(oif, (ipfw_insn_if *)cmd); 2704 break; 2705 2706 case O_VIA: 2707 match = iface_match(oif ? oif : 2708 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd); 2709 break; 2710 2711 case O_MACADDR2: 2712 if (args->eh != NULL) { /* have MAC header */ 2713 u_int32_t *want = (u_int32_t *) 2714 ((ipfw_insn_mac *)cmd)->addr; 2715 u_int32_t *mask = (u_int32_t *) 2716 ((ipfw_insn_mac *)cmd)->mask; 2717 u_int32_t *hdr = (u_int32_t *)args->eh; 2718 2719 match = 2720 ( want[0] == (hdr[0] & mask[0]) && 2721 want[1] == (hdr[1] & mask[1]) && 2722 want[2] == (hdr[2] & mask[2]) ); 2723 } 2724 break; 2725 2726 case O_MAC_TYPE: 2727 if (args->eh != NULL) { 2728 u_int16_t *p = 2729 ((ipfw_insn_u16 *)cmd)->ports; 2730 int i; 2731 2732 for (i = cmdlen - 1; !match && i>0; 2733 i--, p += 2) 2734 match = (etype >= p[0] && 2735 etype <= p[1]); 2736 } 2737 break; 2738 2739 case O_FRAG: 2740 match = (offset != 0); 2741 break; 2742 2743 case O_IN: /* "out" is "not in" */ 2744 match = (oif == NULL); 2745 break; 2746 2747 case O_LAYER2: 2748 match = (args->eh != NULL); 2749 break; 2750 2751 case O_DIVERTED: 2752 match = (cmd->arg1 & 1 && divinput_flags & 2753 IP_FW_DIVERT_LOOPBACK_FLAG) || 2754 (cmd->arg1 & 2 && divinput_flags & 2755 IP_FW_DIVERT_OUTPUT_FLAG); 2756 break; 2757 2758 case O_PROTO: 2759 /* 2760 * We do not allow an arg of 0 so the 2761 * check of "proto" only suffices. 2762 */ 2763 match = (proto == cmd->arg1); 2764 break; 2765 2766 case O_IP_SRC: 2767 match = is_ipv4 && 2768 (((ipfw_insn_ip *)cmd)->addr.s_addr == 2769 src_ip.s_addr); 2770 break; 2771 2772 case O_IP_SRC_LOOKUP: 2773 case O_IP_DST_LOOKUP: 2774 if (is_ipv4) { 2775 uint32_t a = 2776 (cmd->opcode == O_IP_DST_LOOKUP) ? 2777 dst_ip.s_addr : src_ip.s_addr; 2778 uint32_t v = 0; 2779 2780 match = lookup_table(chain, cmd->arg1, a, 2781 &v); 2782 if (!match) 2783 break; 2784 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) 2785 match = 2786 ((ipfw_insn_u32 *)cmd)->d[0] == v; 2787 else 2788 tablearg = v; 2789 } 2790 break; 2791 2792 case O_IP_SRC_MASK: 2793 case O_IP_DST_MASK: 2794 if (is_ipv4) { 2795 uint32_t a = 2796 (cmd->opcode == O_IP_DST_MASK) ? 2797 dst_ip.s_addr : src_ip.s_addr; 2798 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d; 2799 int i = cmdlen-1; 2800 2801 for (; !match && i>0; i-= 2, p+= 2) 2802 match = (p[0] == (a & p[1])); 2803 } 2804 break; 2805 2806 case O_IP_SRC_ME: 2807 if (is_ipv4) { 2808 struct ifnet *tif; 2809 2810 INADDR_TO_IFP(src_ip, tif); 2811 match = (tif != NULL); 2812 } 2813 break; 2814 2815 case O_IP_DST_SET: 2816 case O_IP_SRC_SET: 2817 if (is_ipv4) { 2818 u_int32_t *d = (u_int32_t *)(cmd+1); 2819 u_int32_t addr = 2820 cmd->opcode == O_IP_DST_SET ? 2821 args->f_id.dst_ip : 2822 args->f_id.src_ip; 2823 2824 if (addr < d[0]) 2825 break; 2826 addr -= d[0]; /* subtract base */ 2827 match = (addr < cmd->arg1) && 2828 ( d[ 1 + (addr>>5)] & 2829 (1<<(addr & 0x1f)) ); 2830 } 2831 break; 2832 2833 case O_IP_DST: 2834 match = is_ipv4 && 2835 (((ipfw_insn_ip *)cmd)->addr.s_addr == 2836 dst_ip.s_addr); 2837 break; 2838 2839 case O_IP_DST_ME: 2840 if (is_ipv4) { 2841 struct ifnet *tif; 2842 2843 INADDR_TO_IFP(dst_ip, tif); 2844 match = (tif != NULL); 2845 } 2846 break; 2847 2848 case O_IP_SRCPORT: 2849 case O_IP_DSTPORT: 2850 /* 2851 * offset == 0 && proto != 0 is enough 2852 * to guarantee that we have a 2853 * packet with port info. 2854 */ 2855 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP) 2856 && offset == 0) { 2857 u_int16_t x = 2858 (cmd->opcode == O_IP_SRCPORT) ? 2859 src_port : dst_port ; 2860 u_int16_t *p = 2861 ((ipfw_insn_u16 *)cmd)->ports; 2862 int i; 2863 2864 for (i = cmdlen - 1; !match && i>0; 2865 i--, p += 2) 2866 match = (x>=p[0] && x<=p[1]); 2867 } 2868 break; 2869 2870 case O_ICMPTYPE: 2871 match = (offset == 0 && proto==IPPROTO_ICMP && 2872 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) ); 2873 break; 2874 2875#ifdef INET6 2876 case O_ICMP6TYPE: 2877 match = is_ipv6 && offset == 0 && 2878 proto==IPPROTO_ICMPV6 && 2879 icmp6type_match( 2880 ICMP6(ulp)->icmp6_type, 2881 (ipfw_insn_u32 *)cmd); 2882 break; 2883#endif /* INET6 */ 2884 2885 case O_IPOPT: 2886 match = (is_ipv4 && 2887 ipopts_match(ip, cmd) ); 2888 break; 2889 2890 case O_IPVER: 2891 match = (is_ipv4 && 2892 cmd->arg1 == ip->ip_v); 2893 break; 2894 2895 case O_IPID: 2896 case O_IPLEN: 2897 case O_IPTTL: 2898 if (is_ipv4) { /* only for IP packets */ 2899 uint16_t x; 2900 uint16_t *p; 2901 int i; 2902 2903 if (cmd->opcode == O_IPLEN) 2904 x = ip_len; 2905 else if (cmd->opcode == O_IPTTL) 2906 x = ip->ip_ttl; 2907 else /* must be IPID */ 2908 x = ntohs(ip->ip_id); 2909 if (cmdlen == 1) { 2910 match = (cmd->arg1 == x); 2911 break; 2912 } 2913 /* otherwise we have ranges */ 2914 p = ((ipfw_insn_u16 *)cmd)->ports; 2915 i = cmdlen - 1; 2916 for (; !match && i>0; i--, p += 2) 2917 match = (x >= p[0] && x <= p[1]); 2918 } 2919 break; 2920 2921 case O_IPPRECEDENCE: 2922 match = (is_ipv4 && 2923 (cmd->arg1 == (ip->ip_tos & 0xe0)) ); 2924 break; 2925 2926 case O_IPTOS: 2927 match = (is_ipv4 && 2928 flags_match(cmd, ip->ip_tos)); 2929 break; 2930 2931 case O_TCPDATALEN: 2932 if (proto == IPPROTO_TCP && offset == 0) { 2933 struct tcphdr *tcp; 2934 uint16_t x; 2935 uint16_t *p; 2936 int i; 2937 2938 tcp = TCP(ulp); 2939 x = ip_len - 2940 ((ip->ip_hl + tcp->th_off) << 2); 2941 if (cmdlen == 1) { 2942 match = (cmd->arg1 == x); 2943 break; 2944 } 2945 /* otherwise we have ranges */ 2946 p = ((ipfw_insn_u16 *)cmd)->ports; 2947 i = cmdlen - 1; 2948 for (; !match && i>0; i--, p += 2) 2949 match = (x >= p[0] && x <= p[1]); 2950 } 2951 break; 2952 2953 case O_TCPFLAGS: 2954 match = (proto == IPPROTO_TCP && offset == 0 && 2955 flags_match(cmd, TCP(ulp)->th_flags)); 2956 break; 2957 2958 case O_TCPOPTS: 2959 match = (proto == IPPROTO_TCP && offset == 0 && 2960 tcpopts_match(TCP(ulp), cmd)); 2961 break; 2962 2963 case O_TCPSEQ: 2964 match = (proto == IPPROTO_TCP && offset == 0 && 2965 ((ipfw_insn_u32 *)cmd)->d[0] == 2966 TCP(ulp)->th_seq); 2967 break; 2968 2969 case O_TCPACK: 2970 match = (proto == IPPROTO_TCP && offset == 0 && 2971 ((ipfw_insn_u32 *)cmd)->d[0] == 2972 TCP(ulp)->th_ack); 2973 break; 2974 2975 case O_TCPWIN: 2976 match = (proto == IPPROTO_TCP && offset == 0 && 2977 cmd->arg1 == TCP(ulp)->th_win); 2978 break; 2979 2980 case O_ESTAB: 2981 /* reject packets which have SYN only */ 2982 /* XXX should i also check for TH_ACK ? */ 2983 match = (proto == IPPROTO_TCP && offset == 0 && 2984 (TCP(ulp)->th_flags & 2985 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN); 2986 break; 2987 2988 case O_ALTQ: { 2989 struct pf_mtag *at; 2990 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd; 2991 2992 match = 1; 2993 at = pf_find_mtag(m); 2994 if (at != NULL && at->qid != 0) 2995 break; 2996 at = pf_get_mtag(m); 2997 if (at == NULL) { 2998 /* 2999 * Let the packet fall back to the 3000 * default ALTQ. 3001 */ 3002 break; 3003 } 3004 at->qid = altq->qid; 3005 if (is_ipv4) 3006 at->af = AF_INET; 3007 else 3008 at->af = AF_LINK; 3009 at->hdr = ip; 3010 break; 3011 } 3012 3013 case O_LOG: 3014 if (V_fw_verbose) 3015 ipfw_log(f, hlen, args, m, 3016 oif, offset, tablearg, ip); 3017 match = 1; 3018 break; 3019 3020 case O_PROB: 3021 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]); 3022 break; 3023 3024 case O_VERREVPATH: 3025 /* Outgoing packets automatically pass/match */ 3026 match = ((oif != NULL) || 3027 (m->m_pkthdr.rcvif == NULL) || 3028 ( 3029#ifdef INET6 3030 is_ipv6 ? 3031 verify_path6(&(args->f_id.src_ip6), 3032 m->m_pkthdr.rcvif) : 3033#endif 3034 verify_path(src_ip, m->m_pkthdr.rcvif, 3035 args->f_id.fib))); 3036 break; 3037 3038 case O_VERSRCREACH: 3039 /* Outgoing packets automatically pass/match */ 3040 match = (hlen > 0 && ((oif != NULL) || 3041#ifdef INET6 3042 is_ipv6 ? 3043 verify_path6(&(args->f_id.src_ip6), 3044 NULL) : 3045#endif 3046 verify_path(src_ip, NULL, args->f_id.fib))); 3047 break; 3048 3049 case O_ANTISPOOF: 3050 /* Outgoing packets automatically pass/match */ 3051 if (oif == NULL && hlen > 0 && 3052 ( (is_ipv4 && in_localaddr(src_ip)) 3053#ifdef INET6 3054 || (is_ipv6 && 3055 in6_localaddr(&(args->f_id.src_ip6))) 3056#endif 3057 )) 3058 match = 3059#ifdef INET6 3060 is_ipv6 ? verify_path6( 3061 &(args->f_id.src_ip6), 3062 m->m_pkthdr.rcvif) : 3063#endif 3064 verify_path(src_ip, 3065 m->m_pkthdr.rcvif, 3066 args->f_id.fib); 3067 else 3068 match = 1; 3069 break; 3070 3071 case O_IPSEC: 3072#ifdef IPSEC 3073 match = (m_tag_find(m, 3074 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL); 3075#endif 3076 /* otherwise no match */ 3077 break; 3078 3079#ifdef INET6 3080 case O_IP6_SRC: 3081 match = is_ipv6 && 3082 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6, 3083 &((ipfw_insn_ip6 *)cmd)->addr6); 3084 break; 3085 3086 case O_IP6_DST: 3087 match = is_ipv6 && 3088 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6, 3089 &((ipfw_insn_ip6 *)cmd)->addr6); 3090 break; 3091 case O_IP6_SRC_MASK: 3092 case O_IP6_DST_MASK: 3093 if (is_ipv6) { 3094 int i = cmdlen - 1; 3095 struct in6_addr p; 3096 struct in6_addr *d = 3097 &((ipfw_insn_ip6 *)cmd)->addr6; 3098 3099 for (; !match && i > 0; d += 2, 3100 i -= F_INSN_SIZE(struct in6_addr) 3101 * 2) { 3102 p = (cmd->opcode == 3103 O_IP6_SRC_MASK) ? 3104 args->f_id.src_ip6: 3105 args->f_id.dst_ip6; 3106 APPLY_MASK(&p, &d[1]); 3107 match = 3108 IN6_ARE_ADDR_EQUAL(&d[0], 3109 &p); 3110 } 3111 } 3112 break; 3113 3114 case O_IP6_SRC_ME: 3115 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6); 3116 break; 3117 3118 case O_IP6_DST_ME: 3119 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6); 3120 break; 3121 3122 case O_FLOW6ID: 3123 match = is_ipv6 && 3124 flow6id_match(args->f_id.flow_id6, 3125 (ipfw_insn_u32 *) cmd); 3126 break; 3127 3128 case O_EXT_HDR: 3129 match = is_ipv6 && 3130 (ext_hd & ((ipfw_insn *) cmd)->arg1); 3131 break; 3132 3133 case O_IP6: 3134 match = is_ipv6; 3135 break; 3136#endif 3137 3138 case O_IP4: 3139 match = is_ipv4; 3140 break; 3141 3142 case O_TAG: { 3143 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ? 3144 tablearg : cmd->arg1; 3145 3146 /* Packet is already tagged with this tag? */ 3147 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL); 3148 3149 /* We have `untag' action when F_NOT flag is 3150 * present. And we must remove this mtag from 3151 * mbuf and reset `match' to zero (`match' will 3152 * be inversed later). 3153 * Otherwise we should allocate new mtag and 3154 * push it into mbuf. 3155 */ 3156 if (cmd->len & F_NOT) { /* `untag' action */ 3157 if (mtag != NULL) 3158 m_tag_delete(m, mtag); 3159 } else if (mtag == NULL) { 3160 if ((mtag = m_tag_alloc(MTAG_IPFW, 3161 tag, 0, M_NOWAIT)) != NULL) 3162 m_tag_prepend(m, mtag); 3163 } 3164 match = (cmd->len & F_NOT) ? 0: 1; 3165 break; 3166 } 3167 3168 case O_FIB: /* try match the specified fib */ 3169 if (args->f_id.fib == cmd->arg1) 3170 match = 1; 3171 break; 3172 3173 case O_TAGGED: { 3174 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ? 3175 tablearg : cmd->arg1; 3176 3177 if (cmdlen == 1) { 3178 match = m_tag_locate(m, MTAG_IPFW, 3179 tag, NULL) != NULL; 3180 break; 3181 } 3182 3183 /* we have ranges */ 3184 for (mtag = m_tag_first(m); 3185 mtag != NULL && !match; 3186 mtag = m_tag_next(m, mtag)) { 3187 uint16_t *p; 3188 int i; 3189 3190 if (mtag->m_tag_cookie != MTAG_IPFW) 3191 continue; 3192 3193 p = ((ipfw_insn_u16 *)cmd)->ports; 3194 i = cmdlen - 1; 3195 for(; !match && i > 0; i--, p += 2) 3196 match = 3197 mtag->m_tag_id >= p[0] && 3198 mtag->m_tag_id <= p[1]; 3199 } 3200 break; 3201 } 3202 3203 /* 3204 * The second set of opcodes represents 'actions', 3205 * i.e. the terminal part of a rule once the packet 3206 * matches all previous patterns. 3207 * Typically there is only one action for each rule, 3208 * and the opcode is stored at the end of the rule 3209 * (but there are exceptions -- see below). 3210 * 3211 * In general, here we set retval and terminate the 3212 * outer loop (would be a 'break 3' in some language, 3213 * but we need to do a 'goto done'). 3214 * 3215 * Exceptions: 3216 * O_COUNT and O_SKIPTO actions: 3217 * instead of terminating, we jump to the next rule 3218 * ('goto next_rule', equivalent to a 'break 2'), 3219 * or to the SKIPTO target ('goto again' after 3220 * having set f, cmd and l), respectively. 3221 * 3222 * O_TAG, O_LOG and O_ALTQ action parameters: 3223 * perform some action and set match = 1; 3224 * 3225 * O_LIMIT and O_KEEP_STATE: these opcodes are 3226 * not real 'actions', and are stored right 3227 * before the 'action' part of the rule. 3228 * These opcodes try to install an entry in the 3229 * state tables; if successful, we continue with 3230 * the next opcode (match=1; break;), otherwise 3231 * the packet * must be dropped 3232 * ('goto done' after setting retval); 3233 * 3234 * O_PROBE_STATE and O_CHECK_STATE: these opcodes 3235 * cause a lookup of the state table, and a jump 3236 * to the 'action' part of the parent rule 3237 * ('goto check_body') if an entry is found, or 3238 * (CHECK_STATE only) a jump to the next rule if 3239 * the entry is not found ('goto next_rule'). 3240 * The result of the lookup is cached to make 3241 * further instances of these opcodes are 3242 * effectively NOPs. 3243 */ 3244 case O_LIMIT: 3245 case O_KEEP_STATE: 3246 if (install_state(f, 3247 (ipfw_insn_limit *)cmd, args, tablearg)) { 3248 retval = IP_FW_DENY; 3249 goto done; /* error/limit violation */ 3250 } 3251 match = 1; 3252 break; 3253 3254 case O_PROBE_STATE: 3255 case O_CHECK_STATE: 3256 /* 3257 * dynamic rules are checked at the first 3258 * keep-state or check-state occurrence, 3259 * with the result being stored in dyn_dir. 3260 * The compiler introduces a PROBE_STATE 3261 * instruction for us when we have a 3262 * KEEP_STATE (because PROBE_STATE needs 3263 * to be run first). 3264 */ 3265 if (dyn_dir == MATCH_UNKNOWN && 3266 (q = lookup_dyn_rule(&args->f_id, 3267 &dyn_dir, proto == IPPROTO_TCP ? 3268 TCP(ulp) : NULL)) 3269 != NULL) { 3270 /* 3271 * Found dynamic entry, update stats 3272 * and jump to the 'action' part of 3273 * the parent rule. 3274 */ 3275 q->pcnt++; 3276 q->bcnt += pktlen; 3277 f = q->rule; 3278 cmd = ACTION_PTR(f); 3279 l = f->cmd_len - f->act_ofs; 3280 IPFW_DYN_UNLOCK(); 3281 goto check_body; 3282 } 3283 /* 3284 * Dynamic entry not found. If CHECK_STATE, 3285 * skip to next rule, if PROBE_STATE just 3286 * ignore and continue with next opcode. 3287 */ 3288 if (cmd->opcode == O_CHECK_STATE) 3289 goto next_rule; 3290 match = 1; 3291 break; 3292 3293 case O_ACCEPT: 3294 retval = 0; /* accept */ 3295 goto done; 3296 3297 case O_PIPE: 3298 case O_QUEUE: 3299 args->rule = f; /* report matching rule */ 3300 args->rule_id = f->id; 3301 args->chain_id = chain->id; 3302 if (cmd->arg1 == IP_FW_TABLEARG) 3303 args->cookie = tablearg; 3304 else 3305 args->cookie = cmd->arg1; 3306 retval = IP_FW_DUMMYNET; 3307 goto done; 3308 3309 case O_DIVERT: 3310 case O_TEE: { 3311 struct divert_tag *dt; 3312 3313 if (args->eh) /* not on layer 2 */ 3314 break; 3315 mtag = m_tag_get(PACKET_TAG_DIVERT, 3316 sizeof(struct divert_tag), 3317 M_NOWAIT); 3318 if (mtag == NULL) { 3319 /* XXX statistic */ 3320 /* drop packet */ 3321 IPFW_RUNLOCK(chain); 3322 if (ucred_cache != NULL) 3323 crfree(ucred_cache); 3324 return (IP_FW_DENY); 3325 } 3326 dt = (struct divert_tag *)(mtag+1); 3327 dt->cookie = f->rulenum; 3328 if (cmd->arg1 == IP_FW_TABLEARG) 3329 dt->info = tablearg; 3330 else 3331 dt->info = cmd->arg1; 3332 m_tag_prepend(m, mtag); 3333 retval = (cmd->opcode == O_DIVERT) ? 3334 IP_FW_DIVERT : IP_FW_TEE; 3335 goto done; 3336 } 3337 case O_COUNT: 3338 case O_SKIPTO: 3339 f->pcnt++; /* update stats */ 3340 f->bcnt += pktlen; 3341 f->timestamp = time_uptime; 3342 if (cmd->opcode == O_COUNT) 3343 goto next_rule; 3344 /* handle skipto */ 3345 if (cmd->arg1 == IP_FW_TABLEARG) { 3346 f = lookup_next_rule(f, tablearg); 3347 } else { 3348 if (f->next_rule == NULL) 3349 lookup_next_rule(f, 0); 3350 f = f->next_rule; 3351 } 3352 goto again; 3353 3354 case O_REJECT: 3355 /* 3356 * Drop the packet and send a reject notice 3357 * if the packet is not ICMP (or is an ICMP 3358 * query), and it is not multicast/broadcast. 3359 */ 3360 if (hlen > 0 && is_ipv4 && offset == 0 && 3361 (proto != IPPROTO_ICMP || 3362 is_icmp_query(ICMP(ulp))) && 3363 !(m->m_flags & (M_BCAST|M_MCAST)) && 3364 !IN_MULTICAST(ntohl(dst_ip.s_addr))) { 3365 send_reject(args, cmd->arg1, ip_len, ip); 3366 m = args->m; 3367 } 3368 /* FALLTHROUGH */ 3369#ifdef INET6 3370 case O_UNREACH6: 3371 if (hlen > 0 && is_ipv6 && 3372 ((offset & IP6F_OFF_MASK) == 0) && 3373 (proto != IPPROTO_ICMPV6 || 3374 (is_icmp6_query(args->f_id.flags) == 1)) && 3375 !(m->m_flags & (M_BCAST|M_MCAST)) && 3376 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) { 3377 send_reject6( 3378 args, cmd->arg1, hlen, 3379 (struct ip6_hdr *)ip); 3380 m = args->m; 3381 } 3382 /* FALLTHROUGH */ 3383#endif 3384 case O_DENY: 3385 retval = IP_FW_DENY; 3386 goto done; 3387 3388 case O_FORWARD_IP: { 3389 struct sockaddr_in *sa; 3390 sa = &(((ipfw_insn_sa *)cmd)->sa); 3391 if (args->eh) /* not valid on layer2 pkts */ 3392 break; 3393 if (!q || dyn_dir == MATCH_FORWARD) { 3394 if (sa->sin_addr.s_addr == INADDR_ANY) { 3395 bcopy(sa, &args->hopstore, 3396 sizeof(*sa)); 3397 args->hopstore.sin_addr.s_addr = 3398 htonl(tablearg); 3399 args->next_hop = 3400 &args->hopstore; 3401 } else { 3402 args->next_hop = sa; 3403 } 3404 } 3405 retval = IP_FW_PASS; 3406 } 3407 goto done; 3408 3409 case O_NETGRAPH: 3410 case O_NGTEE: 3411 args->rule = f; /* report matching rule */ 3412 args->rule_id = f->id; 3413 args->chain_id = chain->id; 3414 if (cmd->arg1 == IP_FW_TABLEARG) 3415 args->cookie = tablearg; 3416 else 3417 args->cookie = cmd->arg1; 3418 retval = (cmd->opcode == O_NETGRAPH) ? 3419 IP_FW_NETGRAPH : IP_FW_NGTEE; 3420 goto done; 3421 3422 case O_SETFIB: 3423 f->pcnt++; /* update stats */ 3424 f->bcnt += pktlen; 3425 f->timestamp = time_uptime; 3426 M_SETFIB(m, cmd->arg1); 3427 args->f_id.fib = cmd->arg1; 3428 goto next_rule; 3429 3430 case O_NAT: { 3431 struct cfg_nat *t; 3432 int nat_id; 3433 3434 if (IPFW_NAT_LOADED) { 3435 args->rule = f; /* Report matching rule. */ 3436 args->rule_id = f->id; 3437 args->chain_id = chain->id; 3438 t = ((ipfw_insn_nat *)cmd)->nat; 3439 if (t == NULL) { 3440 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ? 3441 tablearg : cmd->arg1; 3442 LOOKUP_NAT(V_layer3_chain, nat_id, t); 3443 if (t == NULL) { 3444 retval = IP_FW_DENY; 3445 goto done; 3446 } 3447 if (cmd->arg1 != IP_FW_TABLEARG) 3448 ((ipfw_insn_nat *)cmd)->nat = t; 3449 } 3450 retval = ipfw_nat_ptr(args, t, m); 3451 } else 3452 retval = IP_FW_DENY; 3453 goto done; 3454 } 3455 3456 case O_REASS: { 3457 int ip_off; 3458 3459 f->pcnt++; 3460 f->bcnt += pktlen; 3461 ip_off = (args->eh != NULL) ? ntohs(ip->ip_off) : ip->ip_off; 3462 if (ip_off & (IP_MF | IP_OFFMASK)) { 3463 /* 3464 * ip_reass() expects len & off in host 3465 * byte order: fix them in case we come 3466 * from layer2. 3467 */ 3468 if (args->eh != NULL) { 3469 ip->ip_len = ntohs(ip->ip_len); 3470 ip->ip_off = ntohs(ip->ip_off); 3471 } 3472 3473 m = ip_reass(m); 3474 args->m = m; 3475 3476 /* 3477 * IP header checksum fixup after 3478 * reassembly and leave header 3479 * in network byte order. 3480 */ 3481 if (m != NULL) { 3482 int hlen; 3483 3484 ip = mtod(m, struct ip *); 3485 hlen = ip->ip_hl << 2; 3486 /* revert len & off for layer2 pkts */ 3487 if (args->eh != NULL) 3488 ip->ip_len = htons(ip->ip_len); 3489 ip->ip_sum = 0; 3490 if (hlen == sizeof(struct ip)) 3491 ip->ip_sum = in_cksum_hdr(ip); 3492 else 3493 ip->ip_sum = in_cksum(m, hlen); 3494 retval = IP_FW_REASS; 3495 args->rule = f; 3496 args->rule_id = f->id; 3497 args->chain_id = chain->id; 3498 goto done; 3499 } else { 3500 retval = IP_FW_DENY; 3501 goto done; 3502 } 3503 } 3504 goto next_rule; 3505 } 3506 3507 default: 3508 panic("-- unknown opcode %d\n", cmd->opcode); 3509 } /* end of switch() on opcodes */ 3510 3511 if (cmd->len & F_NOT) 3512 match = !match; 3513 3514 if (match) { 3515 if (cmd->len & F_OR) 3516 skip_or = 1; 3517 } else { 3518 if (!(cmd->len & F_OR)) /* not an OR block, */ 3519 break; /* try next rule */ 3520 } 3521 3522 } /* end of inner for, scan opcodes */ 3523 3524next_rule:; /* try next rule */ 3525 3526 } /* end of outer for, scan rules */ 3527 printf("ipfw: ouch!, skip past end of rules, denying packet\n"); 3528 IPFW_RUNLOCK(chain); 3529 if (ucred_cache != NULL) 3530 crfree(ucred_cache); 3531 return (IP_FW_DENY); 3532 3533done: 3534 /* Update statistics */ 3535 f->pcnt++; 3536 f->bcnt += pktlen; 3537 f->timestamp = time_uptime; 3538 IPFW_RUNLOCK(chain); 3539 if (ucred_cache != NULL) 3540 crfree(ucred_cache); 3541 return (retval); 3542 3543pullup_failed: 3544 if (V_fw_verbose) 3545 printf("ipfw: pullup failed\n"); 3546 return (IP_FW_DENY); 3547} 3548 3549/* 3550 * When a rule is added/deleted, clear the next_rule pointers in all rules. 3551 * These will be reconstructed on the fly as packets are matched. 3552 */ 3553static void 3554flush_rule_ptrs(struct ip_fw_chain *chain) 3555{ 3556 struct ip_fw *rule; 3557 3558 IPFW_WLOCK_ASSERT(chain); 3559 3560 chain->id++; 3561 3562 for (rule = chain->rules; rule; rule = rule->next) 3563 rule->next_rule = NULL; 3564} 3565 3566/* 3567 * Add a new rule to the list. Copy the rule into a malloc'ed area, then 3568 * possibly create a rule number and add the rule to the list. 3569 * Update the rule_number in the input struct so the caller knows it as well. 3570 */ 3571static int 3572add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule) 3573{ 3574 struct ip_fw *rule, *f, *prev; 3575 int l = RULESIZE(input_rule); 3576 3577 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE) 3578 return (EINVAL); 3579 3580 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO); 3581 if (rule == NULL) 3582 return (ENOSPC); 3583 3584 bcopy(input_rule, rule, l); 3585 3586 rule->next = NULL; 3587 rule->next_rule = NULL; 3588 3589 rule->pcnt = 0; 3590 rule->bcnt = 0; 3591 rule->timestamp = 0; 3592 3593 IPFW_WLOCK(chain); 3594 3595 if (chain->rules == NULL) { /* default rule */ 3596 chain->rules = rule; 3597 rule->id = ++chain->id; 3598 goto done; 3599 } 3600 3601 /* 3602 * If rulenum is 0, find highest numbered rule before the 3603 * default rule, and add autoinc_step 3604 */ 3605 if (V_autoinc_step < 1) 3606 V_autoinc_step = 1; 3607 else if (V_autoinc_step > 1000) 3608 V_autoinc_step = 1000; 3609 if (rule->rulenum == 0) { 3610 /* 3611 * locate the highest numbered rule before default 3612 */ 3613 for (f = chain->rules; f; f = f->next) { 3614 if (f->rulenum == IPFW_DEFAULT_RULE) 3615 break; 3616 rule->rulenum = f->rulenum; 3617 } 3618 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step) 3619 rule->rulenum += V_autoinc_step; 3620 input_rule->rulenum = rule->rulenum; 3621 } 3622 3623 /* 3624 * Now insert the new rule in the right place in the sorted list. 3625 */ 3626 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) { 3627 if (f->rulenum > rule->rulenum) { /* found the location */ 3628 if (prev) { 3629 rule->next = f; 3630 prev->next = rule; 3631 } else { /* head insert */ 3632 rule->next = chain->rules; 3633 chain->rules = rule; 3634 } 3635 break; 3636 } 3637 } 3638 flush_rule_ptrs(chain); 3639 /* chain->id incremented inside flush_rule_ptrs() */ 3640 rule->id = chain->id; 3641done: 3642 V_static_count++; 3643 V_static_len += l; 3644 IPFW_WUNLOCK(chain); 3645 DEB(printf("ipfw: installed rule %d, static count now %d\n", 3646 rule->rulenum, V_static_count);) 3647 return (0); 3648} 3649 3650/** 3651 * Remove a static rule (including derived * dynamic rules) 3652 * and place it on the ``reap list'' for later reclamation. 3653 * The caller is in charge of clearing rule pointers to avoid 3654 * dangling pointers. 3655 * @return a pointer to the next entry. 3656 * Arguments are not checked, so they better be correct. 3657 */ 3658static struct ip_fw * 3659remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, 3660 struct ip_fw *prev) 3661{ 3662 struct ip_fw *n; 3663 int l = RULESIZE(rule); 3664 3665 IPFW_WLOCK_ASSERT(chain); 3666 3667 n = rule->next; 3668 IPFW_DYN_LOCK(); 3669 remove_dyn_rule(rule, NULL /* force removal */); 3670 IPFW_DYN_UNLOCK(); 3671 if (prev == NULL) 3672 chain->rules = n; 3673 else 3674 prev->next = n; 3675 V_static_count--; 3676 V_static_len -= l; 3677 3678 rule->next = chain->reap; 3679 chain->reap = rule; 3680 3681 return n; 3682} 3683 3684/* 3685 * Reclaim storage associated with a list of rules. This is 3686 * typically the list created using remove_rule. 3687 * A NULL pointer on input is handled correctly. 3688 */ 3689static void 3690reap_rules(struct ip_fw *head) 3691{ 3692 struct ip_fw *rule; 3693 3694 while ((rule = head) != NULL) { 3695 head = head->next; 3696 free(rule, M_IPFW); 3697 } 3698} 3699 3700/* 3701 * Remove all rules from a chain (except rules in set RESVD_SET 3702 * unless kill_default = 1). The caller is responsible for 3703 * reclaiming storage for the rules left in chain->reap. 3704 */ 3705static void 3706free_chain(struct ip_fw_chain *chain, int kill_default) 3707{ 3708 struct ip_fw *prev, *rule; 3709 3710 IPFW_WLOCK_ASSERT(chain); 3711 3712 chain->reap = NULL; 3713 flush_rule_ptrs(chain); /* more efficient to do outside the loop */ 3714 for (prev = NULL, rule = chain->rules; rule ; ) 3715 if (kill_default || rule->set != RESVD_SET) 3716 rule = remove_rule(chain, rule, prev); 3717 else { 3718 prev = rule; 3719 rule = rule->next; 3720 } 3721} 3722 3723/** 3724 * Remove all rules with given number, and also do set manipulation. 3725 * Assumes chain != NULL && *chain != NULL. 3726 * 3727 * The argument is an u_int32_t. The low 16 bit are the rule or set number, 3728 * the next 8 bits are the new set, the top 8 bits are the command: 3729 * 3730 * 0 delete rules with given number 3731 * 1 delete rules with given set number 3732 * 2 move rules with given number to new set 3733 * 3 move rules with given set number to new set 3734 * 4 swap sets with given numbers 3735 * 5 delete rules with given number and with given set number 3736 */ 3737static int 3738del_entry(struct ip_fw_chain *chain, u_int32_t arg) 3739{ 3740 struct ip_fw *prev = NULL, *rule; 3741 u_int16_t rulenum; /* rule or old_set */ 3742 u_int8_t cmd, new_set; 3743 3744 rulenum = arg & 0xffff; 3745 cmd = (arg >> 24) & 0xff; 3746 new_set = (arg >> 16) & 0xff; 3747 3748 if (cmd > 5 || new_set > RESVD_SET) 3749 return EINVAL; 3750 if (cmd == 0 || cmd == 2 || cmd == 5) { 3751 if (rulenum >= IPFW_DEFAULT_RULE) 3752 return EINVAL; 3753 } else { 3754 if (rulenum > RESVD_SET) /* old_set */ 3755 return EINVAL; 3756 } 3757 3758 IPFW_WLOCK(chain); 3759 rule = chain->rules; /* common starting point */ 3760 chain->reap = NULL; /* prepare for deletions */ 3761 switch (cmd) { 3762 case 0: /* delete rules with given number */ 3763 /* 3764 * locate first rule to delete 3765 */ 3766 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next) 3767 ; 3768 if (rule->rulenum != rulenum) { 3769 IPFW_WUNLOCK(chain); 3770 return EINVAL; 3771 } 3772 3773 /* 3774 * flush pointers outside the loop, then delete all matching 3775 * rules. prev remains the same throughout the cycle. 3776 */ 3777 flush_rule_ptrs(chain); 3778 while (rule->rulenum == rulenum) 3779 rule = remove_rule(chain, rule, prev); 3780 break; 3781 3782 case 1: /* delete all rules with given set number */ 3783 flush_rule_ptrs(chain); 3784 while (rule->rulenum < IPFW_DEFAULT_RULE) { 3785 if (rule->set == rulenum) 3786 rule = remove_rule(chain, rule, prev); 3787 else { 3788 prev = rule; 3789 rule = rule->next; 3790 } 3791 } 3792 break; 3793 3794 case 2: /* move rules with given number to new set */ 3795 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3796 if (rule->rulenum == rulenum) 3797 rule->set = new_set; 3798 break; 3799 3800 case 3: /* move rules with given set number to new set */ 3801 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3802 if (rule->set == rulenum) 3803 rule->set = new_set; 3804 break; 3805 3806 case 4: /* swap two sets */ 3807 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next) 3808 if (rule->set == rulenum) 3809 rule->set = new_set; 3810 else if (rule->set == new_set) 3811 rule->set = rulenum; 3812 break; 3813 3814 case 5: /* delete rules with given number and with given set number. 3815 * rulenum - given rule number; 3816 * new_set - given set number. 3817 */ 3818 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next) 3819 ; 3820 if (rule->rulenum != rulenum) { 3821 IPFW_WUNLOCK(chain); 3822 return (EINVAL); 3823 } 3824 flush_rule_ptrs(chain); 3825 while (rule->rulenum == rulenum) { 3826 if (rule->set == new_set) 3827 rule = remove_rule(chain, rule, prev); 3828 else { 3829 prev = rule; 3830 rule = rule->next; 3831 } 3832 } 3833 } 3834 /* 3835 * Look for rules to reclaim. We grab the list before 3836 * releasing the lock then reclaim them w/o the lock to 3837 * avoid a LOR with dummynet. 3838 */ 3839 rule = chain->reap; 3840 IPFW_WUNLOCK(chain); 3841 reap_rules(rule); 3842 return 0; 3843} 3844 3845/* 3846 * Clear counters for a specific rule. 3847 * The enclosing "table" is assumed locked. 3848 */ 3849static void 3850clear_counters(struct ip_fw *rule, int log_only) 3851{ 3852 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule); 3853 3854 if (log_only == 0) { 3855 rule->bcnt = rule->pcnt = 0; 3856 rule->timestamp = 0; 3857 } 3858 if (l->o.opcode == O_LOG) 3859 l->log_left = l->max_log; 3860} 3861 3862/** 3863 * Reset some or all counters on firewall rules. 3864 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number, 3865 * the next 8 bits are the set number, the top 8 bits are the command: 3866 * 0 work with rules from all set's; 3867 * 1 work with rules only from specified set. 3868 * Specified rule number is zero if we want to clear all entries. 3869 * log_only is 1 if we only want to reset logs, zero otherwise. 3870 */ 3871static int 3872zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only) 3873{ 3874 struct ip_fw *rule; 3875 char *msg; 3876 3877 uint16_t rulenum = arg & 0xffff; 3878 uint8_t set = (arg >> 16) & 0xff; 3879 uint8_t cmd = (arg >> 24) & 0xff; 3880 3881 if (cmd > 1) 3882 return (EINVAL); 3883 if (cmd == 1 && set > RESVD_SET) 3884 return (EINVAL); 3885 3886 IPFW_WLOCK(chain); 3887 if (rulenum == 0) { 3888 V_norule_counter = 0; 3889 for (rule = chain->rules; rule; rule = rule->next) { 3890 /* Skip rules from another set. */ 3891 if (cmd == 1 && rule->set != set) 3892 continue; 3893 clear_counters(rule, log_only); 3894 } 3895 msg = log_only ? "All logging counts reset" : 3896 "Accounting cleared"; 3897 } else { 3898 int cleared = 0; 3899 /* 3900 * We can have multiple rules with the same number, so we 3901 * need to clear them all. 3902 */ 3903 for (rule = chain->rules; rule; rule = rule->next) 3904 if (rule->rulenum == rulenum) { 3905 while (rule && rule->rulenum == rulenum) { 3906 if (cmd == 0 || rule->set == set) 3907 clear_counters(rule, log_only); 3908 rule = rule->next; 3909 } 3910 cleared = 1; 3911 break; 3912 } 3913 if (!cleared) { /* we did not find any matching rules */ 3914 IPFW_WUNLOCK(chain); 3915 return (EINVAL); 3916 } 3917 msg = log_only ? "logging count reset" : "cleared"; 3918 } 3919 IPFW_WUNLOCK(chain); 3920 3921 if (V_fw_verbose) { 3922 int lev = LOG_SECURITY | LOG_NOTICE; 3923 3924 if (rulenum) 3925 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg); 3926 else 3927 log(lev, "ipfw: %s.\n", msg); 3928 } 3929 return (0); 3930} 3931 3932/* 3933 * Check validity of the structure before insert. 3934 * Fortunately rules are simple, so this mostly need to check rule sizes. 3935 */ 3936static int 3937check_ipfw_struct(struct ip_fw *rule, int size) 3938{ 3939 int l, cmdlen = 0; 3940 int have_action=0; 3941 ipfw_insn *cmd; 3942 3943 if (size < sizeof(*rule)) { 3944 printf("ipfw: rule too short\n"); 3945 return (EINVAL); 3946 } 3947 /* first, check for valid size */ 3948 l = RULESIZE(rule); 3949 if (l != size) { 3950 printf("ipfw: size mismatch (have %d want %d)\n", size, l); 3951 return (EINVAL); 3952 } 3953 if (rule->act_ofs >= rule->cmd_len) { 3954 printf("ipfw: bogus action offset (%u > %u)\n", 3955 rule->act_ofs, rule->cmd_len - 1); 3956 return (EINVAL); 3957 } 3958 /* 3959 * Now go for the individual checks. Very simple ones, basically only 3960 * instruction sizes. 3961 */ 3962 for (l = rule->cmd_len, cmd = rule->cmd ; 3963 l > 0 ; l -= cmdlen, cmd += cmdlen) { 3964 cmdlen = F_LEN(cmd); 3965 if (cmdlen > l) { 3966 printf("ipfw: opcode %d size truncated\n", 3967 cmd->opcode); 3968 return EINVAL; 3969 } 3970 DEB(printf("ipfw: opcode %d\n", cmd->opcode);) 3971 switch (cmd->opcode) { 3972 case O_PROBE_STATE: 3973 case O_KEEP_STATE: 3974 case O_PROTO: 3975 case O_IP_SRC_ME: 3976 case O_IP_DST_ME: 3977 case O_LAYER2: 3978 case O_IN: 3979 case O_FRAG: 3980 case O_DIVERTED: 3981 case O_IPOPT: 3982 case O_IPTOS: 3983 case O_IPPRECEDENCE: 3984 case O_IPVER: 3985 case O_TCPWIN: 3986 case O_TCPFLAGS: 3987 case O_TCPOPTS: 3988 case O_ESTAB: 3989 case O_VERREVPATH: 3990 case O_VERSRCREACH: 3991 case O_ANTISPOOF: 3992 case O_IPSEC: 3993#ifdef INET6 3994 case O_IP6_SRC_ME: 3995 case O_IP6_DST_ME: 3996 case O_EXT_HDR: 3997 case O_IP6: 3998#endif 3999 case O_IP4: 4000 case O_TAG: 4001 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4002 goto bad_size; 4003 break; 4004 4005 case O_FIB: 4006 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4007 goto bad_size; 4008 if (cmd->arg1 >= rt_numfibs) { 4009 printf("ipfw: invalid fib number %d\n", 4010 cmd->arg1); 4011 return EINVAL; 4012 } 4013 break; 4014 4015 case O_SETFIB: 4016 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4017 goto bad_size; 4018 if (cmd->arg1 >= rt_numfibs) { 4019 printf("ipfw: invalid fib number %d\n", 4020 cmd->arg1); 4021 return EINVAL; 4022 } 4023 goto check_action; 4024 4025 case O_UID: 4026 case O_GID: 4027 case O_JAIL: 4028 case O_IP_SRC: 4029 case O_IP_DST: 4030 case O_TCPSEQ: 4031 case O_TCPACK: 4032 case O_PROB: 4033 case O_ICMPTYPE: 4034 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32)) 4035 goto bad_size; 4036 break; 4037 4038 case O_LIMIT: 4039 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit)) 4040 goto bad_size; 4041 break; 4042 4043 case O_LOG: 4044 if (cmdlen != F_INSN_SIZE(ipfw_insn_log)) 4045 goto bad_size; 4046 4047 ((ipfw_insn_log *)cmd)->log_left = 4048 ((ipfw_insn_log *)cmd)->max_log; 4049 4050 break; 4051 4052 case O_IP_SRC_MASK: 4053 case O_IP_DST_MASK: 4054 /* only odd command lengths */ 4055 if ( !(cmdlen & 1) || cmdlen > 31) 4056 goto bad_size; 4057 break; 4058 4059 case O_IP_SRC_SET: 4060 case O_IP_DST_SET: 4061 if (cmd->arg1 == 0 || cmd->arg1 > 256) { 4062 printf("ipfw: invalid set size %d\n", 4063 cmd->arg1); 4064 return EINVAL; 4065 } 4066 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 4067 (cmd->arg1+31)/32 ) 4068 goto bad_size; 4069 break; 4070 4071 case O_IP_SRC_LOOKUP: 4072 case O_IP_DST_LOOKUP: 4073 if (cmd->arg1 >= IPFW_TABLES_MAX) { 4074 printf("ipfw: invalid table number %d\n", 4075 cmd->arg1); 4076 return (EINVAL); 4077 } 4078 if (cmdlen != F_INSN_SIZE(ipfw_insn) && 4079 cmdlen != F_INSN_SIZE(ipfw_insn_u32)) 4080 goto bad_size; 4081 break; 4082 4083 case O_MACADDR2: 4084 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac)) 4085 goto bad_size; 4086 break; 4087 4088 case O_NOP: 4089 case O_IPID: 4090 case O_IPTTL: 4091 case O_IPLEN: 4092 case O_TCPDATALEN: 4093 case O_TAGGED: 4094 if (cmdlen < 1 || cmdlen > 31) 4095 goto bad_size; 4096 break; 4097 4098 case O_MAC_TYPE: 4099 case O_IP_SRCPORT: 4100 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */ 4101 if (cmdlen < 2 || cmdlen > 31) 4102 goto bad_size; 4103 break; 4104 4105 case O_RECV: 4106 case O_XMIT: 4107 case O_VIA: 4108 if (cmdlen != F_INSN_SIZE(ipfw_insn_if)) 4109 goto bad_size; 4110 break; 4111 4112 case O_ALTQ: 4113 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq)) 4114 goto bad_size; 4115 break; 4116 4117 case O_PIPE: 4118 case O_QUEUE: 4119 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4120 goto bad_size; 4121 goto check_action; 4122 4123 case O_FORWARD_IP: 4124#ifdef IPFIREWALL_FORWARD 4125 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) 4126 goto bad_size; 4127 goto check_action; 4128#else 4129 return EINVAL; 4130#endif 4131 4132 case O_DIVERT: 4133 case O_TEE: 4134 if (ip_divert_ptr == NULL) 4135 return EINVAL; 4136 else 4137 goto check_size; 4138 case O_NETGRAPH: 4139 case O_NGTEE: 4140 if (!NG_IPFW_LOADED) 4141 return EINVAL; 4142 else 4143 goto check_size; 4144 case O_NAT: 4145 if (!IPFW_NAT_LOADED) 4146 return EINVAL; 4147 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat)) 4148 goto bad_size; 4149 goto check_action; 4150 case O_FORWARD_MAC: /* XXX not implemented yet */ 4151 case O_CHECK_STATE: 4152 case O_COUNT: 4153 case O_ACCEPT: 4154 case O_DENY: 4155 case O_REJECT: 4156#ifdef INET6 4157 case O_UNREACH6: 4158#endif 4159 case O_SKIPTO: 4160 case O_REASS: 4161check_size: 4162 if (cmdlen != F_INSN_SIZE(ipfw_insn)) 4163 goto bad_size; 4164check_action: 4165 if (have_action) { 4166 printf("ipfw: opcode %d, multiple actions" 4167 " not allowed\n", 4168 cmd->opcode); 4169 return EINVAL; 4170 } 4171 have_action = 1; 4172 if (l != cmdlen) { 4173 printf("ipfw: opcode %d, action must be" 4174 " last opcode\n", 4175 cmd->opcode); 4176 return EINVAL; 4177 } 4178 break; 4179#ifdef INET6 4180 case O_IP6_SRC: 4181 case O_IP6_DST: 4182 if (cmdlen != F_INSN_SIZE(struct in6_addr) + 4183 F_INSN_SIZE(ipfw_insn)) 4184 goto bad_size; 4185 break; 4186 4187 case O_FLOW6ID: 4188 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 4189 ((ipfw_insn_u32 *)cmd)->o.arg1) 4190 goto bad_size; 4191 break; 4192 4193 case O_IP6_SRC_MASK: 4194 case O_IP6_DST_MASK: 4195 if ( !(cmdlen & 1) || cmdlen > 127) 4196 goto bad_size; 4197 break; 4198 case O_ICMP6TYPE: 4199 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) ) 4200 goto bad_size; 4201 break; 4202#endif 4203 4204 default: 4205 switch (cmd->opcode) { 4206#ifndef INET6 4207 case O_IP6_SRC_ME: 4208 case O_IP6_DST_ME: 4209 case O_EXT_HDR: 4210 case O_IP6: 4211 case O_UNREACH6: 4212 case O_IP6_SRC: 4213 case O_IP6_DST: 4214 case O_FLOW6ID: 4215 case O_IP6_SRC_MASK: 4216 case O_IP6_DST_MASK: 4217 case O_ICMP6TYPE: 4218 printf("ipfw: no IPv6 support in kernel\n"); 4219 return EPROTONOSUPPORT; 4220#endif 4221 default: 4222 printf("ipfw: opcode %d, unknown opcode\n", 4223 cmd->opcode); 4224 return EINVAL; 4225 } 4226 } 4227 } 4228 if (have_action == 0) { 4229 printf("ipfw: missing action\n"); 4230 return EINVAL; 4231 } 4232 return 0; 4233 4234bad_size: 4235 printf("ipfw: opcode %d size %d wrong\n", 4236 cmd->opcode, cmdlen); 4237 return EINVAL; 4238} 4239 4240/* 4241 * Copy the static and dynamic rules to the supplied buffer 4242 * and return the amount of space actually used. 4243 */ 4244static size_t 4245ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space) 4246{ 4247 char *bp = buf; 4248 char *ep = bp + space; 4249 struct ip_fw *rule; 4250 int i; 4251 time_t boot_seconds; 4252 4253 boot_seconds = boottime.tv_sec; 4254 /* XXX this can take a long time and locking will block packet flow */ 4255 IPFW_RLOCK(chain); 4256 for (rule = chain->rules; rule ; rule = rule->next) { 4257 /* 4258 * Verify the entry fits in the buffer in case the 4259 * rules changed between calculating buffer space and 4260 * now. This would be better done using a generation 4261 * number but should suffice for now. 4262 */ 4263 i = RULESIZE(rule); 4264 if (bp + i <= ep) { 4265 bcopy(rule, bp, i); 4266 /* 4267 * XXX HACK. Store the disable mask in the "next" 4268 * pointer in a wild attempt to keep the ABI the same. 4269 * Why do we do this on EVERY rule? 4270 */ 4271 bcopy(&V_set_disable, 4272 &(((struct ip_fw *)bp)->next_rule), 4273 sizeof(V_set_disable)); 4274 if (((struct ip_fw *)bp)->timestamp) 4275 ((struct ip_fw *)bp)->timestamp += boot_seconds; 4276 bp += i; 4277 } 4278 } 4279 IPFW_RUNLOCK(chain); 4280 if (V_ipfw_dyn_v) { 4281 ipfw_dyn_rule *p, *last = NULL; 4282 4283 IPFW_DYN_LOCK(); 4284 for (i = 0 ; i < V_curr_dyn_buckets; i++) 4285 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) { 4286 if (bp + sizeof *p <= ep) { 4287 ipfw_dyn_rule *dst = 4288 (ipfw_dyn_rule *)bp; 4289 bcopy(p, dst, sizeof *p); 4290 bcopy(&(p->rule->rulenum), &(dst->rule), 4291 sizeof(p->rule->rulenum)); 4292 /* 4293 * store set number into high word of 4294 * dst->rule pointer. 4295 */ 4296 bcopy(&(p->rule->set), 4297 (char *)&dst->rule + 4298 sizeof(p->rule->rulenum), 4299 sizeof(p->rule->set)); 4300 /* 4301 * store a non-null value in "next". 4302 * The userland code will interpret a 4303 * NULL here as a marker 4304 * for the last dynamic rule. 4305 */ 4306 bcopy(&dst, &dst->next, sizeof(dst)); 4307 last = dst; 4308 dst->expire = 4309 TIME_LEQ(dst->expire, time_uptime) ? 4310 0 : dst->expire - time_uptime ; 4311 bp += sizeof(ipfw_dyn_rule); 4312 } 4313 } 4314 IPFW_DYN_UNLOCK(); 4315 if (last != NULL) /* mark last dynamic rule */ 4316 bzero(&last->next, sizeof(last)); 4317 } 4318 return (bp - (char *)buf); 4319} 4320 4321 4322/** 4323 * {set|get}sockopt parser. 4324 */ 4325static int 4326ipfw_ctl(struct sockopt *sopt) 4327{ 4328#define RULE_MAXSIZE (256*sizeof(u_int32_t)) 4329 int error; 4330 size_t size; 4331 struct ip_fw *buf, *rule; 4332 u_int32_t rulenum[2]; 4333 4334 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW); 4335 if (error) 4336 return (error); 4337 4338 /* 4339 * Disallow modifications in really-really secure mode, but still allow 4340 * the logging counters to be reset. 4341 */ 4342 if (sopt->sopt_name == IP_FW_ADD || 4343 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) { 4344 error = securelevel_ge(sopt->sopt_td->td_ucred, 3); 4345 if (error) 4346 return (error); 4347 } 4348 4349 error = 0; 4350 4351 switch (sopt->sopt_name) { 4352 case IP_FW_GET: 4353 /* 4354 * pass up a copy of the current rules. Static rules 4355 * come first (the last of which has number IPFW_DEFAULT_RULE), 4356 * followed by a possibly empty list of dynamic rule. 4357 * The last dynamic rule has NULL in the "next" field. 4358 * 4359 * Note that the calculated size is used to bound the 4360 * amount of data returned to the user. The rule set may 4361 * change between calculating the size and returning the 4362 * data in which case we'll just return what fits. 4363 */ 4364 size = V_static_len; /* size of static rules */ 4365 if (V_ipfw_dyn_v) /* add size of dyn.rules */ 4366 size += (V_dyn_count * sizeof(ipfw_dyn_rule)); 4367 4368 if (size >= sopt->sopt_valsize) 4369 break; 4370 /* 4371 * XXX todo: if the user passes a short length just to know 4372 * how much room is needed, do not bother filling up the 4373 * buffer, just jump to the sooptcopyout. 4374 */ 4375 buf = malloc(size, M_TEMP, M_WAITOK); 4376 error = sooptcopyout(sopt, buf, 4377 ipfw_getrules(&V_layer3_chain, buf, size)); 4378 free(buf, M_TEMP); 4379 break; 4380 4381 case IP_FW_FLUSH: 4382 /* 4383 * Normally we cannot release the lock on each iteration. 4384 * We could do it here only because we start from the head all 4385 * the times so there is no risk of missing some entries. 4386 * On the other hand, the risk is that we end up with 4387 * a very inconsistent ruleset, so better keep the lock 4388 * around the whole cycle. 4389 * 4390 * XXX this code can be improved by resetting the head of 4391 * the list to point to the default rule, and then freeing 4392 * the old list without the need for a lock. 4393 */ 4394 4395 IPFW_WLOCK(&V_layer3_chain); 4396 free_chain(&V_layer3_chain, 0 /* keep default rule */); 4397 rule = V_layer3_chain.reap; 4398 IPFW_WUNLOCK(&V_layer3_chain); 4399 reap_rules(rule); 4400 break; 4401 4402 case IP_FW_ADD: 4403 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK); 4404 error = sooptcopyin(sopt, rule, RULE_MAXSIZE, 4405 sizeof(struct ip_fw) ); 4406 if (error == 0) 4407 error = check_ipfw_struct(rule, sopt->sopt_valsize); 4408 if (error == 0) { 4409 error = add_rule(&V_layer3_chain, rule); 4410 size = RULESIZE(rule); 4411 if (!error && sopt->sopt_dir == SOPT_GET) 4412 error = sooptcopyout(sopt, rule, size); 4413 } 4414 free(rule, M_TEMP); 4415 break; 4416 4417 case IP_FW_DEL: 4418 /* 4419 * IP_FW_DEL is used for deleting single rules or sets, 4420 * and (ab)used to atomically manipulate sets. Argument size 4421 * is used to distinguish between the two: 4422 * sizeof(u_int32_t) 4423 * delete single rule or set of rules, 4424 * or reassign rules (or sets) to a different set. 4425 * 2*sizeof(u_int32_t) 4426 * atomic disable/enable sets. 4427 * first u_int32_t contains sets to be disabled, 4428 * second u_int32_t contains sets to be enabled. 4429 */ 4430 error = sooptcopyin(sopt, rulenum, 4431 2*sizeof(u_int32_t), sizeof(u_int32_t)); 4432 if (error) 4433 break; 4434 size = sopt->sopt_valsize; 4435 if (size == sizeof(u_int32_t)) /* delete or reassign */ 4436 error = del_entry(&V_layer3_chain, rulenum[0]); 4437 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */ 4438 V_set_disable = 4439 (V_set_disable | rulenum[0]) & ~rulenum[1] & 4440 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */ 4441 else 4442 error = EINVAL; 4443 break; 4444 4445 case IP_FW_ZERO: 4446 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */ 4447 rulenum[0] = 0; 4448 if (sopt->sopt_val != 0) { 4449 error = sooptcopyin(sopt, rulenum, 4450 sizeof(u_int32_t), sizeof(u_int32_t)); 4451 if (error) 4452 break; 4453 } 4454 error = zero_entry(&V_layer3_chain, rulenum[0], 4455 sopt->sopt_name == IP_FW_RESETLOG); 4456 break; 4457 4458 case IP_FW_TABLE_ADD: 4459 { 4460 ipfw_table_entry ent; 4461 4462 error = sooptcopyin(sopt, &ent, 4463 sizeof(ent), sizeof(ent)); 4464 if (error) 4465 break; 4466 error = add_table_entry(&V_layer3_chain, ent.tbl, 4467 ent.addr, ent.masklen, ent.value); 4468 } 4469 break; 4470 4471 case IP_FW_TABLE_DEL: 4472 { 4473 ipfw_table_entry ent; 4474 4475 error = sooptcopyin(sopt, &ent, 4476 sizeof(ent), sizeof(ent)); 4477 if (error) 4478 break; 4479 error = del_table_entry(&V_layer3_chain, ent.tbl, 4480 ent.addr, ent.masklen); 4481 } 4482 break; 4483 4484 case IP_FW_TABLE_FLUSH: 4485 { 4486 u_int16_t tbl; 4487 4488 error = sooptcopyin(sopt, &tbl, 4489 sizeof(tbl), sizeof(tbl)); 4490 if (error) 4491 break; 4492 IPFW_WLOCK(&V_layer3_chain); 4493 error = flush_table(&V_layer3_chain, tbl); 4494 IPFW_WUNLOCK(&V_layer3_chain); 4495 } 4496 break; 4497 4498 case IP_FW_TABLE_GETSIZE: 4499 { 4500 u_int32_t tbl, cnt; 4501 4502 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl), 4503 sizeof(tbl)))) 4504 break; 4505 IPFW_RLOCK(&V_layer3_chain); 4506 error = count_table(&V_layer3_chain, tbl, &cnt); 4507 IPFW_RUNLOCK(&V_layer3_chain); 4508 if (error) 4509 break; 4510 error = sooptcopyout(sopt, &cnt, sizeof(cnt)); 4511 } 4512 break; 4513 4514 case IP_FW_TABLE_LIST: 4515 { 4516 ipfw_table *tbl; 4517 4518 if (sopt->sopt_valsize < sizeof(*tbl)) { 4519 error = EINVAL; 4520 break; 4521 } 4522 size = sopt->sopt_valsize; 4523 tbl = malloc(size, M_TEMP, M_WAITOK); 4524 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl)); 4525 if (error) { 4526 free(tbl, M_TEMP); 4527 break; 4528 } 4529 tbl->size = (size - sizeof(*tbl)) / 4530 sizeof(ipfw_table_entry); 4531 IPFW_RLOCK(&V_layer3_chain); 4532 error = dump_table(&V_layer3_chain, tbl); 4533 IPFW_RUNLOCK(&V_layer3_chain); 4534 if (error) { 4535 free(tbl, M_TEMP); 4536 break; 4537 } 4538 error = sooptcopyout(sopt, tbl, size); 4539 free(tbl, M_TEMP); 4540 } 4541 break; 4542 4543 case IP_FW_NAT_CFG: 4544 if (IPFW_NAT_LOADED) 4545 error = ipfw_nat_cfg_ptr(sopt); 4546 else { 4547 printf("IP_FW_NAT_CFG: %s\n", 4548 "ipfw_nat not present, please load it"); 4549 error = EINVAL; 4550 } 4551 break; 4552 4553 case IP_FW_NAT_DEL: 4554 if (IPFW_NAT_LOADED) 4555 error = ipfw_nat_del_ptr(sopt); 4556 else { 4557 printf("IP_FW_NAT_DEL: %s\n", 4558 "ipfw_nat not present, please load it"); 4559 error = EINVAL; 4560 } 4561 break; 4562 4563 case IP_FW_NAT_GET_CONFIG: 4564 if (IPFW_NAT_LOADED) 4565 error = ipfw_nat_get_cfg_ptr(sopt); 4566 else { 4567 printf("IP_FW_NAT_GET_CFG: %s\n", 4568 "ipfw_nat not present, please load it"); 4569 error = EINVAL; 4570 } 4571 break; 4572 4573 case IP_FW_NAT_GET_LOG: 4574 if (IPFW_NAT_LOADED) 4575 error = ipfw_nat_get_log_ptr(sopt); 4576 else { 4577 printf("IP_FW_NAT_GET_LOG: %s\n", 4578 "ipfw_nat not present, please load it"); 4579 error = EINVAL; 4580 } 4581 break; 4582 4583 default: 4584 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name); 4585 error = EINVAL; 4586 } 4587 4588 return (error); 4589#undef RULE_MAXSIZE 4590} 4591 4592 4593/* 4594 * This procedure is only used to handle keepalives. It is invoked 4595 * every dyn_keepalive_period 4596 */ 4597static void 4598ipfw_tick(void * vnetx) 4599{ 4600 struct mbuf *m0, *m, *mnext, **mtailp; 4601#ifdef INET6 4602 struct mbuf *m6, **m6_tailp; 4603#endif 4604 int i; 4605 ipfw_dyn_rule *q; 4606#ifdef VIMAGE 4607 struct vnet *vp = vnetx; 4608#endif 4609 4610 CURVNET_SET(vp); 4611 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0) 4612 goto done; 4613 4614 /* 4615 * We make a chain of packets to go out here -- not deferring 4616 * until after we drop the IPFW dynamic rule lock would result 4617 * in a lock order reversal with the normal packet input -> ipfw 4618 * call stack. 4619 */ 4620 m0 = NULL; 4621 mtailp = &m0; 4622#ifdef INET6 4623 m6 = NULL; 4624 m6_tailp = &m6; 4625#endif 4626 IPFW_DYN_LOCK(); 4627 for (i = 0 ; i < V_curr_dyn_buckets ; i++) { 4628 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) { 4629 if (q->dyn_type == O_LIMIT_PARENT) 4630 continue; 4631 if (q->id.proto != IPPROTO_TCP) 4632 continue; 4633 if ( (q->state & BOTH_SYN) != BOTH_SYN) 4634 continue; 4635 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval, 4636 q->expire)) 4637 continue; /* too early */ 4638 if (TIME_LEQ(q->expire, time_uptime)) 4639 continue; /* too late, rule expired */ 4640 4641 m = send_pkt(NULL, &(q->id), q->ack_rev - 1, 4642 q->ack_fwd, TH_SYN); 4643 mnext = send_pkt(NULL, &(q->id), q->ack_fwd - 1, 4644 q->ack_rev, 0); 4645 4646 switch (q->id.addr_type) { 4647 case 4: 4648 if (m != NULL) { 4649 *mtailp = m; 4650 mtailp = &(*mtailp)->m_nextpkt; 4651 } 4652 if (mnext != NULL) { 4653 *mtailp = mnext; 4654 mtailp = &(*mtailp)->m_nextpkt; 4655 } 4656 break; 4657#ifdef INET6 4658 case 6: 4659 if (m != NULL) { 4660 *m6_tailp = m; 4661 m6_tailp = &(*m6_tailp)->m_nextpkt; 4662 } 4663 if (mnext != NULL) { 4664 *m6_tailp = mnext; 4665 m6_tailp = &(*m6_tailp)->m_nextpkt; 4666 } 4667 break; 4668#endif 4669 } 4670 4671 m = mnext = NULL; 4672 } 4673 } 4674 IPFW_DYN_UNLOCK(); 4675 for (m = mnext = m0; m != NULL; m = mnext) { 4676 mnext = m->m_nextpkt; 4677 m->m_nextpkt = NULL; 4678 ip_output(m, NULL, NULL, 0, NULL, NULL); 4679 } 4680#ifdef INET6 4681 for (m = mnext = m6; m != NULL; m = mnext) { 4682 mnext = m->m_nextpkt; 4683 m->m_nextpkt = NULL; 4684 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL); 4685 } 4686#endif 4687done: 4688 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz, 4689 ipfw_tick, vnetx); 4690 CURVNET_RESTORE(); 4691} 4692 4693/**************** 4694 * Stuff that must be initialised only on boot or module load 4695 */ 4696static int 4697ipfw_init(void) 4698{ 4699 int error = 0; 4700 4701 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule", 4702 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL, 4703 UMA_ALIGN_PTR, 0); 4704 4705 IPFW_DYN_LOCK_INIT(); 4706 /* 4707 * Only print out this stuff the first time around, 4708 * when called from the sysinit code. 4709 */ 4710 printf("ipfw2 " 4711#ifdef INET6 4712 "(+ipv6) " 4713#endif 4714 "initialized, divert %s, nat %s, " 4715 "rule-based forwarding " 4716#ifdef IPFIREWALL_FORWARD 4717 "enabled, " 4718#else 4719 "disabled, " 4720#endif 4721 "default to %s, logging ", 4722#ifdef IPDIVERT 4723 "enabled", 4724#else 4725 "loadable", 4726#endif 4727#ifdef IPFIREWALL_NAT 4728 "enabled", 4729#else 4730 "loadable", 4731#endif 4732 default_to_accept ? "accept" : "deny"); 4733 4734 /* 4735 * Note: V_xxx variables can be accessed here but the vnet specific 4736 * initializer may not have been called yet for the VIMAGE case. 4737 * Tuneables will have been processed. We will print out values for 4738 * the default vnet. 4739 * XXX This should all be rationalized AFTER 8.0 4740 */ 4741 if (V_fw_verbose == 0) 4742 printf("disabled\n"); 4743 else if (V_verbose_limit == 0) 4744 printf("unlimited\n"); 4745 else 4746 printf("limited to %d packets/entry by default\n", 4747 V_verbose_limit); 4748 4749 return (error); 4750} 4751 4752/********************** 4753 * Called for the removal of the last instance only on module unload. 4754 */ 4755static void 4756ipfw_destroy(void) 4757{ 4758 4759 uma_zdestroy(ipfw_dyn_rule_zone); 4760 IPFW_DYN_LOCK_DESTROY(); 4761 printf("IP firewall unloaded\n"); 4762} 4763 4764/**************** 4765 * Stuff that must be initialized for every instance 4766 * (including the first of course). 4767 */ 4768static int 4769vnet_ipfw_init(const void *unused) 4770{ 4771 int error; 4772 struct ip_fw default_rule; 4773 4774 /* First set up some values that are compile time options */ 4775#ifdef IPFIREWALL_VERBOSE 4776 V_fw_verbose = 1; 4777#endif 4778#ifdef IPFIREWALL_VERBOSE_LIMIT 4779 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT; 4780#endif 4781 4782 error = init_tables(&V_layer3_chain); 4783 if (error) { 4784 panic("init_tables"); /* XXX Marko fix this ! */ 4785 } 4786#ifdef IPFIREWALL_NAT 4787 LIST_INIT(&V_layer3_chain.nat); 4788#endif 4789 4790 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */ 4791 4792 V_ipfw_dyn_v = NULL; 4793 V_dyn_buckets = 256; /* must be power of 2 */ 4794 V_curr_dyn_buckets = 256; /* must be power of 2 */ 4795 4796 V_dyn_ack_lifetime = 300; 4797 V_dyn_syn_lifetime = 20; 4798 V_dyn_fin_lifetime = 1; 4799 V_dyn_rst_lifetime = 1; 4800 V_dyn_udp_lifetime = 10; 4801 V_dyn_short_lifetime = 5; 4802 4803 V_dyn_keepalive_interval = 20; 4804 V_dyn_keepalive_period = 5; 4805 V_dyn_keepalive = 1; /* do send keepalives */ 4806 4807 V_dyn_max = 4096; /* max # of dynamic rules */ 4808 4809 V_fw_deny_unknown_exthdrs = 1; 4810 4811 V_layer3_chain.rules = NULL; 4812 IPFW_LOCK_INIT(&V_layer3_chain); 4813 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE); 4814 4815 bzero(&default_rule, sizeof default_rule); 4816 default_rule.act_ofs = 0; 4817 default_rule.rulenum = IPFW_DEFAULT_RULE; 4818 default_rule.cmd_len = 1; 4819 default_rule.set = RESVD_SET; 4820 default_rule.cmd[0].len = 1; 4821 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY; 4822 error = add_rule(&V_layer3_chain, &default_rule); 4823 4824 if (error != 0) { 4825 printf("ipfw2: error %u initializing default rule " 4826 "(support disabled)\n", error); 4827 IPFW_LOCK_DESTROY(&V_layer3_chain); 4828 printf("leaving ipfw_iattach (1) with error %d\n", error); 4829 return (error); 4830 } 4831 4832 ip_fw_default_rule = V_layer3_chain.rules; 4833 4834 if (error) { 4835 IPFW_LOCK_DESTROY(&V_layer3_chain); 4836 printf("leaving ipfw_iattach (2) with error %d\n", error); 4837 return (error); 4838 } 4839#ifdef VIMAGE /* want a better way to do this */ 4840 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet); 4841#else 4842 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL); 4843#endif 4844 4845 /* First set up some values that are compile time options */ 4846 V_ipfw_vnet_ready = 1; /* Open for business */ 4847 4848 /* Hook up the raw inputs */ 4849 V_ip_fw_ctl_ptr = ipfw_ctl; 4850 V_ip_fw_chk_ptr = ipfw_chk; 4851 4852 /* 4853 * Hook us up to pfil. 4854 */ 4855 if (V_fw_enable) { 4856 if ((error = ipfw_hook()) != 0) { 4857 printf("ipfw_hook() error\n"); 4858 return (error); 4859 } 4860 } 4861#ifdef INET6 4862 if (V_fw6_enable) { 4863 if ((error = ipfw6_hook()) != 0) { 4864 printf("ipfw6_hook() error\n"); 4865 /* XXX should we unhook everything else? */ 4866 return (error); 4867 } 4868 } 4869#endif 4870 return (0); 4871} 4872 4873/*********************** 4874 * Called for the removal of each instance. 4875 */ 4876static int 4877vnet_ipfw_uninit(const void *unused) 4878{ 4879 struct ip_fw *reap; 4880 4881 V_ipfw_vnet_ready = 0; /* tell new callers to go away */ 4882 ipfw_unhook(); 4883#ifdef INET6 4884 ipfw6_unhook(); 4885#endif 4886 /* layer2 and other entrypoints still come in this way. */ 4887 V_ip_fw_chk_ptr = NULL; 4888 V_ip_fw_ctl_ptr = NULL; 4889 IPFW_WLOCK(&V_layer3_chain); 4890 /* We wait on the wlock here until the last user leaves */ 4891 IPFW_WUNLOCK(&V_layer3_chain); 4892 IPFW_WLOCK(&V_layer3_chain); 4893 callout_drain(&V_ipfw_timeout); 4894 flush_tables(&V_layer3_chain); 4895 V_layer3_chain.reap = NULL; 4896 free_chain(&V_layer3_chain, 1 /* kill default rule */); 4897 reap = V_layer3_chain.reap; 4898 V_layer3_chain.reap = NULL; 4899 IPFW_WUNLOCK(&V_layer3_chain); 4900 if (reap != NULL) 4901 reap_rules(reap); 4902 IPFW_LOCK_DESTROY(&V_layer3_chain); 4903 if (V_ipfw_dyn_v != NULL) 4904 free(V_ipfw_dyn_v, M_IPFW); 4905 return 0; 4906} 4907 4908/* 4909 * Module event handler. 4910 * In general we have the choice of handling most of these events by the 4911 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to 4912 * use the SYSINIT handlers as they are more capable of expressing the 4913 * flow of control during module and vnet operations, so this is just 4914 * a skeleton. Note there is no SYSINIT equivalent of the module 4915 * SHUTDOWN handler, but we don't have anything to do in that case anyhow. 4916 */ 4917static int 4918ipfw_modevent(module_t mod, int type, void *unused) 4919{ 4920 int err = 0; 4921 4922 switch (type) { 4923 case MOD_LOAD: 4924 /* Called once at module load or 4925 * system boot if compiled in. */ 4926 break; 4927 case MOD_QUIESCE: 4928 /* Called before unload. May veto unloading. */ 4929 break; 4930 case MOD_UNLOAD: 4931 /* Called during unload. */ 4932 break; 4933 case MOD_SHUTDOWN: 4934 /* Called during system shutdown. */ 4935 break; 4936 default: 4937 err = EOPNOTSUPP; 4938 break; 4939 } 4940 return err; 4941} 4942 4943static moduledata_t ipfwmod = { 4944 "ipfw", 4945 ipfw_modevent, 4946 0 4947}; 4948 4949/* Define startup order. */ 4950#define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN 4951#define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */ 4952#define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */ 4953#define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */ 4954 4955DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER); 4956MODULE_VERSION(ipfw, 2); 4957/* should declare some dependencies here */ 4958 4959/* 4960 * Starting up. Done in order after ipfwmod() has been called. 4961 * VNET_SYSINIT is also called for each existing vnet and each new vnet. 4962 */ 4963SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER, 4964 ipfw_init, NULL); 4965VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER, 4966 vnet_ipfw_init, NULL); 4967 4968/* 4969 * Closing up shop. These are done in REVERSE ORDER, but still 4970 * after ipfwmod() has been called. Not called on reboot. 4971 * VNET_SYSUNINIT is also called for each exiting vnet as it exits. 4972 * or when the module is unloaded. 4973 */ 4974SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER, 4975 ipfw_destroy, NULL); 4976VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER, 4977 vnet_ipfw_uninit, NULL); 4978 4979