The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/ip_fw2.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    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  * $FreeBSD: releng/6.0/sys/netinet/ip_fw2.c 154217 2006-01-11 08:03:18Z cperciva $
   26  */
   27 
   28 #define        DEB(x)
   29 #define        DDB(x) x
   30 
   31 /*
   32  * Implement IP packet firewall (new version)
   33  */
   34 
   35 #if !defined(KLD_MODULE)
   36 #include "opt_ipfw.h"
   37 #include "opt_ip6fw.h"
   38 #include "opt_ipdn.h"
   39 #include "opt_inet.h"
   40 #include "opt_inet6.h"
   41 #include "opt_ipsec.h"
   42 #ifndef INET
   43 #error IPFIREWALL requires INET.
   44 #endif /* INET */
   45 #endif
   46 
   47 #include <sys/param.h>
   48 #include <sys/systm.h>
   49 #include <sys/condvar.h>
   50 #include <sys/malloc.h>
   51 #include <sys/mbuf.h>
   52 #include <sys/kernel.h>
   53 #include <sys/jail.h>
   54 #include <sys/module.h>
   55 #include <sys/proc.h>
   56 #include <sys/socket.h>
   57 #include <sys/socketvar.h>
   58 #include <sys/sysctl.h>
   59 #include <sys/syslog.h>
   60 #include <sys/ucred.h>
   61 #include <net/if.h>
   62 #include <net/radix.h>
   63 #include <net/route.h>
   64 #include <netinet/in.h>
   65 #include <netinet/in_systm.h>
   66 #include <netinet/in_var.h>
   67 #include <netinet/in_pcb.h>
   68 #include <netinet/ip.h>
   69 #include <netinet/ip_var.h>
   70 #include <netinet/ip_icmp.h>
   71 #include <netinet/ip_fw.h>
   72 #include <netinet/ip_divert.h>
   73 #include <netinet/ip_dummynet.h>
   74 #include <netinet/tcp.h>
   75 #include <netinet/tcp_timer.h>
   76 #include <netinet/tcp_var.h>
   77 #include <netinet/tcpip.h>
   78 #include <netinet/udp.h>
   79 #include <netinet/udp_var.h>
   80 
   81 #include <netgraph/ng_ipfw.h>
   82 
   83 #include <altq/if_altq.h>
   84 
   85 #ifdef IPSEC
   86 #include <netinet6/ipsec.h>
   87 #endif
   88 
   89 #include <netinet/ip6.h>
   90 #include <netinet/icmp6.h>
   91 
   92 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
   93 
   94 #include <machine/in_cksum.h>   /* XXX for in_cksum */
   95 
   96 /*
   97  * set_disable contains one bit per set value (0..31).
   98  * If the bit is set, all rules with the corresponding set
   99  * are disabled. Set RESVD_SET(31) is reserved for the default rule
  100  * and rules that are not deleted by the flush command,
  101  * and CANNOT be disabled.
  102  * Rules in set RESVD_SET can only be deleted explicitly.
  103  */
  104 static u_int32_t set_disable;
  105 
  106 static int fw_verbose;
  107 static int verbose_limit;
  108 
  109 static struct callout ipfw_timeout;
  110 static uma_zone_t ipfw_dyn_rule_zone;
  111 #define IPFW_DEFAULT_RULE       65535
  112 
  113 /*
  114  * Data structure to cache our ucred related
  115  * information. This structure only gets used if
  116  * the user specified UID/GID based constraints in
  117  * a firewall rule.
  118  */
  119 struct ip_fw_ugid {
  120         gid_t           fw_groups[NGROUPS];
  121         int             fw_ngroups;
  122         uid_t           fw_uid;
  123         int             fw_prid;
  124 };
  125 
  126 struct ip_fw_chain {
  127         struct ip_fw    *rules;         /* list of rules */
  128         struct ip_fw    *reap;          /* list of rules to reap */
  129         struct mtx      mtx;            /* lock guarding rule list */
  130         int             busy_count;     /* busy count for rw locks */
  131         int             want_write;
  132         struct cv       cv;
  133 };
  134 #define IPFW_LOCK_INIT(_chain) \
  135         mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
  136                 MTX_DEF | MTX_RECURSE)
  137 #define IPFW_LOCK_DESTROY(_chain)       mtx_destroy(&(_chain)->mtx)
  138 #define IPFW_WLOCK_ASSERT(_chain)       do {                            \
  139         mtx_assert(&(_chain)->mtx, MA_OWNED);                           \
  140         NET_ASSERT_GIANT();                                             \
  141 } while (0)
  142 
  143 static __inline void
  144 IPFW_RLOCK(struct ip_fw_chain *chain)
  145 {
  146         mtx_lock(&chain->mtx);
  147         chain->busy_count++;
  148         mtx_unlock(&chain->mtx);
  149 }
  150 
  151 static __inline void
  152 IPFW_RUNLOCK(struct ip_fw_chain *chain)
  153 {
  154         mtx_lock(&chain->mtx);
  155         chain->busy_count--;
  156         if (chain->busy_count == 0 && chain->want_write)
  157                 cv_signal(&chain->cv);
  158         mtx_unlock(&chain->mtx);
  159 }
  160 
  161 static __inline void
  162 IPFW_WLOCK(struct ip_fw_chain *chain)
  163 {
  164         mtx_lock(&chain->mtx);
  165         chain->want_write++;
  166         while (chain->busy_count > 0)
  167                 cv_wait(&chain->cv, &chain->mtx);
  168 }
  169 
  170 static __inline void
  171 IPFW_WUNLOCK(struct ip_fw_chain *chain)
  172 {
  173         chain->want_write--;
  174         cv_signal(&chain->cv);
  175         mtx_unlock(&chain->mtx);
  176 }
  177 
  178 /*
  179  * list of rules for layer 3
  180  */
  181 static struct ip_fw_chain layer3_chain;
  182 
  183 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
  184 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
  185 
  186 struct table_entry {
  187         struct radix_node       rn[2];
  188         struct sockaddr_in      addr, mask;
  189         u_int32_t               value;
  190 };
  191 
  192 #define IPFW_TABLES_MAX         128
  193 static struct ip_fw_table {
  194         struct radix_node_head  *rnh;
  195         int                     modified;
  196         in_addr_t               last_addr;
  197         int                     last_match;
  198         u_int32_t               last_value;
  199 } ipfw_tables[IPFW_TABLES_MAX];
  200 
  201 static int fw_debug = 1;
  202 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
  203 
  204 #ifdef SYSCTL_NODE
  205 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
  206 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
  207     CTLFLAG_RW | CTLFLAG_SECURE3,
  208     &fw_enable, 0, "Enable ipfw");
  209 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
  210     &autoinc_step, 0, "Rule number autincrement step");
  211 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
  212     CTLFLAG_RW | CTLFLAG_SECURE3,
  213     &fw_one_pass, 0,
  214     "Only do a single pass through ipfw when using dummynet(4)");
  215 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
  216     &fw_debug, 0, "Enable printing of debug ip_fw statements");
  217 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
  218     CTLFLAG_RW | CTLFLAG_SECURE3,
  219     &fw_verbose, 0, "Log matches to ipfw rules");
  220 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
  221     &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
  222 
  223 /*
  224  * Description of dynamic rules.
  225  *
  226  * Dynamic rules are stored in lists accessed through a hash table
  227  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
  228  * be modified through the sysctl variable dyn_buckets which is
  229  * updated when the table becomes empty.
  230  *
  231  * XXX currently there is only one list, ipfw_dyn.
  232  *
  233  * When a packet is received, its address fields are first masked
  234  * with the mask defined for the rule, then hashed, then matched
  235  * against the entries in the corresponding list.
  236  * Dynamic rules can be used for different purposes:
  237  *  + stateful rules;
  238  *  + enforcing limits on the number of sessions;
  239  *  + in-kernel NAT (not implemented yet)
  240  *
  241  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
  242  * measured in seconds and depending on the flags.
  243  *
  244  * The total number of dynamic rules is stored in dyn_count.
  245  * The max number of dynamic rules is dyn_max. When we reach
  246  * the maximum number of rules we do not create anymore. This is
  247  * done to avoid consuming too much memory, but also too much
  248  * time when searching on each packet (ideally, we should try instead
  249  * to put a limit on the length of the list on each bucket...).
  250  *
  251  * Each dynamic rule holds a pointer to the parent ipfw rule so
  252  * we know what action to perform. Dynamic rules are removed when
  253  * the parent rule is deleted. XXX we should make them survive.
  254  *
  255  * There are some limitations with dynamic rules -- we do not
  256  * obey the 'randomized match', and we do not do multiple
  257  * passes through the firewall. XXX check the latter!!!
  258  */
  259 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
  260 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
  261 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
  262 
  263 static struct mtx ipfw_dyn_mtx;         /* mutex guarding dynamic rules */
  264 #define IPFW_DYN_LOCK_INIT() \
  265         mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
  266 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
  267 #define IPFW_DYN_LOCK()         mtx_lock(&ipfw_dyn_mtx)
  268 #define IPFW_DYN_UNLOCK()       mtx_unlock(&ipfw_dyn_mtx)
  269 #define IPFW_DYN_LOCK_ASSERT()  mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
  270 
  271 /*
  272  * Timeouts for various events in handing dynamic rules.
  273  */
  274 static u_int32_t dyn_ack_lifetime = 300;
  275 static u_int32_t dyn_syn_lifetime = 20;
  276 static u_int32_t dyn_fin_lifetime = 1;
  277 static u_int32_t dyn_rst_lifetime = 1;
  278 static u_int32_t dyn_udp_lifetime = 10;
  279 static u_int32_t dyn_short_lifetime = 5;
  280 
  281 /*
  282  * Keepalives are sent if dyn_keepalive is set. They are sent every
  283  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
  284  * seconds of lifetime of a rule.
  285  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
  286  * than dyn_keepalive_period.
  287  */
  288 
  289 static u_int32_t dyn_keepalive_interval = 20;
  290 static u_int32_t dyn_keepalive_period = 5;
  291 static u_int32_t dyn_keepalive = 1;     /* do send keepalives */
  292 
  293 static u_int32_t static_count;  /* # of static rules */
  294 static u_int32_t static_len;    /* size in bytes of static rules */
  295 static u_int32_t dyn_count;             /* # of dynamic rules */
  296 static u_int32_t dyn_max = 4096;        /* max # of dynamic rules */
  297 
  298 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
  299     &dyn_buckets, 0, "Number of dyn. buckets");
  300 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
  301     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
  302 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
  303     &dyn_count, 0, "Number of dyn. rules");
  304 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
  305     &dyn_max, 0, "Max number of dyn. rules");
  306 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
  307     &static_count, 0, "Number of static rules");
  308 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
  309     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
  310 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
  311     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
  312 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
  313     &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
  314 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
  315     &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
  316 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
  317     &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
  318 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
  319     &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
  320 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
  321     &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
  322 
  323 #ifdef INET6
  324 /*
  325  * IPv6 specific variables
  326  */
  327 SYSCTL_DECL(_net_inet6_ip6);
  328 
  329 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
  330 static struct sysctl_oid *ip6_fw_sysctl_tree;
  331 #endif /* INET6 */
  332 #endif /* SYSCTL_NODE */
  333 
  334 static int fw_deny_unknown_exthdrs = 1;
  335 
  336 
  337 /*
  338  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
  339  * Other macros just cast void * into the appropriate type
  340  */
  341 #define L3HDR(T, ip)    ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
  342 #define TCP(p)          ((struct tcphdr *)(p))
  343 #define UDP(p)          ((struct udphdr *)(p))
  344 #define ICMP(p)         ((struct icmphdr *)(p))
  345 #define ICMP6(p)        ((struct icmp6_hdr *)(p))
  346 
  347 static __inline int
  348 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
  349 {
  350         int type = icmp->icmp_type;
  351 
  352         return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
  353 }
  354 
  355 #define TT      ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
  356     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
  357 
  358 static int
  359 is_icmp_query(struct icmphdr *icmp)
  360 {
  361         int type = icmp->icmp_type;
  362 
  363         return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
  364 }
  365 #undef TT
  366 
  367 /*
  368  * The following checks use two arrays of 8 or 16 bits to store the
  369  * bits that we want set or clear, respectively. They are in the
  370  * low and high half of cmd->arg1 or cmd->d[0].
  371  *
  372  * We scan options and store the bits we find set. We succeed if
  373  *
  374  *      (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
  375  *
  376  * The code is sometimes optimized not to store additional variables.
  377  */
  378 
  379 static int
  380 flags_match(ipfw_insn *cmd, u_int8_t bits)
  381 {
  382         u_char want_clear;
  383         bits = ~bits;
  384 
  385         if ( ((cmd->arg1 & 0xff) & bits) != 0)
  386                 return 0; /* some bits we want set were clear */
  387         want_clear = (cmd->arg1 >> 8) & 0xff;
  388         if ( (want_clear & bits) != want_clear)
  389                 return 0; /* some bits we want clear were set */
  390         return 1;
  391 }
  392 
  393 static int
  394 ipopts_match(struct ip *ip, ipfw_insn *cmd)
  395 {
  396         int optlen, bits = 0;
  397         u_char *cp = (u_char *)(ip + 1);
  398         int x = (ip->ip_hl << 2) - sizeof (struct ip);
  399 
  400         for (; x > 0; x -= optlen, cp += optlen) {
  401                 int opt = cp[IPOPT_OPTVAL];
  402 
  403                 if (opt == IPOPT_EOL)
  404                         break;
  405                 if (opt == IPOPT_NOP)
  406                         optlen = 1;
  407                 else {
  408                         optlen = cp[IPOPT_OLEN];
  409                         if (optlen <= 0 || optlen > x)
  410                                 return 0; /* invalid or truncated */
  411                 }
  412                 switch (opt) {
  413 
  414                 default:
  415                         break;
  416 
  417                 case IPOPT_LSRR:
  418                         bits |= IP_FW_IPOPT_LSRR;
  419                         break;
  420 
  421                 case IPOPT_SSRR:
  422                         bits |= IP_FW_IPOPT_SSRR;
  423                         break;
  424 
  425                 case IPOPT_RR:
  426                         bits |= IP_FW_IPOPT_RR;
  427                         break;
  428 
  429                 case IPOPT_TS:
  430                         bits |= IP_FW_IPOPT_TS;
  431                         break;
  432                 }
  433         }
  434         return (flags_match(cmd, bits));
  435 }
  436 
  437 static int
  438 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
  439 {
  440         int optlen, bits = 0;
  441         u_char *cp = (u_char *)(tcp + 1);
  442         int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
  443 
  444         for (; x > 0; x -= optlen, cp += optlen) {
  445                 int opt = cp[0];
  446                 if (opt == TCPOPT_EOL)
  447                         break;
  448                 if (opt == TCPOPT_NOP)
  449                         optlen = 1;
  450                 else {
  451                         optlen = cp[1];
  452                         if (optlen <= 0)
  453                                 break;
  454                 }
  455 
  456                 switch (opt) {
  457 
  458                 default:
  459                         break;
  460 
  461                 case TCPOPT_MAXSEG:
  462                         bits |= IP_FW_TCPOPT_MSS;
  463                         break;
  464 
  465                 case TCPOPT_WINDOW:
  466                         bits |= IP_FW_TCPOPT_WINDOW;
  467                         break;
  468 
  469                 case TCPOPT_SACK_PERMITTED:
  470                 case TCPOPT_SACK:
  471                         bits |= IP_FW_TCPOPT_SACK;
  472                         break;
  473 
  474                 case TCPOPT_TIMESTAMP:
  475                         bits |= IP_FW_TCPOPT_TS;
  476                         break;
  477 
  478                 }
  479         }
  480         return (flags_match(cmd, bits));
  481 }
  482 
  483 static int
  484 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
  485 {
  486         if (ifp == NULL)        /* no iface with this packet, match fails */
  487                 return 0;
  488         /* Check by name or by IP address */
  489         if (cmd->name[0] != '\0') { /* match by name */
  490                 /* Check name */
  491                 if (cmd->p.glob) {
  492                         if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
  493                                 return(1);
  494                 } else {
  495                         if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
  496                                 return(1);
  497                 }
  498         } else {
  499                 struct ifaddr *ia;
  500 
  501                 /* XXX lock? */
  502                 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
  503                         if (ia->ifa_addr == NULL)
  504                                 continue;
  505                         if (ia->ifa_addr->sa_family != AF_INET)
  506                                 continue;
  507                         if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
  508                             (ia->ifa_addr))->sin_addr.s_addr)
  509                                 return(1);      /* match */
  510                 }
  511         }
  512         return(0);      /* no match, fail ... */
  513 }
  514 
  515 /*
  516  * The verify_path function checks if a route to the src exists and
  517  * if it is reachable via ifp (when provided).
  518  * 
  519  * The 'verrevpath' option checks that the interface that an IP packet
  520  * arrives on is the same interface that traffic destined for the
  521  * packet's source address would be routed out of.  The 'versrcreach'
  522  * option just checks that the source address is reachable via any route
  523  * (except default) in the routing table.  These two are a measure to block
  524  * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
  525  * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
  526  * is purposely reminiscent of the Cisco IOS command,
  527  *
  528  *   ip verify unicast reverse-path
  529  *   ip verify unicast source reachable-via any
  530  *
  531  * which implements the same functionality. But note that syntax is
  532  * misleading. The check may be performed on all IP packets whether unicast,
  533  * multicast, or broadcast.
  534  */
  535 static int
  536 verify_path(struct in_addr src, struct ifnet *ifp)
  537 {
  538         struct route ro;
  539         struct sockaddr_in *dst;
  540 
  541         bzero(&ro, sizeof(ro));
  542 
  543         dst = (struct sockaddr_in *)&(ro.ro_dst);
  544         dst->sin_family = AF_INET;
  545         dst->sin_len = sizeof(*dst);
  546         dst->sin_addr = src;
  547         rtalloc_ign(&ro, RTF_CLONING);
  548 
  549         if (ro.ro_rt == NULL)
  550                 return 0;
  551 
  552         /* if ifp is provided, check for equality with rtentry */
  553         if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
  554                 RTFREE(ro.ro_rt);
  555                 return 0;
  556         }
  557 
  558         /* if no ifp provided, check if rtentry is not default route */
  559         if (ifp == NULL &&
  560              satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
  561                 RTFREE(ro.ro_rt);
  562                 return 0;
  563         }
  564 
  565         /* or if this is a blackhole/reject route */
  566         if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
  567                 RTFREE(ro.ro_rt);
  568                 return 0;
  569         }
  570 
  571         /* found valid route */
  572         RTFREE(ro.ro_rt);
  573         return 1;
  574 }
  575 
  576 #ifdef INET6
  577 /*
  578  * ipv6 specific rules here...
  579  */
  580 static __inline int
  581 icmp6type_match (int type, ipfw_insn_u32 *cmd)
  582 {
  583         return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
  584 }
  585 
  586 static int
  587 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
  588 {
  589         int i;
  590         for (i=0; i <= cmd->o.arg1; ++i )
  591                 if (curr_flow == cmd->d[i] )
  592                         return 1;
  593         return 0;
  594 }
  595 
  596 /* support for IP6_*_ME opcodes */
  597 static int
  598 search_ip6_addr_net (struct in6_addr * ip6_addr)
  599 {
  600         struct ifnet *mdc;
  601         struct ifaddr *mdc2;
  602         struct in6_ifaddr *fdm;
  603         struct in6_addr copia;
  604 
  605         TAILQ_FOREACH(mdc, &ifnet, if_link)
  606                 for (mdc2 = mdc->if_addrlist.tqh_first; mdc2;
  607                     mdc2 = mdc2->ifa_list.tqe_next) {
  608                         if (!mdc2->ifa_addr)
  609                                 continue;
  610                         if (mdc2->ifa_addr->sa_family == AF_INET6) {
  611                                 fdm = (struct in6_ifaddr *)mdc2;
  612                                 copia = fdm->ia_addr.sin6_addr;
  613                                 /* need for leaving scope_id in the sock_addr */
  614                                 in6_clearscope(&copia);
  615                                 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
  616                                         return 1;
  617                         }
  618                 }
  619         return 0;
  620 }
  621 
  622 static int
  623 verify_path6(struct in6_addr *src, struct ifnet *ifp)
  624 {
  625         struct route_in6 ro;
  626         struct sockaddr_in6 *dst;
  627 
  628         bzero(&ro, sizeof(ro));
  629 
  630         dst = (struct sockaddr_in6 * )&(ro.ro_dst);
  631         dst->sin6_family = AF_INET6;
  632         dst->sin6_len = sizeof(*dst);
  633         dst->sin6_addr = *src;
  634         rtalloc_ign((struct route *)&ro, RTF_CLONING);
  635 
  636         if (ro.ro_rt == NULL)
  637                 return 0;
  638 
  639         /* if ifp is provided, check for equality with rtentry */
  640         if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
  641                 RTFREE(ro.ro_rt);
  642                 return 0;
  643         }
  644 
  645         /* if no ifp provided, check if rtentry is not default route */
  646         if (ifp == NULL &&
  647             IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
  648                 RTFREE(ro.ro_rt);
  649                 return 0;
  650         }
  651 
  652         /* or if this is a blackhole/reject route */
  653         if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
  654                 RTFREE(ro.ro_rt);
  655                 return 0;
  656         }
  657 
  658         /* found valid route */
  659         RTFREE(ro.ro_rt);
  660         return 1;
  661 
  662 }
  663 static __inline int
  664 hash_packet6(struct ipfw_flow_id *id)
  665 {
  666         u_int32_t i;
  667         i = (id->dst_ip6.__u6_addr.__u6_addr32[0]) ^
  668             (id->dst_ip6.__u6_addr.__u6_addr32[1]) ^
  669             (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
  670             (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
  671             (id->dst_port) ^ (id->src_port) ^ (id->flow_id6);
  672         return i;
  673 }
  674 
  675 static int
  676 is_icmp6_query(int icmp6_type)
  677 {
  678         if ((icmp6_type <= ICMP6_MAXTYPE) &&
  679             (icmp6_type == ICMP6_ECHO_REQUEST ||
  680             icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
  681             icmp6_type == ICMP6_WRUREQUEST ||
  682             icmp6_type == ICMP6_FQDN_QUERY ||
  683             icmp6_type == ICMP6_NI_QUERY))
  684                 return (1);
  685 
  686         return (0);
  687 }
  688 
  689 static void
  690 send_reject6(struct ip_fw_args *args, int code, u_short offset, u_int hlen)
  691 {
  692         if (code == ICMP6_UNREACH_RST && offset == 0 &&
  693             args->f_id.proto == IPPROTO_TCP) {
  694                 struct ip6_hdr *ip6;
  695                 struct tcphdr *tcp;
  696                 tcp_seq ack, seq;
  697                 int flags;
  698                 struct {
  699                         struct ip6_hdr ip6;
  700                         struct tcphdr th;
  701                 } ti;
  702 
  703                 if (args->m->m_len < (hlen+sizeof(struct tcphdr))) {
  704                         args->m = m_pullup(args->m, hlen+sizeof(struct tcphdr));
  705                         if (args->m == NULL)
  706                                 return;
  707                 }
  708 
  709                 ip6 = mtod(args->m, struct ip6_hdr *);
  710                 tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
  711 
  712                 if ((tcp->th_flags & TH_RST) != 0) {
  713                         m_freem(args->m);
  714                         return;
  715                 }
  716 
  717                 ti.ip6 = *ip6;
  718                 ti.th = *tcp;
  719                 ti.th.th_seq = ntohl(ti.th.th_seq);
  720                 ti.th.th_ack = ntohl(ti.th.th_ack);
  721                 ti.ip6.ip6_nxt = IPPROTO_TCP;
  722 
  723                 if (ti.th.th_flags & TH_ACK) {
  724                         ack = 0;
  725                         seq = ti.th.th_ack;
  726                         flags = TH_RST;
  727                 } else {
  728                         ack = ti.th.th_seq;
  729                         if (((args->m)->m_flags & M_PKTHDR) != 0) {
  730                                 ack += (args->m)->m_pkthdr.len - hlen
  731                                         - (ti.th.th_off << 2);
  732                         } else if (ip6->ip6_plen) {
  733                                 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6)
  734                                         - hlen - (ti.th.th_off << 2);
  735                         } else {
  736                                 m_freem(args->m);
  737                                 return;
  738                         }
  739                         if (tcp->th_flags & TH_SYN)
  740                                 ack++;
  741                         seq = 0;
  742                         flags = TH_RST|TH_ACK;
  743                 }
  744                 bcopy(&ti, ip6, sizeof(ti));
  745                 tcp_respond(NULL, ip6, (struct tcphdr *)(ip6 + 1),
  746                         args->m, ack, seq, flags);
  747 
  748         } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
  749                 icmp6_error(args->m, ICMP6_DST_UNREACH, code, 0);
  750 
  751         } else
  752                 m_freem(args->m);
  753 
  754         args->m = NULL;
  755 }
  756 
  757 #endif /* INET6 */
  758 
  759 static u_int64_t norule_counter;        /* counter for ipfw_log(NULL...) */
  760 
  761 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
  762 #define SNP(buf) buf, sizeof(buf)
  763 
  764 /*
  765  * We enter here when we have a rule with O_LOG.
  766  * XXX this function alone takes about 2Kbytes of code!
  767  */
  768 static void
  769 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
  770         struct mbuf *m, struct ifnet *oif, u_short offset)
  771 {
  772         struct ether_header *eh = args->eh;
  773         char *action;
  774         int limit_reached = 0;
  775         char action2[40], proto[128], fragment[32];
  776 
  777         fragment[0] = '\0';
  778         proto[0] = '\0';
  779 
  780         if (f == NULL) {        /* bogus pkt */
  781                 if (verbose_limit != 0 && norule_counter >= verbose_limit)
  782                         return;
  783                 norule_counter++;
  784                 if (norule_counter == verbose_limit)
  785                         limit_reached = verbose_limit;
  786                 action = "Refuse";
  787         } else {        /* O_LOG is the first action, find the real one */
  788                 ipfw_insn *cmd = ACTION_PTR(f);
  789                 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
  790 
  791                 if (l->max_log != 0 && l->log_left == 0)
  792                         return;
  793                 l->log_left--;
  794                 if (l->log_left == 0)
  795                         limit_reached = l->max_log;
  796                 cmd += F_LEN(cmd);      /* point to first action */
  797                 if (cmd->opcode == O_ALTQ) {
  798                         ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
  799 
  800                         snprintf(SNPARGS(action2, 0), "Altq %d",
  801                                 altq->qid);
  802                         cmd += F_LEN(cmd);
  803                 }
  804                 if (cmd->opcode == O_PROB)
  805                         cmd += F_LEN(cmd);
  806 
  807                 action = action2;
  808                 switch (cmd->opcode) {
  809                 case O_DENY:
  810                         action = "Deny";
  811                         break;
  812 
  813                 case O_REJECT:
  814                         if (cmd->arg1==ICMP_REJECT_RST)
  815                                 action = "Reset";
  816                         else if (cmd->arg1==ICMP_UNREACH_HOST)
  817                                 action = "Reject";
  818                         else
  819                                 snprintf(SNPARGS(action2, 0), "Unreach %d",
  820                                         cmd->arg1);
  821                         break;
  822 
  823                 case O_UNREACH6:
  824                         if (cmd->arg1==ICMP6_UNREACH_RST)
  825                                 action = "Reset";
  826                         else
  827                                 snprintf(SNPARGS(action2, 0), "Unreach %d",
  828                                         cmd->arg1);
  829                         break;
  830 
  831                 case O_ACCEPT:
  832                         action = "Accept";
  833                         break;
  834                 case O_COUNT:
  835                         action = "Count";
  836                         break;
  837                 case O_DIVERT:
  838                         snprintf(SNPARGS(action2, 0), "Divert %d",
  839                                 cmd->arg1);
  840                         break;
  841                 case O_TEE:
  842                         snprintf(SNPARGS(action2, 0), "Tee %d",
  843                                 cmd->arg1);
  844                         break;
  845                 case O_SKIPTO:
  846                         snprintf(SNPARGS(action2, 0), "SkipTo %d",
  847                                 cmd->arg1);
  848                         break;
  849                 case O_PIPE:
  850                         snprintf(SNPARGS(action2, 0), "Pipe %d",
  851                                 cmd->arg1);
  852                         break;
  853                 case O_QUEUE:
  854                         snprintf(SNPARGS(action2, 0), "Queue %d",
  855                                 cmd->arg1);
  856                         break;
  857                 case O_FORWARD_IP: {
  858                         ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
  859                         int len;
  860 
  861                         len = snprintf(SNPARGS(action2, 0), "Forward to %s",
  862                                 inet_ntoa(sa->sa.sin_addr));
  863                         if (sa->sa.sin_port)
  864                                 snprintf(SNPARGS(action2, len), ":%d",
  865                                     sa->sa.sin_port);
  866                         }
  867                         break;
  868                 case O_NETGRAPH:
  869                         snprintf(SNPARGS(action2, 0), "Netgraph %d",
  870                                 cmd->arg1);
  871                         break;
  872                 case O_NGTEE:
  873                         snprintf(SNPARGS(action2, 0), "Ngtee %d",
  874                                 cmd->arg1);
  875                         break;
  876                 default:
  877                         action = "UNKNOWN";
  878                         break;
  879                 }
  880         }
  881 
  882         if (hlen == 0) {        /* non-ip */
  883                 snprintf(SNPARGS(proto, 0), "MAC");
  884 
  885         } else {
  886                 int len;
  887                 char src[48], dst[48];
  888                 struct icmphdr *icmp;
  889                 struct tcphdr *tcp;
  890                 struct udphdr *udp;
  891                 /* Initialize to make compiler happy. */
  892                 struct ip *ip = NULL;
  893 #ifdef INET6
  894                 struct ip6_hdr *ip6 = NULL;
  895                 struct icmp6_hdr *icmp6;
  896 #endif
  897                 src[0] = '\0';
  898                 dst[0] = '\0';
  899 #ifdef INET6
  900                 if (args->f_id.addr_type == 6) {
  901                         snprintf(src, sizeof(src), "[%s]",
  902                             ip6_sprintf(&args->f_id.src_ip6));
  903                         snprintf(dst, sizeof(dst), "[%s]",
  904                             ip6_sprintf(&args->f_id.dst_ip6));
  905 
  906                         ip6 = (struct ip6_hdr *)mtod(m, struct ip6_hdr *);
  907                         tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
  908                         udp = (struct udphdr *)(mtod(args->m, char *) + hlen);
  909                 } else
  910 #endif
  911                 {
  912                         ip = mtod(m, struct ip *);
  913                         tcp = L3HDR(struct tcphdr, ip);
  914                         udp = L3HDR(struct udphdr, ip);
  915 
  916                         inet_ntoa_r(ip->ip_src, src);
  917                         inet_ntoa_r(ip->ip_dst, dst);
  918                 }
  919 
  920                 switch (args->f_id.proto) {
  921                 case IPPROTO_TCP:
  922                         len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
  923                         if (offset == 0)
  924                                 snprintf(SNPARGS(proto, len), ":%d %s:%d",
  925                                     ntohs(tcp->th_sport),
  926                                     dst,
  927                                     ntohs(tcp->th_dport));
  928                         else
  929                                 snprintf(SNPARGS(proto, len), " %s", dst);
  930                         break;
  931 
  932                 case IPPROTO_UDP:
  933                         len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
  934                         if (offset == 0)
  935                                 snprintf(SNPARGS(proto, len), ":%d %s:%d",
  936                                     ntohs(udp->uh_sport),
  937                                     dst,
  938                                     ntohs(udp->uh_dport));
  939                         else
  940                                 snprintf(SNPARGS(proto, len), " %s", dst);
  941                         break;
  942 
  943                 case IPPROTO_ICMP:
  944                         icmp = L3HDR(struct icmphdr, ip);
  945                         if (offset == 0)
  946                                 len = snprintf(SNPARGS(proto, 0),
  947                                     "ICMP:%u.%u ",
  948                                     icmp->icmp_type, icmp->icmp_code);
  949                         else
  950                                 len = snprintf(SNPARGS(proto, 0), "ICMP ");
  951                         len += snprintf(SNPARGS(proto, len), "%s", src);
  952                         snprintf(SNPARGS(proto, len), " %s", dst);
  953                         break;
  954 #ifdef INET6
  955                 case IPPROTO_ICMPV6:
  956                         icmp6 = (struct icmp6_hdr *)(mtod(args->m, char *) + hlen);
  957                         if (offset == 0)
  958                                 len = snprintf(SNPARGS(proto, 0),
  959                                     "ICMPv6:%u.%u ",
  960                                     icmp6->icmp6_type, icmp6->icmp6_code);
  961                         else
  962                                 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
  963                         len += snprintf(SNPARGS(proto, len), "%s", src);
  964                         snprintf(SNPARGS(proto, len), " %s", dst);
  965                         break;
  966 #endif
  967                 default:
  968                         len = snprintf(SNPARGS(proto, 0), "P:%d %s",
  969                             args->f_id.proto, src);
  970                         snprintf(SNPARGS(proto, len), " %s", dst);
  971                         break;
  972                 }
  973 
  974 #ifdef INET6
  975                 if (args->f_id.addr_type == 6) {
  976                         if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
  977                                 snprintf(SNPARGS(fragment, 0),
  978                                     " (frag %08x:%d@%d%s)",
  979                                     args->f_id.frag_id6,
  980                                     ntohs(ip6->ip6_plen) - hlen,
  981                                     ntohs(offset & IP6F_OFF_MASK) << 3,
  982                                     (offset & IP6F_MORE_FRAG) ? "+" : "");
  983                 } else
  984 #endif
  985                 {
  986                         int ip_off, ip_len;
  987                         if (eh != NULL) { /* layer 2 packets are as on the wire */
  988                                 ip_off = ntohs(ip->ip_off);
  989                                 ip_len = ntohs(ip->ip_len);
  990                         } else {
  991                                 ip_off = ip->ip_off;
  992                                 ip_len = ip->ip_len;
  993                         }
  994                         if (ip_off & (IP_MF | IP_OFFMASK))
  995                                 snprintf(SNPARGS(fragment, 0),
  996                                     " (frag %d:%d@%d%s)",
  997                                     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
  998                                     offset << 3,
  999                                     (ip_off & IP_MF) ? "+" : "");
 1000                 }
 1001         }
 1002         if (oif || m->m_pkthdr.rcvif)
 1003                 log(LOG_SECURITY | LOG_INFO,
 1004                     "ipfw: %d %s %s %s via %s%s\n",
 1005                     f ? f->rulenum : -1,
 1006                     action, proto, oif ? "out" : "in",
 1007                     oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
 1008                     fragment);
 1009         else
 1010                 log(LOG_SECURITY | LOG_INFO,
 1011                     "ipfw: %d %s %s [no if info]%s\n",
 1012                     f ? f->rulenum : -1,
 1013                     action, proto, fragment);
 1014         if (limit_reached)
 1015                 log(LOG_SECURITY | LOG_NOTICE,
 1016                     "ipfw: limit %d reached on entry %d\n",
 1017                     limit_reached, f ? f->rulenum : -1);
 1018 }
 1019 
 1020 /*
 1021  * IMPORTANT: the hash function for dynamic rules must be commutative
 1022  * in source and destination (ip,port), because rules are bidirectional
 1023  * and we want to find both in the same bucket.
 1024  */
 1025 static __inline int
 1026 hash_packet(struct ipfw_flow_id *id)
 1027 {
 1028         u_int32_t i;
 1029 
 1030 #ifdef INET6
 1031         if (IS_IP6_FLOW_ID(id)) 
 1032                 i = hash_packet6(id);
 1033         else
 1034 #endif /* INET6 */
 1035         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
 1036         i &= (curr_dyn_buckets - 1);
 1037         return i;
 1038 }
 1039 
 1040 /**
 1041  * unlink a dynamic rule from a chain. prev is a pointer to
 1042  * the previous one, q is a pointer to the rule to delete,
 1043  * head is a pointer to the head of the queue.
 1044  * Modifies q and potentially also head.
 1045  */
 1046 #define UNLINK_DYN_RULE(prev, head, q) {                                \
 1047         ipfw_dyn_rule *old_q = q;                                       \
 1048                                                                         \
 1049         /* remove a refcount to the parent */                           \
 1050         if (q->dyn_type == O_LIMIT)                                     \
 1051                 q->parent->count--;                                     \
 1052         DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
 1053                 (q->id.src_ip), (q->id.src_port),                       \
 1054                 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )      \
 1055         if (prev != NULL)                                               \
 1056                 prev->next = q = q->next;                               \
 1057         else                                                            \
 1058                 head = q = q->next;                                     \
 1059         dyn_count--;                                                    \
 1060         uma_zfree(ipfw_dyn_rule_zone, old_q); }
 1061 
 1062 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
 1063 
 1064 /**
 1065  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
 1066  *
 1067  * If keep_me == NULL, rules are deleted even if not expired,
 1068  * otherwise only expired rules are removed.
 1069  *
 1070  * The value of the second parameter is also used to point to identify
 1071  * a rule we absolutely do not want to remove (e.g. because we are
 1072  * holding a reference to it -- this is the case with O_LIMIT_PARENT
 1073  * rules). The pointer is only used for comparison, so any non-null
 1074  * value will do.
 1075  */
 1076 static void
 1077 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
 1078 {
 1079         static u_int32_t last_remove = 0;
 1080 
 1081 #define FORCE (keep_me == NULL)
 1082 
 1083         ipfw_dyn_rule *prev, *q;
 1084         int i, pass = 0, max_pass = 0;
 1085 
 1086         IPFW_DYN_LOCK_ASSERT();
 1087 
 1088         if (ipfw_dyn_v == NULL || dyn_count == 0)
 1089                 return;
 1090         /* do not expire more than once per second, it is useless */
 1091         if (!FORCE && last_remove == time_second)
 1092                 return;
 1093         last_remove = time_second;
 1094 
 1095         /*
 1096          * because O_LIMIT refer to parent rules, during the first pass only
 1097          * remove child and mark any pending LIMIT_PARENT, and remove
 1098          * them in a second pass.
 1099          */
 1100 next_pass:
 1101         for (i = 0 ; i < curr_dyn_buckets ; i++) {
 1102                 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
 1103                         /*
 1104                          * Logic can become complex here, so we split tests.
 1105                          */
 1106                         if (q == keep_me)
 1107                                 goto next;
 1108                         if (rule != NULL && rule != q->rule)
 1109                                 goto next; /* not the one we are looking for */
 1110                         if (q->dyn_type == O_LIMIT_PARENT) {
 1111                                 /*
 1112                                  * handle parent in the second pass,
 1113                                  * record we need one.
 1114                                  */
 1115                                 max_pass = 1;
 1116                                 if (pass == 0)
 1117                                         goto next;
 1118                                 if (FORCE && q->count != 0 ) {
 1119                                         /* XXX should not happen! */
 1120                                         printf("ipfw: OUCH! cannot remove rule,"
 1121                                              " count %d\n", q->count);
 1122                                 }
 1123                         } else {
 1124                                 if (!FORCE &&
 1125                                     !TIME_LEQ( q->expire, time_second ))
 1126                                         goto next;
 1127                         }
 1128              if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
 1129                      UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
 1130                      continue;
 1131              }
 1132 next:
 1133                         prev=q;
 1134                         q=q->next;
 1135                 }
 1136         }
 1137         if (pass++ < max_pass)
 1138                 goto next_pass;
 1139 }
 1140 
 1141 
 1142 /**
 1143  * lookup a dynamic rule.
 1144  */
 1145 static ipfw_dyn_rule *
 1146 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
 1147         struct tcphdr *tcp)
 1148 {
 1149         /*
 1150          * stateful ipfw extensions.
 1151          * Lookup into dynamic session queue
 1152          */
 1153 #define MATCH_REVERSE   0
 1154 #define MATCH_FORWARD   1
 1155 #define MATCH_NONE      2
 1156 #define MATCH_UNKNOWN   3
 1157         int i, dir = MATCH_NONE;
 1158         ipfw_dyn_rule *prev, *q=NULL;
 1159 
 1160         IPFW_DYN_LOCK_ASSERT();
 1161 
 1162         if (ipfw_dyn_v == NULL)
 1163                 goto done;      /* not found */
 1164         i = hash_packet( pkt );
 1165         for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
 1166                 if (q->dyn_type == O_LIMIT_PARENT && q->count)
 1167                         goto next;
 1168                 if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
 1169                         UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
 1170                         continue;
 1171                 }
 1172                 if (pkt->proto == q->id.proto &&
 1173                     q->dyn_type != O_LIMIT_PARENT) {
 1174                         if (IS_IP6_FLOW_ID(pkt)) {
 1175                             if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
 1176                                 &(q->id.src_ip6)) &&
 1177                             IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
 1178                                 &(q->id.dst_ip6)) &&
 1179                             pkt->src_port == q->id.src_port &&
 1180                             pkt->dst_port == q->id.dst_port ) {
 1181                                 dir = MATCH_FORWARD;
 1182                                 break;
 1183                             }
 1184                             if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
 1185                                     &(q->id.dst_ip6)) &&
 1186                                 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
 1187                                     &(q->id.src_ip6)) &&
 1188                                 pkt->src_port == q->id.dst_port &&
 1189                                 pkt->dst_port == q->id.src_port ) {
 1190                                     dir = MATCH_REVERSE;
 1191                                     break;
 1192                             }
 1193                         } else {
 1194                             if (pkt->src_ip == q->id.src_ip &&
 1195                                 pkt->dst_ip == q->id.dst_ip &&
 1196                                 pkt->src_port == q->id.src_port &&
 1197                                 pkt->dst_port == q->id.dst_port ) {
 1198                                     dir = MATCH_FORWARD;
 1199                                     break;
 1200                             }
 1201                             if (pkt->src_ip == q->id.dst_ip &&
 1202                                 pkt->dst_ip == q->id.src_ip &&
 1203                                 pkt->src_port == q->id.dst_port &&
 1204                                 pkt->dst_port == q->id.src_port ) {
 1205                                     dir = MATCH_REVERSE;
 1206                                     break;
 1207                             }
 1208                         }
 1209                 }
 1210 next:
 1211                 prev = q;
 1212                 q = q->next;
 1213         }
 1214         if (q == NULL)
 1215                 goto done; /* q = NULL, not found */
 1216 
 1217         if ( prev != NULL) { /* found and not in front */
 1218                 prev->next = q->next;
 1219                 q->next = ipfw_dyn_v[i];
 1220                 ipfw_dyn_v[i] = q;
 1221         }
 1222         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
 1223                 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
 1224 
 1225 #define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
 1226 #define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
 1227                 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
 1228                 switch (q->state) {
 1229                 case TH_SYN:                            /* opening */
 1230                         q->expire = time_second + dyn_syn_lifetime;
 1231                         break;
 1232 
 1233                 case BOTH_SYN:                  /* move to established */
 1234                 case BOTH_SYN | TH_FIN :        /* one side tries to close */
 1235                 case BOTH_SYN | (TH_FIN << 8) :
 1236                         if (tcp) {
 1237 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
 1238                             u_int32_t ack = ntohl(tcp->th_ack);
 1239                             if (dir == MATCH_FORWARD) {
 1240                                 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
 1241                                     q->ack_fwd = ack;
 1242                                 else { /* ignore out-of-sequence */
 1243                                     break;
 1244                                 }
 1245                             } else {
 1246                                 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
 1247                                     q->ack_rev = ack;
 1248                                 else { /* ignore out-of-sequence */
 1249                                     break;
 1250                                 }
 1251                             }
 1252                         }
 1253                         q->expire = time_second + dyn_ack_lifetime;
 1254                         break;
 1255 
 1256                 case BOTH_SYN | BOTH_FIN:       /* both sides closed */
 1257                         if (dyn_fin_lifetime >= dyn_keepalive_period)
 1258                                 dyn_fin_lifetime = dyn_keepalive_period - 1;
 1259                         q->expire = time_second + dyn_fin_lifetime;
 1260                         break;
 1261 
 1262                 default:
 1263 #if 0
 1264                         /*
 1265                          * reset or some invalid combination, but can also
 1266                          * occur if we use keep-state the wrong way.
 1267                          */
 1268                         if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
 1269                                 printf("invalid state: 0x%x\n", q->state);
 1270 #endif
 1271                         if (dyn_rst_lifetime >= dyn_keepalive_period)
 1272                                 dyn_rst_lifetime = dyn_keepalive_period - 1;
 1273                         q->expire = time_second + dyn_rst_lifetime;
 1274                         break;
 1275                 }
 1276         } else if (pkt->proto == IPPROTO_UDP) {
 1277                 q->expire = time_second + dyn_udp_lifetime;
 1278         } else {
 1279                 /* other protocols */
 1280                 q->expire = time_second + dyn_short_lifetime;
 1281         }
 1282 done:
 1283         if (match_direction)
 1284                 *match_direction = dir;
 1285         return q;
 1286 }
 1287 
 1288 static ipfw_dyn_rule *
 1289 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
 1290         struct tcphdr *tcp)
 1291 {
 1292         ipfw_dyn_rule *q;
 1293 
 1294         IPFW_DYN_LOCK();
 1295         q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
 1296         if (q == NULL)
 1297                 IPFW_DYN_UNLOCK();
 1298         /* NB: return table locked when q is not NULL */
 1299         return q;
 1300 }
 1301 
 1302 static void
 1303 realloc_dynamic_table(void)
 1304 {
 1305         IPFW_DYN_LOCK_ASSERT();
 1306 
 1307         /*
 1308          * Try reallocation, make sure we have a power of 2 and do
 1309          * not allow more than 64k entries. In case of overflow,
 1310          * default to 1024.
 1311          */
 1312 
 1313         if (dyn_buckets > 65536)
 1314                 dyn_buckets = 1024;
 1315         if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
 1316                 dyn_buckets = curr_dyn_buckets; /* reset */
 1317                 return;
 1318         }
 1319         curr_dyn_buckets = dyn_buckets;
 1320         if (ipfw_dyn_v != NULL)
 1321                 free(ipfw_dyn_v, M_IPFW);
 1322         for (;;) {
 1323                 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
 1324                        M_IPFW, M_NOWAIT | M_ZERO);
 1325                 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
 1326                         break;
 1327                 curr_dyn_buckets /= 2;
 1328         }
 1329 }
 1330 
 1331 /**
 1332  * Install state of type 'type' for a dynamic session.
 1333  * The hash table contains two type of rules:
 1334  * - regular rules (O_KEEP_STATE)
 1335  * - rules for sessions with limited number of sess per user
 1336  *   (O_LIMIT). When they are created, the parent is
 1337  *   increased by 1, and decreased on delete. In this case,
 1338  *   the third parameter is the parent rule and not the chain.
 1339  * - "parent" rules for the above (O_LIMIT_PARENT).
 1340  */
 1341 static ipfw_dyn_rule *
 1342 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
 1343 {
 1344         ipfw_dyn_rule *r;
 1345         int i;
 1346 
 1347         IPFW_DYN_LOCK_ASSERT();
 1348 
 1349         if (ipfw_dyn_v == NULL ||
 1350             (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
 1351                 realloc_dynamic_table();
 1352                 if (ipfw_dyn_v == NULL)
 1353                         return NULL; /* failed ! */
 1354         }
 1355         i = hash_packet(id);
 1356 
 1357         r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
 1358         if (r == NULL) {
 1359                 printf ("ipfw: sorry cannot allocate state\n");
 1360                 return NULL;
 1361         }
 1362 
 1363         /* increase refcount on parent, and set pointer */
 1364         if (dyn_type == O_LIMIT) {
 1365                 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
 1366                 if ( parent->dyn_type != O_LIMIT_PARENT)
 1367                         panic("invalid parent");
 1368                 parent->count++;
 1369                 r->parent = parent;
 1370                 rule = parent->rule;
 1371         }
 1372 
 1373         r->id = *id;
 1374         r->expire = time_second + dyn_syn_lifetime;
 1375         r->rule = rule;
 1376         r->dyn_type = dyn_type;
 1377         r->pcnt = r->bcnt = 0;
 1378         r->count = 0;
 1379 
 1380         r->bucket = i;
 1381         r->next = ipfw_dyn_v[i];
 1382         ipfw_dyn_v[i] = r;
 1383         dyn_count++;
 1384         DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
 1385            dyn_type,
 1386            (r->id.src_ip), (r->id.src_port),
 1387            (r->id.dst_ip), (r->id.dst_port),
 1388            dyn_count ); )
 1389         return r;
 1390 }
 1391 
 1392 /**
 1393  * lookup dynamic parent rule using pkt and rule as search keys.
 1394  * If the lookup fails, then install one.
 1395  */
 1396 static ipfw_dyn_rule *
 1397 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
 1398 {
 1399         ipfw_dyn_rule *q;
 1400         int i;
 1401 
 1402         IPFW_DYN_LOCK_ASSERT();
 1403 
 1404         if (ipfw_dyn_v) {
 1405                 int is_v6 = IS_IP6_FLOW_ID(pkt);
 1406                 i = hash_packet( pkt );
 1407                 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
 1408                         if (q->dyn_type == O_LIMIT_PARENT &&
 1409                             rule== q->rule &&
 1410                             pkt->proto == q->id.proto &&
 1411                             pkt->src_port == q->id.src_port &&
 1412                             pkt->dst_port == q->id.dst_port &&
 1413                             (
 1414                                 (is_v6 &&
 1415                                  IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
 1416                                         &(q->id.src_ip6)) &&
 1417                                  IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
 1418                                         &(q->id.dst_ip6))) ||
 1419                                 (!is_v6 &&
 1420                                  pkt->src_ip == q->id.src_ip &&
 1421                                  pkt->dst_ip == q->id.dst_ip)
 1422                             )
 1423                         ) {
 1424                                 q->expire = time_second + dyn_short_lifetime;
 1425                                 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
 1426                                 return q;
 1427                         }
 1428         }
 1429         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
 1430 }
 1431 
 1432 /**
 1433  * Install dynamic state for rule type cmd->o.opcode
 1434  *
 1435  * Returns 1 (failure) if state is not installed because of errors or because
 1436  * session limitations are enforced.
 1437  */
 1438 static int
 1439 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
 1440         struct ip_fw_args *args)
 1441 {
 1442         static int last_log;
 1443 
 1444         ipfw_dyn_rule *q;
 1445 
 1446         DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
 1447             cmd->o.opcode,
 1448             (args->f_id.src_ip), (args->f_id.src_port),
 1449             (args->f_id.dst_ip), (args->f_id.dst_port) );)
 1450 
 1451         IPFW_DYN_LOCK();
 1452 
 1453         q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
 1454 
 1455         if (q != NULL) { /* should never occur */
 1456                 if (last_log != time_second) {
 1457                         last_log = time_second;
 1458                         printf("ipfw: install_state: entry already present, done\n");
 1459                 }
 1460                 IPFW_DYN_UNLOCK();
 1461                 return 0;
 1462         }
 1463 
 1464         if (dyn_count >= dyn_max)
 1465                 /*
 1466                  * Run out of slots, try to remove any expired rule.
 1467                  */
 1468                 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
 1469 
 1470         if (dyn_count >= dyn_max) {
 1471                 if (last_log != time_second) {
 1472                         last_log = time_second;
 1473                         printf("ipfw: install_state: Too many dynamic rules\n");
 1474                 }
 1475                 IPFW_DYN_UNLOCK();
 1476                 return 1; /* cannot install, notify caller */
 1477         }
 1478 
 1479         switch (cmd->o.opcode) {
 1480         case O_KEEP_STATE: /* bidir rule */
 1481                 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
 1482                 break;
 1483 
 1484         case O_LIMIT: /* limit number of sessions */
 1485             {
 1486                 u_int16_t limit_mask = cmd->limit_mask;
 1487                 struct ipfw_flow_id id;
 1488                 ipfw_dyn_rule *parent;
 1489 
 1490                 DEB(printf("ipfw: installing dyn-limit rule %d\n",
 1491                     cmd->conn_limit);)
 1492 
 1493                 id.dst_ip = id.src_ip = 0;
 1494                 id.dst_port = id.src_port = 0;
 1495                 id.proto = args->f_id.proto;
 1496 
 1497                 if (IS_IP6_FLOW_ID (&(args->f_id))) {
 1498                         if (limit_mask & DYN_SRC_ADDR)
 1499                                 id.src_ip6 = args->f_id.src_ip6;
 1500                         if (limit_mask & DYN_DST_ADDR)
 1501                                 id.dst_ip6 = args->f_id.dst_ip6;
 1502                 } else {
 1503                         if (limit_mask & DYN_SRC_ADDR)
 1504                                 id.src_ip = args->f_id.src_ip;
 1505                         if (limit_mask & DYN_DST_ADDR)
 1506                                 id.dst_ip = args->f_id.dst_ip;
 1507                 }
 1508                 if (limit_mask & DYN_SRC_PORT)
 1509                         id.src_port = args->f_id.src_port;
 1510                 if (limit_mask & DYN_DST_PORT)
 1511                         id.dst_port = args->f_id.dst_port;
 1512                 parent = lookup_dyn_parent(&id, rule);
 1513                 if (parent == NULL) {
 1514                         printf("ipfw: add parent failed\n");
 1515                         IPFW_DYN_UNLOCK();
 1516                         return 1;
 1517                 }
 1518                 if (parent->count >= cmd->conn_limit) {
 1519                         /*
 1520                          * See if we can remove some expired rule.
 1521                          */
 1522                         remove_dyn_rule(rule, parent);
 1523                         if (parent->count >= cmd->conn_limit) {
 1524                                 if (fw_verbose && last_log != time_second) {
 1525                                         last_log = time_second;
 1526                                         log(LOG_SECURITY | LOG_DEBUG,
 1527                                             "drop session, too many entries\n");
 1528                                 }
 1529                                 IPFW_DYN_UNLOCK();
 1530                                 return 1;
 1531                         }
 1532                 }
 1533                 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
 1534             }
 1535                 break;
 1536         default:
 1537                 printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
 1538                 IPFW_DYN_UNLOCK();
 1539                 return 1;
 1540         }
 1541         lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
 1542         IPFW_DYN_UNLOCK();
 1543         return 0;
 1544 }
 1545 
 1546 /*
 1547  * Generate a TCP packet, containing either a RST or a keepalive.
 1548  * When flags & TH_RST, we are sending a RST packet, because of a
 1549  * "reset" action matched the packet.
 1550  * Otherwise we are sending a keepalive, and flags & TH_
 1551  */
 1552 static struct mbuf *
 1553 send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
 1554 {
 1555         struct mbuf *m;
 1556         struct ip *ip;
 1557         struct tcphdr *tcp;
 1558 
 1559         MGETHDR(m, M_DONTWAIT, MT_HEADER);
 1560         if (m == 0)
 1561                 return (NULL);
 1562         m->m_pkthdr.rcvif = (struct ifnet *)0;
 1563         m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
 1564         m->m_data += max_linkhdr;
 1565 
 1566         ip = mtod(m, struct ip *);
 1567         bzero(ip, m->m_len);
 1568         tcp = (struct tcphdr *)(ip + 1); /* no IP options */
 1569         ip->ip_p = IPPROTO_TCP;
 1570         tcp->th_off = 5;
 1571         /*
 1572          * Assume we are sending a RST (or a keepalive in the reverse
 1573          * direction), swap src and destination addresses and ports.
 1574          */
 1575         ip->ip_src.s_addr = htonl(id->dst_ip);
 1576         ip->ip_dst.s_addr = htonl(id->src_ip);
 1577         tcp->th_sport = htons(id->dst_port);
 1578         tcp->th_dport = htons(id->src_port);
 1579         if (flags & TH_RST) {   /* we are sending a RST */
 1580                 if (flags & TH_ACK) {
 1581                         tcp->th_seq = htonl(ack);
 1582                         tcp->th_ack = htonl(0);
 1583                         tcp->th_flags = TH_RST;
 1584                 } else {
 1585                         if (flags & TH_SYN)
 1586                                 seq++;
 1587                         tcp->th_seq = htonl(0);
 1588                         tcp->th_ack = htonl(seq);
 1589                         tcp->th_flags = TH_RST | TH_ACK;
 1590                 }
 1591         } else {
 1592                 /*
 1593                  * We are sending a keepalive. flags & TH_SYN determines
 1594                  * the direction, forward if set, reverse if clear.
 1595                  * NOTE: seq and ack are always assumed to be correct
 1596                  * as set by the caller. This may be confusing...
 1597                  */
 1598                 if (flags & TH_SYN) {
 1599                         /*
 1600                          * we have to rewrite the correct addresses!
 1601                          */
 1602                         ip->ip_dst.s_addr = htonl(id->dst_ip);
 1603                         ip->ip_src.s_addr = htonl(id->src_ip);
 1604                         tcp->th_dport = htons(id->dst_port);
 1605                         tcp->th_sport = htons(id->src_port);
 1606                 }
 1607                 tcp->th_seq = htonl(seq);
 1608                 tcp->th_ack = htonl(ack);
 1609                 tcp->th_flags = TH_ACK;
 1610         }
 1611         /*
 1612          * set ip_len to the payload size so we can compute
 1613          * the tcp checksum on the pseudoheader
 1614          * XXX check this, could save a couple of words ?
 1615          */
 1616         ip->ip_len = htons(sizeof(struct tcphdr));
 1617         tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
 1618         /*
 1619          * now fill fields left out earlier
 1620          */
 1621         ip->ip_ttl = ip_defttl;
 1622         ip->ip_len = m->m_pkthdr.len;
 1623         m->m_flags |= M_SKIP_FIREWALL;
 1624         return (m);
 1625 }
 1626 
 1627 /*
 1628  * sends a reject message, consuming the mbuf passed as an argument.
 1629  */
 1630 static void
 1631 send_reject(struct ip_fw_args *args, int code, u_short offset, int ip_len)
 1632 {
 1633 
 1634         if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
 1635                 /* We need the IP header in host order for icmp_error(). */
 1636                 if (args->eh != NULL) {
 1637                         struct ip *ip = mtod(args->m, struct ip *);
 1638                         ip->ip_len = ntohs(ip->ip_len);
 1639                         ip->ip_off = ntohs(ip->ip_off);
 1640                 }
 1641                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
 1642         } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
 1643                 struct tcphdr *const tcp =
 1644                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
 1645                 if ( (tcp->th_flags & TH_RST) == 0) {
 1646                         struct mbuf *m;
 1647                         m = send_pkt(&(args->f_id), ntohl(tcp->th_seq),
 1648                                 ntohl(tcp->th_ack),
 1649                                 tcp->th_flags | TH_RST);
 1650                         if (m != NULL)
 1651                                 ip_output(m, NULL, NULL, 0, NULL, NULL);
 1652                 }
 1653                 m_freem(args->m);
 1654         } else
 1655                 m_freem(args->m);
 1656         args->m = NULL;
 1657 }
 1658 
 1659 /**
 1660  *
 1661  * Given an ip_fw *, lookup_next_rule will return a pointer
 1662  * to the next rule, which can be either the jump
 1663  * target (for skipto instructions) or the next one in the list (in
 1664  * all other cases including a missing jump target).
 1665  * The result is also written in the "next_rule" field of the rule.
 1666  * Backward jumps are not allowed, so start looking from the next
 1667  * rule...
 1668  *
 1669  * This never returns NULL -- in case we do not have an exact match,
 1670  * the next rule is returned. When the ruleset is changed,
 1671  * pointers are flushed so we are always correct.
 1672  */
 1673 
 1674 static struct ip_fw *
 1675 lookup_next_rule(struct ip_fw *me)
 1676 {
 1677         struct ip_fw *rule = NULL;
 1678         ipfw_insn *cmd;
 1679 
 1680         /* look for action, in case it is a skipto */
 1681         cmd = ACTION_PTR(me);
 1682         if (cmd->opcode == O_LOG)
 1683                 cmd += F_LEN(cmd);
 1684         if (cmd->opcode == O_ALTQ)
 1685                 cmd += F_LEN(cmd);
 1686         if ( cmd->opcode == O_SKIPTO )
 1687                 for (rule = me->next; rule ; rule = rule->next)
 1688                         if (rule->rulenum >= cmd->arg1)
 1689                                 break;
 1690         if (rule == NULL)                       /* failure or not a skipto */
 1691                 rule = me->next;
 1692         me->next_rule = rule;
 1693         return rule;
 1694 }
 1695 
 1696 static void
 1697 init_tables(void)
 1698 {
 1699         int i;
 1700 
 1701         for (i = 0; i < IPFW_TABLES_MAX; i++) {
 1702                 rn_inithead((void **)&ipfw_tables[i].rnh, 32);
 1703                 ipfw_tables[i].modified = 1;
 1704         }
 1705 }
 1706 
 1707 static int
 1708 add_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen, u_int32_t value)
 1709 {
 1710         struct radix_node_head *rnh;
 1711         struct table_entry *ent;
 1712 
 1713         if (tbl >= IPFW_TABLES_MAX)
 1714                 return (EINVAL);
 1715         rnh = ipfw_tables[tbl].rnh;
 1716         ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
 1717         if (ent == NULL)
 1718                 return (ENOMEM);
 1719         ent->value = value;
 1720         ent->addr.sin_len = ent->mask.sin_len = 8;
 1721         ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
 1722         ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
 1723         RADIX_NODE_HEAD_LOCK(rnh);
 1724         if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
 1725             NULL) {
 1726                 RADIX_NODE_HEAD_UNLOCK(rnh);
 1727                 free(ent, M_IPFW_TBL);
 1728                 return (EEXIST);
 1729         }
 1730         ipfw_tables[tbl].modified = 1;
 1731         RADIX_NODE_HEAD_UNLOCK(rnh);
 1732         return (0);
 1733 }
 1734 
 1735 static int
 1736 del_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen)
 1737 {
 1738         struct radix_node_head *rnh;
 1739         struct table_entry *ent;
 1740         struct sockaddr_in sa, mask;
 1741 
 1742         if (tbl >= IPFW_TABLES_MAX)
 1743                 return (EINVAL);
 1744         rnh = ipfw_tables[tbl].rnh;
 1745         sa.sin_len = mask.sin_len = 8;
 1746         mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
 1747         sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
 1748         RADIX_NODE_HEAD_LOCK(rnh);
 1749         ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
 1750         if (ent == NULL) {
 1751                 RADIX_NODE_HEAD_UNLOCK(rnh);
 1752                 return (ESRCH);
 1753         }
 1754         ipfw_tables[tbl].modified = 1;
 1755         RADIX_NODE_HEAD_UNLOCK(rnh);
 1756         free(ent, M_IPFW_TBL);
 1757         return (0);
 1758 }
 1759 
 1760 static int
 1761 flush_table_entry(struct radix_node *rn, void *arg)
 1762 {
 1763         struct radix_node_head * const rnh = arg;
 1764         struct table_entry *ent;
 1765 
 1766         ent = (struct table_entry *)
 1767             rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
 1768         if (ent != NULL)
 1769                 free(ent, M_IPFW_TBL);
 1770         return (0);
 1771 }
 1772 
 1773 static int
 1774 flush_table(u_int16_t tbl)
 1775 {
 1776         struct radix_node_head *rnh;
 1777 
 1778         if (tbl >= IPFW_TABLES_MAX)
 1779                 return (EINVAL);
 1780         rnh = ipfw_tables[tbl].rnh;
 1781         RADIX_NODE_HEAD_LOCK(rnh);
 1782         rnh->rnh_walktree(rnh, flush_table_entry, rnh);
 1783         ipfw_tables[tbl].modified = 1;
 1784         RADIX_NODE_HEAD_UNLOCK(rnh);
 1785         return (0);
 1786 }
 1787 
 1788 static void
 1789 flush_tables(void)
 1790 {
 1791         u_int16_t tbl;
 1792 
 1793         for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
 1794                 flush_table(tbl);
 1795 }
 1796 
 1797 static int
 1798 lookup_table(u_int16_t tbl, in_addr_t addr, u_int32_t *val)
 1799 {
 1800         struct radix_node_head *rnh;
 1801         struct ip_fw_table *table;
 1802         struct table_entry *ent;
 1803         struct sockaddr_in sa;
 1804         int last_match;
 1805 
 1806         if (tbl >= IPFW_TABLES_MAX)
 1807                 return (0);
 1808         table = &ipfw_tables[tbl];
 1809         rnh = table->rnh;
 1810         RADIX_NODE_HEAD_LOCK(rnh);
 1811         if (addr == table->last_addr && !table->modified) {
 1812                 last_match = table->last_match;
 1813                 if (last_match)
 1814                         *val = table->last_value;
 1815                 RADIX_NODE_HEAD_UNLOCK(rnh);
 1816                 return (last_match);
 1817         }
 1818         table->modified = 0;
 1819         sa.sin_len = 8;
 1820         sa.sin_addr.s_addr = addr;
 1821         ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
 1822         table->last_addr = addr;
 1823         if (ent != NULL) {
 1824                 table->last_value = *val = ent->value;
 1825                 table->last_match = 1;
 1826                 RADIX_NODE_HEAD_UNLOCK(rnh);
 1827                 return (1);
 1828         }
 1829         table->last_match = 0;
 1830         RADIX_NODE_HEAD_UNLOCK(rnh);
 1831         return (0);
 1832 }
 1833 
 1834 static int
 1835 count_table_entry(struct radix_node *rn, void *arg)
 1836 {
 1837         u_int32_t * const cnt = arg;
 1838 
 1839         (*cnt)++;
 1840         return (0);
 1841 }
 1842 
 1843 static int
 1844 count_table(u_int32_t tbl, u_int32_t *cnt)
 1845 {
 1846         struct radix_node_head *rnh;
 1847 
 1848         if (tbl >= IPFW_TABLES_MAX)
 1849                 return (EINVAL);
 1850         rnh = ipfw_tables[tbl].rnh;
 1851         *cnt = 0;
 1852         RADIX_NODE_HEAD_LOCK(rnh);
 1853         rnh->rnh_walktree(rnh, count_table_entry, cnt);
 1854         RADIX_NODE_HEAD_UNLOCK(rnh);
 1855         return (0);
 1856 }
 1857 
 1858 static int
 1859 dump_table_entry(struct radix_node *rn, void *arg)
 1860 {
 1861         struct table_entry * const n = (struct table_entry *)rn;
 1862         ipfw_table * const tbl = arg;
 1863         ipfw_table_entry *ent;
 1864 
 1865         if (tbl->cnt == tbl->size)
 1866                 return (1);
 1867         ent = &tbl->ent[tbl->cnt];
 1868         ent->tbl = tbl->tbl;
 1869         if (in_nullhost(n->mask.sin_addr))
 1870                 ent->masklen = 0;
 1871         else
 1872                 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
 1873         ent->addr = n->addr.sin_addr.s_addr;
 1874         ent->value = n->value;
 1875         tbl->cnt++;
 1876         return (0);
 1877 }
 1878 
 1879 static int
 1880 dump_table(ipfw_table *tbl)
 1881 {
 1882         struct radix_node_head *rnh;
 1883 
 1884         if (tbl->tbl >= IPFW_TABLES_MAX)
 1885                 return (EINVAL);
 1886         rnh = ipfw_tables[tbl->tbl].rnh;
 1887         tbl->cnt = 0;
 1888         RADIX_NODE_HEAD_LOCK(rnh);
 1889         rnh->rnh_walktree(rnh, dump_table_entry, tbl);
 1890         RADIX_NODE_HEAD_UNLOCK(rnh);
 1891         return (0);
 1892 }
 1893 
 1894 static void
 1895 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
 1896 {
 1897         struct ucred *cr;
 1898 
 1899         if (inp->inp_socket != NULL) {
 1900                 cr = inp->inp_socket->so_cred;
 1901                 ugp->fw_prid = jailed(cr) ?
 1902                     cr->cr_prison->pr_id : -1;
 1903                 ugp->fw_uid = cr->cr_uid;
 1904                 ugp->fw_ngroups = cr->cr_ngroups;
 1905                 bcopy(cr->cr_groups, ugp->fw_groups,
 1906                     sizeof(ugp->fw_groups));
 1907         }
 1908 }
 1909 
 1910 static int
 1911 check_uidgid(ipfw_insn_u32 *insn,
 1912         int proto, struct ifnet *oif,
 1913         struct in_addr dst_ip, u_int16_t dst_port,
 1914         struct in_addr src_ip, u_int16_t src_port,
 1915         struct ip_fw_ugid *ugp, int *lookup, struct inpcb *inp)
 1916 {
 1917         struct inpcbinfo *pi;
 1918         int wildcard;
 1919         struct inpcb *pcb;
 1920         int match;
 1921         gid_t *gp;
 1922 
 1923         /*
 1924          * Check to see if the UDP or TCP stack supplied us with
 1925          * the PCB. If so, rather then holding a lock and looking
 1926          * up the PCB, we can use the one that was supplied.
 1927          */
 1928         if (inp && *lookup == 0) {
 1929                 INP_LOCK_ASSERT(inp);
 1930                 if (inp->inp_socket != NULL) {
 1931                         fill_ugid_cache(inp, ugp);
 1932                         *lookup = 1;
 1933                 }
 1934         }
 1935         /*
 1936          * If we have already been here and the packet has no
 1937          * PCB entry associated with it, then we can safely
 1938          * assume that this is a no match.
 1939          */
 1940         if (*lookup == -1)
 1941                 return (0);
 1942         if (proto == IPPROTO_TCP) {
 1943                 wildcard = 0;
 1944                 pi = &tcbinfo;
 1945         } else if (proto == IPPROTO_UDP) {
 1946                 wildcard = 1;
 1947                 pi = &udbinfo;
 1948         } else
 1949                 return 0;
 1950         match = 0;
 1951         if (*lookup == 0) {
 1952                 INP_INFO_RLOCK(pi);
 1953                 pcb =  (oif) ?
 1954                         in_pcblookup_hash(pi,
 1955                                 dst_ip, htons(dst_port),
 1956                                 src_ip, htons(src_port),
 1957                                 wildcard, oif) :
 1958                         in_pcblookup_hash(pi,
 1959                                 src_ip, htons(src_port),
 1960                                 dst_ip, htons(dst_port),
 1961                                 wildcard, NULL);
 1962                 if (pcb != NULL) {
 1963                         INP_LOCK(pcb);
 1964                         if (pcb->inp_socket != NULL) {
 1965                                 fill_ugid_cache(pcb, ugp);
 1966                                 *lookup = 1;
 1967                         }
 1968                         INP_UNLOCK(pcb);
 1969                 }
 1970                 INP_INFO_RUNLOCK(pi);
 1971                 if (*lookup == 0) {
 1972                         /*
 1973                          * If the lookup did not yield any results, there
 1974                          * is no sense in coming back and trying again. So
 1975                          * we can set lookup to -1 and ensure that we wont
 1976                          * bother the pcb system again.
 1977                          */
 1978                         *lookup = -1;
 1979                         return (0);
 1980                 }
 1981         } 
 1982         if (insn->o.opcode == O_UID)
 1983                 match = (ugp->fw_uid == (uid_t)insn->d[0]);
 1984         else if (insn->o.opcode == O_GID) {
 1985                 for (gp = ugp->fw_groups;
 1986                         gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
 1987                         if (*gp == (gid_t)insn->d[0]) {
 1988                                 match = 1;
 1989                                 break;
 1990                         }
 1991         } else if (insn->o.opcode == O_JAIL)
 1992                 match = (ugp->fw_prid == (int)insn->d[0]);
 1993         return match;
 1994 }
 1995 
 1996 /*
 1997  * The main check routine for the firewall.
 1998  *
 1999  * All arguments are in args so we can modify them and return them
 2000  * back to the caller.
 2001  *
 2002  * Parameters:
 2003  *
 2004  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
 2005  *              Starts with the IP header.
 2006  *      args->eh (in)   Mac header if present, or NULL for layer3 packet.
 2007  *      args->oif       Outgoing interface, or NULL if packet is incoming.
 2008  *              The incoming interface is in the mbuf. (in)
 2009  *      args->divert_rule (in/out)
 2010  *              Skip up to the first rule past this rule number;
 2011  *              upon return, non-zero port number for divert or tee.
 2012  *
 2013  *      args->rule      Pointer to the last matching rule (in/out)
 2014  *      args->next_hop  Socket we are forwarding to (out).
 2015  *      args->f_id      Addresses grabbed from the packet (out)
 2016  *      args->cookie    a cookie depending on rule action
 2017  *
 2018  * Return value:
 2019  *
 2020  *      IP_FW_PASS      the packet must be accepted
 2021  *      IP_FW_DENY      the packet must be dropped
 2022  *      IP_FW_DIVERT    divert packet, port in m_tag
 2023  *      IP_FW_TEE       tee packet, port in m_tag
 2024  *      IP_FW_DUMMYNET  to dummynet, pipe in args->cookie
 2025  *      IP_FW_NETGRAPH  into netgraph, cookie args->cookie
 2026  *
 2027  */
 2028 
 2029 int
 2030 ipfw_chk(struct ip_fw_args *args)
 2031 {
 2032         /*
 2033          * Local variables hold state during the processing of a packet.
 2034          *
 2035          * IMPORTANT NOTE: to speed up the processing of rules, there
 2036          * are some assumption on the values of the variables, which
 2037          * are documented here. Should you change them, please check
 2038          * the implementation of the various instructions to make sure
 2039          * that they still work.
 2040          *
 2041          * args->eh     The MAC header. It is non-null for a layer2
 2042          *      packet, it is NULL for a layer-3 packet.
 2043          *
 2044          * m | args->m  Pointer to the mbuf, as received from the caller.
 2045          *      It may change if ipfw_chk() does an m_pullup, or if it
 2046          *      consumes the packet because it calls send_reject().
 2047          *      XXX This has to change, so that ipfw_chk() never modifies
 2048          *      or consumes the buffer.
 2049          * ip   is simply an alias of the value of m, and it is kept
 2050          *      in sync with it (the packet is  supposed to start with
 2051          *      the ip header).
 2052          */
 2053         struct mbuf *m = args->m;
 2054         struct ip *ip = mtod(m, struct ip *);
 2055 
 2056         /*
 2057          * For rules which contain uid/gid or jail constraints, cache
 2058          * a copy of the users credentials after the pcb lookup has been
 2059          * executed. This will speed up the processing of rules with
 2060          * these types of constraints, as well as decrease contention
 2061          * on pcb related locks.
 2062          */
 2063         struct ip_fw_ugid fw_ugid_cache;
 2064         int ugid_lookup = 0;
 2065 
 2066         /*
 2067          * divinput_flags       If non-zero, set to the IP_FW_DIVERT_*_FLAG
 2068          *      associated with a packet input on a divert socket.  This
 2069          *      will allow to distinguish traffic and its direction when
 2070          *      it originates from a divert socket.
 2071          */
 2072         u_int divinput_flags = 0;
 2073 
 2074         /*
 2075          * oif | args->oif      If NULL, ipfw_chk has been called on the
 2076          *      inbound path (ether_input, bdg_forward, ip_input).
 2077          *      If non-NULL, ipfw_chk has been called on the outbound path
 2078          *      (ether_output, ip_output).
 2079          */
 2080         struct ifnet *oif = args->oif;
 2081 
 2082         struct ip_fw *f = NULL;         /* matching rule */
 2083         int retval = 0;
 2084 
 2085         /*
 2086          * hlen The length of the IP header.
 2087          */
 2088         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
 2089 
 2090         /*
 2091          * offset       The offset of a fragment. offset != 0 means that
 2092          *      we have a fragment at this offset of an IPv4 packet.
 2093          *      offset == 0 means that (if this is an IPv4 packet)
 2094          *      this is the first or only fragment.
 2095          *      For IPv6 offset == 0 means there is no Fragment Header. 
 2096          *      If offset != 0 for IPv6 always use correct mask to
 2097          *      get the correct offset because we add IP6F_MORE_FRAG
 2098          *      to be able to dectect the first fragment which would
 2099          *      otherwise have offset = 0.
 2100          */
 2101         u_short offset = 0;
 2102 
 2103         /*
 2104          * Local copies of addresses. They are only valid if we have
 2105          * an IP packet.
 2106          *
 2107          * proto        The protocol. Set to 0 for non-ip packets,
 2108          *      or to the protocol read from the packet otherwise.
 2109          *      proto != 0 means that we have an IPv4 packet.
 2110          *
 2111          * src_port, dst_port   port numbers, in HOST format. Only
 2112          *      valid for TCP and UDP packets.
 2113          *
 2114          * src_ip, dst_ip       ip addresses, in NETWORK format.
 2115          *      Only valid for IPv4 packets.
 2116          */
 2117         u_int8_t proto;
 2118         u_int16_t src_port = 0, dst_port = 0;   /* NOTE: host format    */
 2119         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
 2120         u_int16_t ip_len=0;
 2121         int pktlen;
 2122 
 2123         /*
 2124          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
 2125          *      MATCH_NONE when checked and not matched (q = NULL),
 2126          *      MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
 2127          */
 2128         int dyn_dir = MATCH_UNKNOWN;
 2129         ipfw_dyn_rule *q = NULL;
 2130         struct ip_fw_chain *chain = &layer3_chain;
 2131         struct m_tag *mtag;
 2132 
 2133         /*
 2134          * We store in ulp a pointer to the upper layer protocol header.
 2135          * In the ipv4 case this is easy to determine from the header,
 2136          * but for ipv6 we might have some additional headers in the middle.
 2137          * ulp is NULL if not found.
 2138          */
 2139         void *ulp = NULL;               /* upper layer protocol pointer. */
 2140         /* XXX ipv6 variables */
 2141         int is_ipv6 = 0;
 2142         u_int16_t ext_hd = 0;   /* bits vector for extension header filtering */
 2143         /* end of ipv6 variables */
 2144         int is_ipv4 = 0;
 2145 
 2146         if (m->m_flags & M_SKIP_FIREWALL)
 2147                 return (IP_FW_PASS);    /* accept */
 2148 
 2149         pktlen = m->m_pkthdr.len;
 2150         proto = args->f_id.proto = 0;   /* mark f_id invalid */
 2151                 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
 2152 
 2153 /*
 2154  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
 2155  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
 2156  * pointer might become stale after other pullups (but we never use it
 2157  * this way).
 2158  */
 2159 #define PULLUP_TO(len, p, T)                                            \
 2160 do {                                                                    \
 2161         int x = (len) + sizeof(T);                                      \
 2162         if ((m)->m_len < x) {                                           \
 2163                 args->m = m = m_pullup(m, x);                           \
 2164                 if (m == NULL)                                          \
 2165                         goto pullup_failed;                             \
 2166         }                                                               \
 2167         p = (mtod(m, char *) + (len));                                  \
 2168 } while (0)
 2169 
 2170         /* Identify IP packets and fill up variables. */
 2171         if (pktlen >= sizeof(struct ip6_hdr) &&
 2172             (args->eh == NULL || ntohs(args->eh->ether_type)==ETHERTYPE_IPV6) &&
 2173             mtod(m, struct ip *)->ip_v == 6) {
 2174                 is_ipv6 = 1;
 2175                 args->f_id.addr_type = 6;
 2176                 hlen = sizeof(struct ip6_hdr);
 2177                 proto = mtod(m, struct ip6_hdr *)->ip6_nxt;
 2178 
 2179                 /* Search extension headers to find upper layer protocols */
 2180                 while (ulp == NULL) {
 2181                         switch (proto) {
 2182                         case IPPROTO_ICMPV6:
 2183                                 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
 2184                                 args->f_id.flags = ICMP6(ulp)->icmp6_type;
 2185                                 break;
 2186 
 2187                         case IPPROTO_TCP:
 2188                                 PULLUP_TO(hlen, ulp, struct tcphdr);
 2189                                 dst_port = TCP(ulp)->th_dport;
 2190                                 src_port = TCP(ulp)->th_sport;
 2191                                 args->f_id.flags = TCP(ulp)->th_flags;
 2192                                 break;
 2193 
 2194                         case IPPROTO_UDP:
 2195                                 PULLUP_TO(hlen, ulp, struct udphdr);
 2196                                 dst_port = UDP(ulp)->uh_dport;
 2197                                 src_port = UDP(ulp)->uh_sport;
 2198                                 break;
 2199 
 2200                         case IPPROTO_HOPOPTS:   /* RFC 2460 */
 2201                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
 2202                                 ext_hd |= EXT_HOPOPTS;
 2203                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
 2204                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
 2205                                 ulp = NULL;
 2206                                 break;
 2207 
 2208                         case IPPROTO_ROUTING:   /* RFC 2460 */
 2209                                 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
 2210                                 if (((struct ip6_rthdr *)ulp)->ip6r_type != 0) {
 2211                                         printf("IPFW2: IPV6 - Unknown Routing "
 2212                                             "Header type(%d)\n",
 2213                                             ((struct ip6_rthdr *)ulp)->ip6r_type);
 2214                                         if (fw_deny_unknown_exthdrs)
 2215                                             return (IP_FW_DENY);
 2216                                         break;
 2217                                 }
 2218                                 ext_hd |= EXT_ROUTING;
 2219                                 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
 2220                                 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
 2221                                 ulp = NULL;
 2222                                 break;
 2223 
 2224                         case IPPROTO_FRAGMENT:  /* RFC 2460 */
 2225                                 PULLUP_TO(hlen, ulp, struct ip6_frag);
 2226                                 ext_hd |= EXT_FRAGMENT;
 2227                                 hlen += sizeof (struct ip6_frag);
 2228                                 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
 2229                                 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
 2230                                         IP6F_OFF_MASK;
 2231                                 /* Add IP6F_MORE_FRAG for offset of first
 2232                                  * fragment to be != 0. */
 2233                                 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
 2234                                         IP6F_MORE_FRAG;
 2235                                 if (offset == 0) {
 2236                                         printf("IPFW2: IPV6 - Invalid Fragment "
 2237                                             "Header\n");
 2238                                         if (fw_deny_unknown_exthdrs)
 2239                                             return (IP_FW_DENY);
 2240                                         break;
 2241                                 }
 2242                                 args->f_id.frag_id6 =
 2243                                     ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
 2244                                 ulp = NULL;
 2245                                 break;
 2246 
 2247                         case IPPROTO_DSTOPTS:   /* RFC 2460 */
 2248                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
 2249                                 ext_hd |= EXT_DSTOPTS;
 2250                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
 2251                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
 2252                                 ulp = NULL;
 2253                                 break;
 2254 
 2255                         case IPPROTO_AH:        /* RFC 2402 */
 2256                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
 2257                                 ext_hd |= EXT_AH;
 2258                                 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
 2259                                 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
 2260                                 ulp = NULL;
 2261                                 break;
 2262 
 2263                         case IPPROTO_ESP:       /* RFC 2406 */
 2264                                 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
 2265                                 /* Anything past Seq# is variable length and
 2266                                  * data past this ext. header is encrypted. */
 2267                                 ext_hd |= EXT_ESP;
 2268                                 break;
 2269 
 2270                         case IPPROTO_NONE:      /* RFC 2460 */
 2271                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
 2272                                 /* Packet ends here. if ip6e_len!=0 octets
 2273                                  * must be ignored. */
 2274                                 break;
 2275 
 2276                         case IPPROTO_OSPFIGP:
 2277                                 /* XXX OSPF header check? */
 2278                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
 2279                                 break;
 2280 
 2281                         default:
 2282                                 printf("IPFW2: IPV6 - Unknown Extension "
 2283                                     "Header(%d), ext_hd=%x\n", proto, ext_hd);
 2284                                 if (fw_deny_unknown_exthdrs)
 2285                                     return (IP_FW_DENY);
 2286                                 break;
 2287                         } /*switch */
 2288                 }
 2289                 args->f_id.src_ip6 = mtod(m,struct ip6_hdr *)->ip6_src;
 2290                 args->f_id.dst_ip6 = mtod(m,struct ip6_hdr *)->ip6_dst;
 2291                 args->f_id.src_ip = 0;
 2292                 args->f_id.dst_ip = 0;
 2293                 args->f_id.flow_id6 = ntohl(mtod(m, struct ip6_hdr *)->ip6_flow);
 2294         } else if (pktlen >= sizeof(struct ip) &&
 2295             (args->eh == NULL || ntohs(args->eh->ether_type) == ETHERTYPE_IP) &&
 2296             mtod(m, struct ip *)->ip_v == 4) {
 2297                 is_ipv4 = 1;
 2298                 ip = mtod(m, struct ip *);
 2299                 hlen = ip->ip_hl << 2;
 2300                 args->f_id.addr_type = 4;
 2301 
 2302                 /*
 2303                  * Collect parameters into local variables for faster matching.
 2304                  */
 2305                 proto = ip->ip_p;
 2306                 src_ip = ip->ip_src;
 2307                 dst_ip = ip->ip_dst;
 2308                 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
 2309                         offset = ntohs(ip->ip_off) & IP_OFFMASK;
 2310                         ip_len = ntohs(ip->ip_len);
 2311                 } else {
 2312                         offset = ip->ip_off & IP_OFFMASK;
 2313                         ip_len = ip->ip_len;
 2314                 }
 2315                 pktlen = ip_len < pktlen ? ip_len : pktlen;
 2316 
 2317                 if (offset == 0) {
 2318                         switch (proto) {
 2319                         case IPPROTO_TCP:
 2320                                 PULLUP_TO(hlen, ulp, struct tcphdr);
 2321                                 dst_port = TCP(ulp)->th_dport;
 2322                                 src_port = TCP(ulp)->th_sport;
 2323                                 args->f_id.flags = TCP(ulp)->th_flags;
 2324                                 break;
 2325 
 2326                         case IPPROTO_UDP:
 2327                                 PULLUP_TO(hlen, ulp, struct udphdr);
 2328                                 dst_port = UDP(ulp)->uh_dport;
 2329                                 src_port = UDP(ulp)->uh_sport;
 2330                                 break;
 2331 
 2332                         case IPPROTO_ICMP:
 2333                                 PULLUP_TO(hlen, ulp, struct icmphdr);
 2334                                 args->f_id.flags = ICMP(ulp)->icmp_type;
 2335                                 break;
 2336 
 2337                         default:
 2338                                 break;
 2339                         }
 2340                 }
 2341 
 2342                 args->f_id.src_ip = ntohl(src_ip.s_addr);
 2343                 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
 2344         }
 2345 #undef PULLUP_TO
 2346         if (proto) { /* we may have port numbers, store them */
 2347                 args->f_id.proto = proto;
 2348                 args->f_id.src_port = src_port = ntohs(src_port);
 2349                 args->f_id.dst_port = dst_port = ntohs(dst_port);
 2350         }
 2351 
 2352         IPFW_RLOCK(chain);
 2353         mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
 2354         if (args->rule) {
 2355                 /*
 2356                  * Packet has already been tagged. Look for the next rule
 2357                  * to restart processing.
 2358                  *
 2359                  * If fw_one_pass != 0 then just accept it.
 2360                  * XXX should not happen here, but optimized out in
 2361                  * the caller.
 2362                  */
 2363                 if (fw_one_pass) {
 2364                         IPFW_RUNLOCK(chain);
 2365                         return (IP_FW_PASS);
 2366                 }
 2367 
 2368                 f = args->rule->next_rule;
 2369                 if (f == NULL)
 2370                         f = lookup_next_rule(args->rule);
 2371         } else {
 2372                 /*
 2373                  * Find the starting rule. It can be either the first
 2374                  * one, or the one after divert_rule if asked so.
 2375                  */
 2376                 int skipto = mtag ? divert_cookie(mtag) : 0;
 2377 
 2378                 f = chain->rules;
 2379                 if (args->eh == NULL && skipto != 0) {
 2380                         if (skipto >= IPFW_DEFAULT_RULE) {
 2381                                 IPFW_RUNLOCK(chain);
 2382                                 return (IP_FW_DENY); /* invalid */
 2383                         }
 2384                         while (f && f->rulenum <= skipto)
 2385                                 f = f->next;
 2386                         if (f == NULL) {        /* drop packet */
 2387                                 IPFW_RUNLOCK(chain);
 2388                                 return (IP_FW_DENY);
 2389                         }
 2390                 }
 2391         }
 2392         /* reset divert rule to avoid confusion later */
 2393         if (mtag) {
 2394                 divinput_flags = divert_info(mtag) &
 2395                     (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
 2396                 m_tag_delete(m, mtag);
 2397         }
 2398 
 2399         /*
 2400          * Now scan the rules, and parse microinstructions for each rule.
 2401          */
 2402         for (; f; f = f->next) {
 2403                 int l, cmdlen;
 2404                 ipfw_insn *cmd;
 2405                 int skip_or; /* skip rest of OR block */
 2406 
 2407 again:
 2408                 if (set_disable & (1 << f->set) )
 2409                         continue;
 2410 
 2411                 skip_or = 0;
 2412                 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
 2413                     l -= cmdlen, cmd += cmdlen) {
 2414                         int match;
 2415 
 2416                         /*
 2417                          * check_body is a jump target used when we find a
 2418                          * CHECK_STATE, and need to jump to the body of
 2419                          * the target rule.
 2420                          */
 2421 
 2422 check_body:
 2423                         cmdlen = F_LEN(cmd);
 2424                         /*
 2425                          * An OR block (insn_1 || .. || insn_n) has the
 2426                          * F_OR bit set in all but the last instruction.
 2427                          * The first match will set "skip_or", and cause
 2428                          * the following instructions to be skipped until
 2429                          * past the one with the F_OR bit clear.
 2430                          */
 2431                         if (skip_or) {          /* skip this instruction */
 2432                                 if ((cmd->len & F_OR) == 0)
 2433                                         skip_or = 0;    /* next one is good */
 2434                                 continue;
 2435                         }
 2436                         match = 0; /* set to 1 if we succeed */
 2437 
 2438                         switch (cmd->opcode) {
 2439                         /*
 2440                          * The first set of opcodes compares the packet's
 2441                          * fields with some pattern, setting 'match' if a
 2442                          * match is found. At the end of the loop there is
 2443                          * logic to deal with F_NOT and F_OR flags associated
 2444                          * with the opcode.
 2445                          */
 2446                         case O_NOP:
 2447                                 match = 1;
 2448                                 break;
 2449 
 2450                         case O_FORWARD_MAC:
 2451                                 printf("ipfw: opcode %d unimplemented\n",
 2452                                     cmd->opcode);
 2453                                 break;
 2454 
 2455                         case O_GID:
 2456                         case O_UID:
 2457                         case O_JAIL:
 2458                                 /*
 2459                                  * We only check offset == 0 && proto != 0,
 2460                                  * as this ensures that we have a
 2461                                  * packet with the ports info.
 2462                                  */
 2463                                 if (offset!=0)
 2464                                         break;
 2465                                 if (is_ipv6) /* XXX to be fixed later */
 2466                                         break;
 2467                                 if (proto == IPPROTO_TCP ||
 2468                                     proto == IPPROTO_UDP)
 2469                                         match = check_uidgid(
 2470                                                     (ipfw_insn_u32 *)cmd,
 2471                                                     proto, oif,
 2472                                                     dst_ip, dst_port,
 2473                                                     src_ip, src_port, &fw_ugid_cache,
 2474                                                     &ugid_lookup, args->inp);
 2475                                 break;
 2476 
 2477                         case O_RECV:
 2478                                 match = iface_match(m->m_pkthdr.rcvif,
 2479                                     (ipfw_insn_if *)cmd);
 2480                                 break;
 2481 
 2482                         case O_XMIT:
 2483                                 match = iface_match(oif, (ipfw_insn_if *)cmd);
 2484                                 break;
 2485 
 2486                         case O_VIA:
 2487                                 match = iface_match(oif ? oif :
 2488                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
 2489                                 break;
 2490 
 2491                         case O_MACADDR2:
 2492                                 if (args->eh != NULL) { /* have MAC header */
 2493                                         u_int32_t *want = (u_int32_t *)
 2494                                                 ((ipfw_insn_mac *)cmd)->addr;
 2495                                         u_int32_t *mask = (u_int32_t *)
 2496                                                 ((ipfw_insn_mac *)cmd)->mask;
 2497                                         u_int32_t *hdr = (u_int32_t *)args->eh;
 2498 
 2499                                         match =
 2500                                             ( want[0] == (hdr[0] & mask[0]) &&
 2501                                               want[1] == (hdr[1] & mask[1]) &&
 2502                                               want[2] == (hdr[2] & mask[2]) );
 2503                                 }
 2504                                 break;
 2505 
 2506                         case O_MAC_TYPE:
 2507                                 if (args->eh != NULL) {
 2508                                         u_int16_t t =
 2509                                             ntohs(args->eh->ether_type);
 2510                                         u_int16_t *p =
 2511                                             ((ipfw_insn_u16 *)cmd)->ports;
 2512                                         int i;
 2513 
 2514                                         for (i = cmdlen - 1; !match && i>0;
 2515                                             i--, p += 2)
 2516                                                 match = (t>=p[0] && t<=p[1]);
 2517                                 }
 2518                                 break;
 2519 
 2520                         case O_FRAG:
 2521                                 match = (offset != 0);
 2522                                 break;
 2523 
 2524                         case O_IN:      /* "out" is "not in" */
 2525                                 match = (oif == NULL);
 2526                                 break;
 2527 
 2528                         case O_LAYER2:
 2529                                 match = (args->eh != NULL);
 2530                                 break;
 2531 
 2532                         case O_DIVERTED:
 2533                                 match = (cmd->arg1 & 1 && divinput_flags &
 2534                                     IP_FW_DIVERT_LOOPBACK_FLAG) ||
 2535                                         (cmd->arg1 & 2 && divinput_flags &
 2536                                     IP_FW_DIVERT_OUTPUT_FLAG);
 2537                                 break;
 2538 
 2539                         case O_PROTO:
 2540                                 /*
 2541                                  * We do not allow an arg of 0 so the
 2542                                  * check of "proto" only suffices.
 2543                                  */
 2544                                 match = (proto == cmd->arg1);
 2545                                 break;
 2546 
 2547                         case O_IP_SRC:
 2548                                 match = is_ipv4 &&
 2549                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
 2550                                     src_ip.s_addr);
 2551                                 break;
 2552 
 2553                         case O_IP_SRC_LOOKUP:
 2554                         case O_IP_DST_LOOKUP:
 2555                                 if (is_ipv4) {
 2556                                     uint32_t a =
 2557                                         (cmd->opcode == O_IP_DST_LOOKUP) ?
 2558                                             dst_ip.s_addr : src_ip.s_addr;
 2559                                     uint32_t v;
 2560 
 2561                                     match = lookup_table(cmd->arg1, a, &v);
 2562                                     if (!match)
 2563                                         break;
 2564                                     if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
 2565                                         match =
 2566                                             ((ipfw_insn_u32 *)cmd)->d[0] == v;
 2567                                 }
 2568                                 break;
 2569 
 2570                         case O_IP_SRC_MASK:
 2571                         case O_IP_DST_MASK:
 2572                                 if (is_ipv4) {
 2573                                     uint32_t a =
 2574                                         (cmd->opcode == O_IP_DST_MASK) ?
 2575                                             dst_ip.s_addr : src_ip.s_addr;
 2576                                     uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
 2577                                     int i = cmdlen-1;
 2578 
 2579                                     for (; !match && i>0; i-= 2, p+= 2)
 2580                                         match = (p[0] == (a & p[1]));
 2581                                 }
 2582                                 break;
 2583 
 2584                         case O_IP_SRC_ME:
 2585                                 if (is_ipv4) {
 2586                                         struct ifnet *tif;
 2587 
 2588                                         INADDR_TO_IFP(src_ip, tif);
 2589                                         match = (tif != NULL);
 2590                                 }
 2591                                 break;
 2592 
 2593                         case O_IP_DST_SET:
 2594                         case O_IP_SRC_SET:
 2595                                 if (is_ipv4) {
 2596                                         u_int32_t *d = (u_int32_t *)(cmd+1);
 2597                                         u_int32_t addr =
 2598                                             cmd->opcode == O_IP_DST_SET ?
 2599                                                 args->f_id.dst_ip :
 2600                                                 args->f_id.src_ip;
 2601 
 2602                                             if (addr < d[0])
 2603                                                     break;
 2604                                             addr -= d[0]; /* subtract base */
 2605                                             match = (addr < cmd->arg1) &&
 2606                                                 ( d[ 1 + (addr>>5)] &
 2607                                                   (1<<(addr & 0x1f)) );
 2608                                 }
 2609                                 break;
 2610 
 2611                         case O_IP_DST:
 2612                                 match = is_ipv4 &&
 2613                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
 2614                                     dst_ip.s_addr);
 2615                                 break;
 2616 
 2617                         case O_IP_DST_ME:
 2618                                 if (is_ipv4) {
 2619                                         struct ifnet *tif;
 2620 
 2621                                         INADDR_TO_IFP(dst_ip, tif);
 2622                                         match = (tif != NULL);
 2623                                 }
 2624                                 break;
 2625 
 2626                         case O_IP_SRCPORT:
 2627                         case O_IP_DSTPORT:
 2628                                 /*
 2629                                  * offset == 0 && proto != 0 is enough
 2630                                  * to guarantee that we have a
 2631                                  * packet with port info.
 2632                                  */
 2633                                 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
 2634                                     && offset == 0) {
 2635                                         u_int16_t x =
 2636                                             (cmd->opcode == O_IP_SRCPORT) ?
 2637                                                 src_port : dst_port ;
 2638                                         u_int16_t *p =
 2639                                             ((ipfw_insn_u16 *)cmd)->ports;
 2640                                         int i;
 2641 
 2642                                         for (i = cmdlen - 1; !match && i>0;
 2643                                             i--, p += 2)
 2644                                                 match = (x>=p[0] && x<=p[1]);
 2645                                 }
 2646                                 break;
 2647 
 2648                         case O_ICMPTYPE:
 2649                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
 2650                                     icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
 2651                                 break;
 2652 
 2653 #ifdef INET6
 2654                         case O_ICMP6TYPE:
 2655                                 match = is_ipv6 && offset == 0 &&
 2656                                     proto==IPPROTO_ICMPV6 &&
 2657                                     icmp6type_match(
 2658                                         ICMP6(ulp)->icmp6_type,
 2659                                         (ipfw_insn_u32 *)cmd);
 2660                                 break;
 2661 #endif /* INET6 */
 2662 
 2663                         case O_IPOPT:
 2664                                 match = (is_ipv4 &&
 2665                                     ipopts_match(mtod(m, struct ip *), cmd) );
 2666                                 break;
 2667 
 2668                         case O_IPVER:
 2669                                 match = (is_ipv4 &&
 2670                                     cmd->arg1 == mtod(m, struct ip *)->ip_v);
 2671                                 break;
 2672 
 2673                         case O_IPID:
 2674                         case O_IPLEN:
 2675                         case O_IPTTL:
 2676                                 if (is_ipv4) {  /* only for IP packets */
 2677                                     uint16_t x;
 2678                                     uint16_t *p;
 2679                                     int i;
 2680 
 2681                                     if (cmd->opcode == O_IPLEN)
 2682                                         x = ip_len;
 2683                                     else if (cmd->opcode == O_IPTTL)
 2684                                         x = mtod(m, struct ip *)->ip_ttl;
 2685                                     else /* must be IPID */
 2686                                         x = ntohs(mtod(m, struct ip *)->ip_id);
 2687                                     if (cmdlen == 1) {
 2688                                         match = (cmd->arg1 == x);
 2689                                         break;
 2690                                     }
 2691                                     /* otherwise we have ranges */
 2692                                     p = ((ipfw_insn_u16 *)cmd)->ports;
 2693                                     i = cmdlen - 1;
 2694                                     for (; !match && i>0; i--, p += 2)
 2695                                         match = (x >= p[0] && x <= p[1]);
 2696                                 }
 2697                                 break;
 2698 
 2699                         case O_IPPRECEDENCE:
 2700                                 match = (is_ipv4 &&
 2701                                     (cmd->arg1 == (mtod(m, struct ip *)->ip_tos & 0xe0)) );
 2702                                 break;
 2703 
 2704                         case O_IPTOS:
 2705                                 match = (is_ipv4 &&
 2706                                     flags_match(cmd, mtod(m, struct ip *)->ip_tos));
 2707                                 break;
 2708 
 2709                         case O_TCPDATALEN:
 2710                                 if (proto == IPPROTO_TCP && offset == 0) {
 2711                                     struct tcphdr *tcp;
 2712                                     uint16_t x;
 2713                                     uint16_t *p;
 2714                                     int i;
 2715 
 2716                                     tcp = TCP(ulp);
 2717                                     x = ip_len -
 2718                                         ((ip->ip_hl + tcp->th_off) << 2);
 2719                                     if (cmdlen == 1) {
 2720                                         match = (cmd->arg1 == x);
 2721                                         break;
 2722                                     }
 2723                                     /* otherwise we have ranges */
 2724                                     p = ((ipfw_insn_u16 *)cmd)->ports;
 2725                                     i = cmdlen - 1;
 2726                                     for (; !match && i>0; i--, p += 2)
 2727                                         match = (x >= p[0] && x <= p[1]);
 2728                                 }
 2729                                 break;
 2730 
 2731                         case O_TCPFLAGS:
 2732                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2733                                     flags_match(cmd, TCP(ulp)->th_flags));
 2734                                 break;
 2735 
 2736                         case O_TCPOPTS:
 2737                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2738                                     tcpopts_match(TCP(ulp), cmd));
 2739                                 break;
 2740 
 2741                         case O_TCPSEQ:
 2742                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2743                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
 2744                                         TCP(ulp)->th_seq);
 2745                                 break;
 2746 
 2747                         case O_TCPACK:
 2748                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2749                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
 2750                                         TCP(ulp)->th_ack);
 2751                                 break;
 2752 
 2753                         case O_TCPWIN:
 2754                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2755                                     cmd->arg1 == TCP(ulp)->th_win);
 2756                                 break;
 2757 
 2758                         case O_ESTAB:
 2759                                 /* reject packets which have SYN only */
 2760                                 /* XXX should i also check for TH_ACK ? */
 2761                                 match = (proto == IPPROTO_TCP && offset == 0 &&
 2762                                     (TCP(ulp)->th_flags &
 2763                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
 2764                                 break;
 2765 
 2766                         case O_ALTQ: {
 2767                                 struct altq_tag *at;
 2768                                 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
 2769 
 2770                                 match = 1;
 2771                                 mtag = m_tag_find(m, PACKET_TAG_PF_QID, NULL);
 2772                                 if (mtag != NULL)
 2773                                         break;
 2774                                 mtag = m_tag_get(PACKET_TAG_PF_QID,
 2775                                                 sizeof(struct altq_tag),
 2776                                                 M_NOWAIT);
 2777                                 if (mtag == NULL) {
 2778                                         /*
 2779                                          * Let the packet fall back to the
 2780                                          * default ALTQ.
 2781                                          */
 2782                                         break;
 2783                                 }
 2784                                 at = (struct altq_tag *)(mtag+1);
 2785                                 at->qid = altq->qid;
 2786                                 if (is_ipv4)
 2787                                         at->af = AF_INET;
 2788                                 else
 2789                                         at->af = AF_LINK;
 2790                                 at->hdr = ip;
 2791                                 m_tag_prepend(m, mtag);
 2792                                 break;
 2793                         }
 2794 
 2795                         case O_LOG:
 2796                                 if (fw_verbose)
 2797                                         ipfw_log(f, hlen, args, m, oif, offset);
 2798                                 match = 1;
 2799                                 break;
 2800 
 2801                         case O_PROB:
 2802                                 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
 2803                                 break;
 2804 
 2805                         case O_VERREVPATH:
 2806                                 /* Outgoing packets automatically pass/match */
 2807                                 match = ((oif != NULL) ||
 2808                                     (m->m_pkthdr.rcvif == NULL) ||
 2809                                     (
 2810 #ifdef INET6
 2811                                     is_ipv6 ?
 2812                                         verify_path6(&(args->f_id.src_ip6),
 2813                                             m->m_pkthdr.rcvif) :
 2814 #endif
 2815                                     verify_path(src_ip, m->m_pkthdr.rcvif)));
 2816                                 break;
 2817 
 2818                         case O_VERSRCREACH:
 2819                                 /* Outgoing packets automatically pass/match */
 2820                                 match = (hlen > 0 && ((oif != NULL) ||
 2821 #ifdef INET6
 2822                                     is_ipv6 ?
 2823                                         verify_path6(&(args->f_id.src_ip6),
 2824                                             NULL) :
 2825 #endif
 2826                                     verify_path(src_ip, NULL)));
 2827                                 break;
 2828 
 2829                         case O_ANTISPOOF:
 2830                                 /* Outgoing packets automatically pass/match */
 2831                                 if (oif == NULL && hlen > 0 &&
 2832                                     (  (is_ipv4 && in_localaddr(src_ip))
 2833 #ifdef INET6
 2834                                     || (is_ipv6 &&
 2835                                         in6_localaddr(&(args->f_id.src_ip6)))
 2836 #endif
 2837                                     ))
 2838                                         match =
 2839 #ifdef INET6
 2840                                             is_ipv6 ? verify_path6(
 2841                                                 &(args->f_id.src_ip6),
 2842                                                 m->m_pkthdr.rcvif) :
 2843 #endif
 2844                                             verify_path(src_ip,
 2845                                                 m->m_pkthdr.rcvif);
 2846                                 else
 2847                                         match = 1;
 2848                                 break;
 2849 
 2850                         case O_IPSEC:
 2851 #ifdef FAST_IPSEC
 2852                                 match = (m_tag_find(m,
 2853                                     PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
 2854 #endif
 2855 #ifdef IPSEC
 2856                                 match = (ipsec_getnhist(m) != 0);
 2857 #endif
 2858                                 /* otherwise no match */
 2859                                 break;
 2860 
 2861 #ifdef INET6
 2862                         case O_IP6_SRC:
 2863                                 match = is_ipv6 &&
 2864                                     IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
 2865                                     &((ipfw_insn_ip6 *)cmd)->addr6);
 2866                                 break;
 2867 
 2868                         case O_IP6_DST:
 2869                                 match = is_ipv6 &&
 2870                                 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
 2871                                     &((ipfw_insn_ip6 *)cmd)->addr6);
 2872                                 break;
 2873                         case O_IP6_SRC_MASK:
 2874                                 if (is_ipv6) {
 2875                                         ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
 2876                                         struct in6_addr p = args->f_id.src_ip6;
 2877 
 2878                                         APPLY_MASK(&p, &te->mask6);
 2879                                         match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
 2880                                 }
 2881                                 break;
 2882 
 2883                         case O_IP6_DST_MASK:
 2884                                 if (is_ipv6) {
 2885                                         ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
 2886                                         struct in6_addr p = args->f_id.dst_ip6;
 2887 
 2888                                         APPLY_MASK(&p, &te->mask6);
 2889                                         match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
 2890                                 }
 2891                                 break;
 2892 
 2893                         case O_IP6_SRC_ME:
 2894                                 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
 2895                                 break;
 2896 
 2897                         case O_IP6_DST_ME:
 2898                                 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
 2899                                 break;
 2900 
 2901                         case O_FLOW6ID:
 2902                                 match = is_ipv6 &&
 2903                                     flow6id_match(args->f_id.flow_id6,
 2904                                     (ipfw_insn_u32 *) cmd);
 2905                                 break;
 2906 
 2907                         case O_EXT_HDR:
 2908                                 match = is_ipv6 &&
 2909                                     (ext_hd & ((ipfw_insn *) cmd)->arg1);
 2910                                 break;
 2911 
 2912                         case O_IP6:
 2913                                 match = is_ipv6;
 2914                                 break;
 2915 #endif
 2916 
 2917                         case O_IP4:
 2918                                 match = is_ipv4;
 2919                                 break;
 2920 
 2921                         /*
 2922                          * The second set of opcodes represents 'actions',
 2923                          * i.e. the terminal part of a rule once the packet
 2924                          * matches all previous patterns.
 2925                          * Typically there is only one action for each rule,
 2926                          * and the opcode is stored at the end of the rule
 2927                          * (but there are exceptions -- see below).
 2928                          *
 2929                          * In general, here we set retval and terminate the
 2930                          * outer loop (would be a 'break 3' in some language,
 2931                          * but we need to do a 'goto done').
 2932                          *
 2933                          * Exceptions:
 2934                          * O_COUNT and O_SKIPTO actions:
 2935                          *   instead of terminating, we jump to the next rule
 2936                          *   ('goto next_rule', equivalent to a 'break 2'),
 2937                          *   or to the SKIPTO target ('goto again' after
 2938                          *   having set f, cmd and l), respectively.
 2939                          *
 2940                          * O_LOG and O_ALTQ action parameters:
 2941                          *   perform some action and set match = 1;
 2942                          *
 2943                          * O_LIMIT and O_KEEP_STATE: these opcodes are
 2944                          *   not real 'actions', and are stored right
 2945                          *   before the 'action' part of the rule.
 2946                          *   These opcodes try to install an entry in the
 2947                          *   state tables; if successful, we continue with
 2948                          *   the next opcode (match=1; break;), otherwise
 2949                          *   the packet *   must be dropped
 2950                          *   ('goto done' after setting retval);
 2951                          *
 2952                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
 2953                          *   cause a lookup of the state table, and a jump
 2954                          *   to the 'action' part of the parent rule
 2955                          *   ('goto check_body') if an entry is found, or
 2956                          *   (CHECK_STATE only) a jump to the next rule if
 2957                          *   the entry is not found ('goto next_rule').
 2958                          *   The result of the lookup is cached to make
 2959                          *   further instances of these opcodes are
 2960                          *   effectively NOPs.
 2961                          */
 2962                         case O_LIMIT:
 2963                         case O_KEEP_STATE:
 2964                                 if (install_state(f,
 2965                                     (ipfw_insn_limit *)cmd, args)) {
 2966                                         retval = IP_FW_DENY;
 2967                                         goto done; /* error/limit violation */
 2968                                 }
 2969                                 match = 1;
 2970                                 break;
 2971 
 2972                         case O_PROBE_STATE:
 2973                         case O_CHECK_STATE:
 2974                                 /*
 2975                                  * dynamic rules are checked at the first
 2976                                  * keep-state or check-state occurrence,
 2977                                  * with the result being stored in dyn_dir.
 2978                                  * The compiler introduces a PROBE_STATE
 2979                                  * instruction for us when we have a
 2980                                  * KEEP_STATE (because PROBE_STATE needs
 2981                                  * to be run first).
 2982                                  */
 2983                                 if (dyn_dir == MATCH_UNKNOWN &&
 2984                                     (q = lookup_dyn_rule(&args->f_id,
 2985                                      &dyn_dir, proto == IPPROTO_TCP ?
 2986                                         TCP(ulp) : NULL))
 2987                                         != NULL) {
 2988                                         /*
 2989                                          * Found dynamic entry, update stats
 2990                                          * and jump to the 'action' part of
 2991                                          * the parent rule.
 2992                                          */
 2993                                         q->pcnt++;
 2994                                         q->bcnt += pktlen;
 2995                                         f = q->rule;
 2996                                         cmd = ACTION_PTR(f);
 2997                                         l = f->cmd_len - f->act_ofs;
 2998                                         IPFW_DYN_UNLOCK();
 2999                                         goto check_body;
 3000                                 }
 3001                                 /*
 3002                                  * Dynamic entry not found. If CHECK_STATE,
 3003                                  * skip to next rule, if PROBE_STATE just
 3004                                  * ignore and continue with next opcode.
 3005                                  */
 3006                                 if (cmd->opcode == O_CHECK_STATE)
 3007                                         goto next_rule;
 3008                                 match = 1;
 3009                                 break;
 3010 
 3011                         case O_ACCEPT:
 3012                                 retval = 0;     /* accept */
 3013                                 goto done;
 3014 
 3015                         case O_PIPE:
 3016                         case O_QUEUE:
 3017                                 args->rule = f; /* report matching rule */
 3018                                 args->cookie = cmd->arg1;
 3019                                 retval = IP_FW_DUMMYNET;
 3020                                 goto done;
 3021 
 3022                         case O_DIVERT:
 3023                         case O_TEE: {
 3024                                 struct divert_tag *dt;
 3025 
 3026                                 if (args->eh) /* not on layer 2 */
 3027                                         break;
 3028                                 mtag = m_tag_get(PACKET_TAG_DIVERT,
 3029                                                 sizeof(struct divert_tag),
 3030                                                 M_NOWAIT);
 3031                                 if (mtag == NULL) {
 3032                                         /* XXX statistic */
 3033                                         /* drop packet */
 3034                                         IPFW_RUNLOCK(chain);
 3035                                         return (IP_FW_DENY);
 3036                                 }
 3037                                 dt = (struct divert_tag *)(mtag+1);
 3038                                 dt->cookie = f->rulenum;
 3039                                 dt->info = cmd->arg1;
 3040                                 m_tag_prepend(m, mtag);
 3041                                 retval = (cmd->opcode == O_DIVERT) ?
 3042                                     IP_FW_DIVERT : IP_FW_TEE;
 3043                                 goto done;
 3044                         }
 3045 
 3046                         case O_COUNT:
 3047                         case O_SKIPTO:
 3048                                 f->pcnt++;      /* update stats */
 3049                                 f->bcnt += pktlen;
 3050                                 f->timestamp = time_second;
 3051                                 if (cmd->opcode == O_COUNT)
 3052                                         goto next_rule;
 3053                                 /* handle skipto */
 3054                                 if (f->next_rule == NULL)
 3055                                         lookup_next_rule(f);
 3056                                 f = f->next_rule;
 3057                                 goto again;
 3058 
 3059                         case O_REJECT:
 3060                                 /*
 3061                                  * Drop the packet and send a reject notice
 3062                                  * if the packet is not ICMP (or is an ICMP
 3063                                  * query), and it is not multicast/broadcast.
 3064                                  */
 3065                                 if (hlen > 0 && is_ipv4 && offset == 0 &&
 3066                                     (proto != IPPROTO_ICMP ||
 3067                                      is_icmp_query(ICMP(ulp))) &&
 3068                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
 3069                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
 3070                                         send_reject(args, cmd->arg1,
 3071                                             offset,ip_len);
 3072                                         m = args->m;
 3073                                 }
 3074                                 /* FALLTHROUGH */
 3075 #ifdef INET6
 3076                         case O_UNREACH6:
 3077                                 if (hlen > 0 && is_ipv6 &&
 3078                                     (proto != IPPROTO_ICMPV6 ||
 3079                                      (is_icmp6_query(args->f_id.flags) == 1)) &&
 3080                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
 3081                                     !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
 3082                                         send_reject6(args, cmd->arg1,
 3083                                             offset, hlen);
 3084                                         m = args->m;
 3085                                 }
 3086                                 /* FALLTHROUGH */
 3087 #endif
 3088                         case O_DENY:
 3089                                 retval = IP_FW_DENY;
 3090                                 goto done;
 3091 
 3092                         case O_FORWARD_IP:
 3093                                 if (args->eh)   /* not valid on layer2 pkts */
 3094                                         break;
 3095                                 if (!q || dyn_dir == MATCH_FORWARD)
 3096                                         args->next_hop =
 3097                                             &((ipfw_insn_sa *)cmd)->sa;
 3098                                 retval = IP_FW_PASS;
 3099                                 goto done;
 3100 
 3101                         case O_NETGRAPH:
 3102                         case O_NGTEE:
 3103                                 args->rule = f; /* report matching rule */
 3104                                 args->cookie = cmd->arg1;
 3105                                 retval = (cmd->opcode == O_NETGRAPH) ?
 3106                                     IP_FW_NETGRAPH : IP_FW_NGTEE;
 3107                                 goto done;
 3108 
 3109                         default:
 3110                                 panic("-- unknown opcode %d\n", cmd->opcode);
 3111                         } /* end of switch() on opcodes */
 3112 
 3113                         if (cmd->len & F_NOT)
 3114                                 match = !match;
 3115 
 3116                         if (match) {
 3117                                 if (cmd->len & F_OR)
 3118                                         skip_or = 1;
 3119                         } else {
 3120                                 if (!(cmd->len & F_OR)) /* not an OR block, */
 3121                                         break;          /* try next rule    */
 3122                         }
 3123 
 3124                 }       /* end of inner for, scan opcodes */
 3125 
 3126 next_rule:;             /* try next rule                */
 3127 
 3128         }               /* end of outer for, scan rules */
 3129         printf("ipfw: ouch!, skip past end of rules, denying packet\n");
 3130         IPFW_RUNLOCK(chain);
 3131         return (IP_FW_DENY);
 3132 
 3133 done:
 3134         /* Update statistics */
 3135         f->pcnt++;
 3136         f->bcnt += pktlen;
 3137         f->timestamp = time_second;
 3138         IPFW_RUNLOCK(chain);
 3139         return (retval);
 3140 
 3141 pullup_failed:
 3142         if (fw_verbose)
 3143                 printf("ipfw: pullup failed\n");
 3144         return (IP_FW_DENY);
 3145 }
 3146 
 3147 /*
 3148  * When a rule is added/deleted, clear the next_rule pointers in all rules.
 3149  * These will be reconstructed on the fly as packets are matched.
 3150  */
 3151 static void
 3152 flush_rule_ptrs(struct ip_fw_chain *chain)
 3153 {
 3154         struct ip_fw *rule;
 3155 
 3156         IPFW_WLOCK_ASSERT(chain);
 3157 
 3158         for (rule = chain->rules; rule; rule = rule->next)
 3159                 rule->next_rule = NULL;
 3160 }
 3161 
 3162 /*
 3163  * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
 3164  * pipe/queue, or to all of them (match == NULL).
 3165  */
 3166 void
 3167 flush_pipe_ptrs(struct dn_flow_set *match)
 3168 {
 3169         struct ip_fw *rule;
 3170 
 3171         IPFW_WLOCK(&layer3_chain);
 3172         for (rule = layer3_chain.rules; rule; rule = rule->next) {
 3173                 ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
 3174 
 3175                 if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
 3176                         continue;
 3177                 /*
 3178                  * XXX Use bcmp/bzero to handle pipe_ptr to overcome
 3179                  * possible alignment problems on 64-bit architectures.
 3180                  * This code is seldom used so we do not worry too
 3181                  * much about efficiency.
 3182                  */
 3183                 if (match == NULL ||
 3184                     !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
 3185                         bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
 3186         }
 3187         IPFW_WUNLOCK(&layer3_chain);
 3188 }
 3189 
 3190 /*
 3191  * Add a new rule to the list. Copy the rule into a malloc'ed area, then
 3192  * possibly create a rule number and add the rule to the list.
 3193  * Update the rule_number in the input struct so the caller knows it as well.
 3194  */
 3195 static int
 3196 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
 3197 {
 3198         struct ip_fw *rule, *f, *prev;
 3199         int l = RULESIZE(input_rule);
 3200 
 3201         if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
 3202                 return (EINVAL);
 3203 
 3204         rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
 3205         if (rule == NULL)
 3206                 return (ENOSPC);
 3207 
 3208         bcopy(input_rule, rule, l);
 3209 
 3210         rule->next = NULL;
 3211         rule->next_rule = NULL;
 3212 
 3213         rule->pcnt = 0;
 3214         rule->bcnt = 0;
 3215         rule->timestamp = 0;
 3216 
 3217         IPFW_WLOCK(chain);
 3218 
 3219         if (chain->rules == NULL) {     /* default rule */
 3220                 chain->rules = rule;
 3221                 goto done;
 3222         }
 3223 
 3224         /*
 3225          * If rulenum is 0, find highest numbered rule before the
 3226          * default rule, and add autoinc_step
 3227          */
 3228         if (autoinc_step < 1)
 3229                 autoinc_step = 1;
 3230         else if (autoinc_step > 1000)
 3231                 autoinc_step = 1000;
 3232         if (rule->rulenum == 0) {
 3233                 /*
 3234                  * locate the highest numbered rule before default
 3235                  */
 3236                 for (f = chain->rules; f; f = f->next) {
 3237                         if (f->rulenum == IPFW_DEFAULT_RULE)
 3238                                 break;
 3239                         rule->rulenum = f->rulenum;
 3240                 }
 3241                 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
 3242                         rule->rulenum += autoinc_step;
 3243                 input_rule->rulenum = rule->rulenum;
 3244         }
 3245 
 3246         /*
 3247          * Now insert the new rule in the right place in the sorted list.
 3248          */
 3249         for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
 3250                 if (f->rulenum > rule->rulenum) { /* found the location */
 3251                         if (prev) {
 3252                                 rule->next = f;
 3253                                 prev->next = rule;
 3254                         } else { /* head insert */
 3255                                 rule->next = chain->rules;
 3256                                 chain->rules = rule;
 3257                         }
 3258                         break;
 3259                 }
 3260         }
 3261         flush_rule_ptrs(chain);
 3262 done:
 3263         static_count++;
 3264         static_len += l;
 3265         IPFW_WUNLOCK(chain);
 3266         DEB(printf("ipfw: installed rule %d, static count now %d\n",
 3267                 rule->rulenum, static_count);)
 3268         return (0);
 3269 }
 3270 
 3271 /**
 3272  * Remove a static rule (including derived * dynamic rules)
 3273  * and place it on the ``reap list'' for later reclamation.
 3274  * The caller is in charge of clearing rule pointers to avoid
 3275  * dangling pointers.
 3276  * @return a pointer to the next entry.
 3277  * Arguments are not checked, so they better be correct.
 3278  */
 3279 static struct ip_fw *
 3280 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
 3281 {
 3282         struct ip_fw *n;
 3283         int l = RULESIZE(rule);
 3284 
 3285         IPFW_WLOCK_ASSERT(chain);
 3286 
 3287         n = rule->next;
 3288         IPFW_DYN_LOCK();
 3289         remove_dyn_rule(rule, NULL /* force removal */);
 3290         IPFW_DYN_UNLOCK();
 3291         if (prev == NULL)
 3292                 chain->rules = n;
 3293         else
 3294                 prev->next = n;
 3295         static_count--;
 3296         static_len -= l;
 3297 
 3298         rule->next = chain->reap;
 3299         chain->reap = rule;
 3300 
 3301         return n;
 3302 }
 3303 
 3304 /**
 3305  * Reclaim storage associated with a list of rules.  This is
 3306  * typically the list created using remove_rule.
 3307  */
 3308 static void
 3309 reap_rules(struct ip_fw *head)
 3310 {
 3311         struct ip_fw *rule;
 3312 
 3313         while ((rule = head) != NULL) {
 3314                 head = head->next;
 3315                 if (DUMMYNET_LOADED)
 3316                         ip_dn_ruledel_ptr(rule);
 3317                 free(rule, M_IPFW);
 3318         }
 3319 }
 3320 
 3321 /*
 3322  * Remove all rules from a chain (except rules in set RESVD_SET
 3323  * unless kill_default = 1).  The caller is responsible for
 3324  * reclaiming storage for the rules left in chain->reap.
 3325  */
 3326 static void
 3327 free_chain(struct ip_fw_chain *chain, int kill_default)
 3328 {
 3329         struct ip_fw *prev, *rule;
 3330 
 3331         IPFW_WLOCK_ASSERT(chain);
 3332 
 3333         flush_rule_ptrs(chain); /* more efficient to do outside the loop */
 3334         for (prev = NULL, rule = chain->rules; rule ; )
 3335                 if (kill_default || rule->set != RESVD_SET)
 3336                         rule = remove_rule(chain, rule, prev);
 3337                 else {
 3338                         prev = rule;
 3339                         rule = rule->next;
 3340                 }
 3341 }
 3342 
 3343 /**
 3344  * Remove all rules with given number, and also do set manipulation.
 3345  * Assumes chain != NULL && *chain != NULL.
 3346  *
 3347  * The argument is an u_int32_t. The low 16 bit are the rule or set number,
 3348  * the next 8 bits are the new set, the top 8 bits are the command:
 3349  *
 3350  *      0       delete rules with given number
 3351  *      1       delete rules with given set number
 3352  *      2       move rules with given number to new set
 3353  *      3       move rules with given set number to new set
 3354  *      4       swap sets with given numbers
 3355  */
 3356 static int
 3357 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
 3358 {
 3359         struct ip_fw *prev = NULL, *rule;
 3360         u_int16_t rulenum;      /* rule or old_set */
 3361         u_int8_t cmd, new_set;
 3362 
 3363         rulenum = arg & 0xffff;
 3364         cmd = (arg >> 24) & 0xff;
 3365         new_set = (arg >> 16) & 0xff;
 3366 
 3367         if (cmd > 4)
 3368                 return EINVAL;
 3369         if (new_set > RESVD_SET)
 3370                 return EINVAL;
 3371         if (cmd == 0 || cmd == 2) {
 3372                 if (rulenum >= IPFW_DEFAULT_RULE)
 3373                         return EINVAL;
 3374         } else {
 3375                 if (rulenum > RESVD_SET)        /* old_set */
 3376                         return EINVAL;
 3377         }
 3378 
 3379         IPFW_WLOCK(chain);
 3380         rule = chain->rules;
 3381         chain->reap = NULL;
 3382         switch (cmd) {
 3383         case 0: /* delete rules with given number */
 3384                 /*
 3385                  * locate first rule to delete
 3386                  */
 3387                 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
 3388                         ;
 3389                 if (rule->rulenum != rulenum) {
 3390                         IPFW_WUNLOCK(chain);
 3391                         return EINVAL;
 3392                 }
 3393 
 3394                 /*
 3395                  * flush pointers outside the loop, then delete all matching
 3396                  * rules. prev remains the same throughout the cycle.
 3397                  */
 3398                 flush_rule_ptrs(chain);
 3399                 while (rule->rulenum == rulenum)
 3400                         rule = remove_rule(chain, rule, prev);
 3401                 break;
 3402 
 3403         case 1: /* delete all rules with given set number */
 3404                 flush_rule_ptrs(chain);
 3405                 rule = chain->rules;
 3406                 while (rule->rulenum < IPFW_DEFAULT_RULE)
 3407                         if (rule->set == rulenum)
 3408                                 rule = remove_rule(chain, rule, prev);
 3409                         else {
 3410                                 prev = rule;
 3411                                 rule = rule->next;
 3412                         }
 3413                 break;
 3414 
 3415         case 2: /* move rules with given number to new set */
 3416                 rule = chain->rules;
 3417                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
 3418                         if (rule->rulenum == rulenum)
 3419                                 rule->set = new_set;
 3420                 break;
 3421 
 3422         case 3: /* move rules with given set number to new set */
 3423                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
 3424                         if (rule->set == rulenum)
 3425                                 rule->set = new_set;
 3426                 break;
 3427 
 3428         case 4: /* swap two sets */
 3429                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
 3430                         if (rule->set == rulenum)
 3431                                 rule->set = new_set;
 3432                         else if (rule->set == new_set)
 3433                                 rule->set = rulenum;
 3434                 break;
 3435         }
 3436         /*
 3437          * Look for rules to reclaim.  We grab the list before
 3438          * releasing the lock then reclaim them w/o the lock to
 3439          * avoid a LOR with dummynet.
 3440          */
 3441         rule = chain->reap;
 3442         chain->reap = NULL;
 3443         IPFW_WUNLOCK(chain);
 3444         if (rule)
 3445                 reap_rules(rule);
 3446         return 0;
 3447 }
 3448 
 3449 /*
 3450  * Clear counters for a specific rule.
 3451  * The enclosing "table" is assumed locked.
 3452  */
 3453 static void
 3454 clear_counters(struct ip_fw *rule, int log_only)
 3455 {
 3456         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
 3457 
 3458         if (log_only == 0) {
 3459                 rule->bcnt = rule->pcnt = 0;
 3460                 rule->timestamp = 0;
 3461         }
 3462         if (l->o.opcode == O_LOG)
 3463                 l->log_left = l->max_log;
 3464 }
 3465 
 3466 /**
 3467  * Reset some or all counters on firewall rules.
 3468  * @arg frwl is null to clear all entries, or contains a specific
 3469  * rule number.
 3470  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
 3471  */
 3472 static int
 3473 zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
 3474 {
 3475         struct ip_fw *rule;
 3476         char *msg;
 3477 
 3478         IPFW_WLOCK(chain);
 3479         if (rulenum == 0) {
 3480                 norule_counter = 0;
 3481                 for (rule = chain->rules; rule; rule = rule->next)
 3482                         clear_counters(rule, log_only);
 3483                 msg = log_only ? "ipfw: All logging counts reset.\n" :
 3484                                 "ipfw: Accounting cleared.\n";
 3485         } else {
 3486                 int cleared = 0;
 3487                 /*
 3488                  * We can have multiple rules with the same number, so we
 3489                  * need to clear them all.
 3490                  */
 3491                 for (rule = chain->rules; rule; rule = rule->next)
 3492                         if (rule->rulenum == rulenum) {
 3493                                 while (rule && rule->rulenum == rulenum) {
 3494                                         clear_counters(rule, log_only);
 3495                                         rule = rule->next;
 3496                                 }
 3497                                 cleared = 1;
 3498                                 break;
 3499                         }
 3500                 if (!cleared) { /* we did not find any matching rules */
 3501                         IPFW_WUNLOCK(chain);
 3502                         return (EINVAL);
 3503                 }
 3504                 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
 3505                                 "ipfw: Entry %d cleared.\n";
 3506         }
 3507         IPFW_WUNLOCK(chain);
 3508 
 3509         if (fw_verbose)
 3510                 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
 3511         return (0);
 3512 }
 3513 
 3514 /*
 3515  * Check validity of the structure before insert.
 3516  * Fortunately rules are simple, so this mostly need to check rule sizes.
 3517  */
 3518 static int
 3519 check_ipfw_struct(struct ip_fw *rule, int size)
 3520 {
 3521         int l, cmdlen = 0;
 3522         int have_action=0;
 3523         ipfw_insn *cmd;
 3524 
 3525         if (size < sizeof(*rule)) {
 3526                 printf("ipfw: rule too short\n");
 3527                 return (EINVAL);
 3528         }
 3529         /* first, check for valid size */
 3530         l = RULESIZE(rule);
 3531         if (l != size) {
 3532                 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
 3533                 return (EINVAL);
 3534         }
 3535         if (rule->act_ofs >= rule->cmd_len) {
 3536                 printf("ipfw: bogus action offset (%u > %u)\n",
 3537                     rule->act_ofs, rule->cmd_len - 1);
 3538                 return (EINVAL);
 3539         }
 3540         /*
 3541          * Now go for the individual checks. Very simple ones, basically only
 3542          * instruction sizes.
 3543          */
 3544         for (l = rule->cmd_len, cmd = rule->cmd ;
 3545                         l > 0 ; l -= cmdlen, cmd += cmdlen) {
 3546                 cmdlen = F_LEN(cmd);
 3547                 if (cmdlen > l) {
 3548                         printf("ipfw: opcode %d size truncated\n",
 3549                             cmd->opcode);
 3550                         return EINVAL;
 3551                 }
 3552                 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
 3553                 switch (cmd->opcode) {
 3554                 case O_PROBE_STATE:
 3555                 case O_KEEP_STATE:
 3556                 case O_PROTO:
 3557                 case O_IP_SRC_ME:
 3558                 case O_IP_DST_ME:
 3559                 case O_LAYER2:
 3560                 case O_IN:
 3561                 case O_FRAG:
 3562                 case O_DIVERTED:
 3563                 case O_IPOPT:
 3564                 case O_IPTOS:
 3565                 case O_IPPRECEDENCE:
 3566                 case O_IPVER:
 3567                 case O_TCPWIN:
 3568                 case O_TCPFLAGS:
 3569                 case O_TCPOPTS:
 3570                 case O_ESTAB:
 3571                 case O_VERREVPATH:
 3572                 case O_VERSRCREACH:
 3573                 case O_ANTISPOOF:
 3574                 case O_IPSEC:
 3575 #ifdef INET6
 3576                 case O_IP6_SRC_ME:
 3577                 case O_IP6_DST_ME:
 3578                 case O_EXT_HDR:
 3579                 case O_IP6:
 3580 #endif
 3581                 case O_IP4:
 3582                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
 3583                                 goto bad_size;
 3584                         break;
 3585 
 3586                 case O_UID:
 3587                 case O_GID:
 3588                 case O_JAIL:
 3589                 case O_IP_SRC:
 3590                 case O_IP_DST:
 3591                 case O_TCPSEQ:
 3592                 case O_TCPACK:
 3593                 case O_PROB:
 3594                 case O_ICMPTYPE:
 3595                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
 3596                                 goto bad_size;
 3597                         break;
 3598 
 3599                 case O_LIMIT:
 3600                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
 3601                                 goto bad_size;
 3602                         break;
 3603 
 3604                 case O_LOG:
 3605                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
 3606                                 goto bad_size;
 3607 
 3608                         ((ipfw_insn_log *)cmd)->log_left =
 3609                             ((ipfw_insn_log *)cmd)->max_log;
 3610 
 3611                         break;
 3612 
 3613                 case O_IP_SRC_MASK:
 3614                 case O_IP_DST_MASK:
 3615                         /* only odd command lengths */
 3616                         if ( !(cmdlen & 1) || cmdlen > 31)
 3617                                 goto bad_size;
 3618                         break;
 3619 
 3620                 case O_IP_SRC_SET:
 3621                 case O_IP_DST_SET:
 3622                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
 3623                                 printf("ipfw: invalid set size %d\n",
 3624                                         cmd->arg1);
 3625                                 return EINVAL;
 3626                         }
 3627                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
 3628                             (cmd->arg1+31)/32 )
 3629                                 goto bad_size;
 3630                         break;
 3631 
 3632                 case O_IP_SRC_LOOKUP:
 3633                 case O_IP_DST_LOOKUP:
 3634                         if (cmd->arg1 >= IPFW_TABLES_MAX) {
 3635                                 printf("ipfw: invalid table number %d\n",
 3636                                     cmd->arg1);
 3637                                 return (EINVAL);
 3638                         }
 3639                         if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
 3640                             cmdlen != F_INSN_SIZE(ipfw_insn_u32))
 3641                                 goto bad_size;
 3642                         break;
 3643 
 3644                 case O_MACADDR2:
 3645                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
 3646                                 goto bad_size;
 3647                         break;
 3648 
 3649                 case O_NOP:
 3650                 case O_IPID:
 3651                 case O_IPTTL:
 3652                 case O_IPLEN:
 3653                 case O_TCPDATALEN:
 3654                         if (cmdlen < 1 || cmdlen > 31)
 3655                                 goto bad_size;
 3656                         break;
 3657 
 3658                 case O_MAC_TYPE:
 3659                 case O_IP_SRCPORT:
 3660                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
 3661                         if (cmdlen < 2 || cmdlen > 31)
 3662                                 goto bad_size;
 3663                         break;
 3664 
 3665                 case O_RECV:
 3666                 case O_XMIT:
 3667                 case O_VIA:
 3668                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
 3669                                 goto bad_size;
 3670                         break;
 3671 
 3672                 case O_ALTQ:
 3673                         if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
 3674                                 goto bad_size;
 3675                         break;
 3676 
 3677                 case O_PIPE:
 3678                 case O_QUEUE:
 3679                         if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
 3680                                 goto bad_size;
 3681                         goto check_action;
 3682 
 3683                 case O_FORWARD_IP:
 3684 #ifdef  IPFIREWALL_FORWARD
 3685                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
 3686                                 goto bad_size;
 3687                         goto check_action;
 3688 #else
 3689                         return EINVAL;
 3690 #endif
 3691 
 3692                 case O_DIVERT:
 3693                 case O_TEE:
 3694                         if (ip_divert_ptr == NULL)
 3695                                 return EINVAL;
 3696                         else
 3697                                 goto check_size;
 3698                 case O_NETGRAPH:
 3699                 case O_NGTEE:
 3700                         if (!NG_IPFW_LOADED)
 3701                                 return EINVAL;
 3702                         else
 3703                                 goto check_size;
 3704                 case O_FORWARD_MAC: /* XXX not implemented yet */
 3705                 case O_CHECK_STATE:
 3706                 case O_COUNT:
 3707                 case O_ACCEPT:
 3708                 case O_DENY:
 3709                 case O_REJECT:
 3710 #ifdef INET6
 3711                 case O_UNREACH6:
 3712 #endif
 3713                 case O_SKIPTO:
 3714 check_size:
 3715                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
 3716                                 goto bad_size;
 3717 check_action:
 3718                         if (have_action) {
 3719                                 printf("ipfw: opcode %d, multiple actions"
 3720                                         " not allowed\n",
 3721                                         cmd->opcode);
 3722                                 return EINVAL;
 3723                         }
 3724                         have_action = 1;
 3725                         if (l != cmdlen) {
 3726                                 printf("ipfw: opcode %d, action must be"
 3727                                         " last opcode\n",
 3728                                         cmd->opcode);
 3729                                 return EINVAL;
 3730                         }
 3731                         break;
 3732 #ifdef INET6
 3733                 case O_IP6_SRC:
 3734                 case O_IP6_DST:
 3735                         if (cmdlen != F_INSN_SIZE(struct in6_addr) +
 3736                             F_INSN_SIZE(ipfw_insn))
 3737                                 goto bad_size;
 3738                         break;
 3739 
 3740                 case O_FLOW6ID:
 3741                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
 3742                             ((ipfw_insn_u32 *)cmd)->o.arg1)
 3743                                 goto bad_size;
 3744                         break;
 3745 
 3746                 case O_IP6_SRC_MASK:
 3747                 case O_IP6_DST_MASK:
 3748                         if ( !(cmdlen & 1) || cmdlen > 127)
 3749                                 goto bad_size;
 3750                         break;
 3751                 case O_ICMP6TYPE:
 3752                         if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
 3753                                 goto bad_size;
 3754                         break;
 3755 #endif
 3756 
 3757                 default:
 3758                         switch (cmd->opcode) {
 3759 #ifndef INET6
 3760                         case O_IP6_SRC_ME:
 3761                         case O_IP6_DST_ME:
 3762                         case O_EXT_HDR:
 3763                         case O_IP6:
 3764                         case O_UNREACH6:
 3765                         case O_IP6_SRC:
 3766                         case O_IP6_DST:
 3767                         case O_FLOW6ID:
 3768                         case O_IP6_SRC_MASK:
 3769                         case O_IP6_DST_MASK:
 3770                         case O_ICMP6TYPE:
 3771                                 printf("ipfw: no IPv6 support in kernel\n");
 3772                                 return EPROTONOSUPPORT;
 3773 #endif
 3774                         default:
 3775                                 printf("ipfw: opcode %d, unknown opcode\n",
 3776                                         cmd->opcode);
 3777                                 return EINVAL;
 3778                         }
 3779                 }
 3780         }
 3781         if (have_action == 0) {
 3782                 printf("ipfw: missing action\n");
 3783                 return EINVAL;
 3784         }
 3785         return 0;
 3786 
 3787 bad_size:
 3788         printf("ipfw: opcode %d size %d wrong\n",
 3789                 cmd->opcode, cmdlen);
 3790         return EINVAL;
 3791 }
 3792 
 3793 /*
 3794  * Copy the static and dynamic rules to the supplied buffer
 3795  * and return the amount of space actually used.
 3796  */
 3797 static size_t
 3798 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
 3799 {
 3800         char *bp = buf;
 3801         char *ep = bp + space;
 3802         struct ip_fw *rule;
 3803         int i;
 3804 
 3805         /* XXX this can take a long time and locking will block packet flow */
 3806         IPFW_RLOCK(chain);
 3807         for (rule = chain->rules; rule ; rule = rule->next) {
 3808                 /*
 3809                  * Verify the entry fits in the buffer in case the
 3810                  * rules changed between calculating buffer space and
 3811                  * now.  This would be better done using a generation
 3812                  * number but should suffice for now.
 3813                  */
 3814                 i = RULESIZE(rule);
 3815                 if (bp + i <= ep) {
 3816                         bcopy(rule, bp, i);
 3817                         bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
 3818                             sizeof(set_disable));
 3819                         bp += i;
 3820                 }
 3821         }
 3822         IPFW_RUNLOCK(chain);
 3823         if (ipfw_dyn_v) {
 3824                 ipfw_dyn_rule *p, *last = NULL;
 3825 
 3826                 IPFW_DYN_LOCK();
 3827                 for (i = 0 ; i < curr_dyn_buckets; i++)
 3828                         for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
 3829                                 if (bp + sizeof *p <= ep) {
 3830                                         ipfw_dyn_rule *dst =
 3831                                                 (ipfw_dyn_rule *)bp;
 3832                                         bcopy(p, dst, sizeof *p);
 3833                                         bcopy(&(p->rule->rulenum), &(dst->rule),
 3834                                             sizeof(p->rule->rulenum));
 3835                                         /*
 3836                                          * store a non-null value in "next".
 3837                                          * The userland code will interpret a
 3838                                          * NULL here as a marker
 3839                                          * for the last dynamic rule.
 3840                                          */
 3841                                         bcopy(&dst, &dst->next, sizeof(dst));
 3842                                         last = dst;
 3843                                         dst->expire =
 3844                                             TIME_LEQ(dst->expire, time_second) ?
 3845                                                 0 : dst->expire - time_second ;
 3846                                         bp += sizeof(ipfw_dyn_rule);
 3847                                 }
 3848                         }
 3849                 IPFW_DYN_UNLOCK();
 3850                 if (last != NULL) /* mark last dynamic rule */
 3851                         bzero(&last->next, sizeof(last));
 3852         }
 3853         return (bp - (char *)buf);
 3854 }
 3855 
 3856 
 3857 /**
 3858  * {set|get}sockopt parser.
 3859  */
 3860 static int
 3861 ipfw_ctl(struct sockopt *sopt)
 3862 {
 3863 #define RULE_MAXSIZE    (256*sizeof(u_int32_t))
 3864         int error, rule_num;
 3865         size_t size;
 3866         struct ip_fw *buf, *rule;
 3867         u_int32_t rulenum[2];
 3868 
 3869         error = suser(sopt->sopt_td);
 3870         if (error)
 3871                 return (error);
 3872 
 3873         /*
 3874          * Disallow modifications in really-really secure mode, but still allow
 3875          * the logging counters to be reset.
 3876          */
 3877         if (sopt->sopt_name == IP_FW_ADD ||
 3878             (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
 3879 #if __FreeBSD_version >= 500034
 3880                 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
 3881                 if (error)
 3882                         return (error);
 3883 #else /* FreeBSD 4.x */
 3884                 if (securelevel >= 3)
 3885                         return (EPERM);
 3886 #endif
 3887         }
 3888 
 3889         error = 0;
 3890 
 3891         switch (sopt->sopt_name) {
 3892         case IP_FW_GET:
 3893                 /*
 3894                  * pass up a copy of the current rules. Static rules
 3895                  * come first (the last of which has number IPFW_DEFAULT_RULE),
 3896                  * followed by a possibly empty list of dynamic rule.
 3897                  * The last dynamic rule has NULL in the "next" field.
 3898                  *
 3899                  * Note that the calculated size is used to bound the
 3900                  * amount of data returned to the user.  The rule set may
 3901                  * change between calculating the size and returning the
 3902                  * data in which case we'll just return what fits.
 3903                  */
 3904                 size = static_len;      /* size of static rules */
 3905                 if (ipfw_dyn_v)         /* add size of dyn.rules */
 3906                         size += (dyn_count * sizeof(ipfw_dyn_rule));
 3907 
 3908                 /*
 3909                  * XXX todo: if the user passes a short length just to know
 3910                  * how much room is needed, do not bother filling up the
 3911                  * buffer, just jump to the sooptcopyout.
 3912                  */
 3913                 buf = malloc(size, M_TEMP, M_WAITOK);
 3914                 error = sooptcopyout(sopt, buf,
 3915                                 ipfw_getrules(&layer3_chain, buf, size));
 3916                 free(buf, M_TEMP);
 3917                 break;
 3918 
 3919         case IP_FW_FLUSH:
 3920                 /*
 3921                  * Normally we cannot release the lock on each iteration.
 3922                  * We could do it here only because we start from the head all
 3923                  * the times so there is no risk of missing some entries.
 3924                  * On the other hand, the risk is that we end up with
 3925                  * a very inconsistent ruleset, so better keep the lock
 3926                  * around the whole cycle.
 3927                  *
 3928                  * XXX this code can be improved by resetting the head of
 3929                  * the list to point to the default rule, and then freeing
 3930                  * the old list without the need for a lock.
 3931                  */
 3932 
 3933                 IPFW_WLOCK(&layer3_chain);
 3934                 layer3_chain.reap = NULL;
 3935                 free_chain(&layer3_chain, 0 /* keep default rule */);
 3936                 rule = layer3_chain.reap, layer3_chain.reap = NULL;
 3937                 IPFW_WUNLOCK(&layer3_chain);
 3938                 if (layer3_chain.reap != NULL)
 3939                         reap_rules(rule);
 3940                 break;
 3941 
 3942         case IP_FW_ADD:
 3943                 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
 3944                 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
 3945                         sizeof(struct ip_fw) );
 3946                 if (error == 0)
 3947                         error = check_ipfw_struct(rule, sopt->sopt_valsize);
 3948                 if (error == 0) {
 3949                         error = add_rule(&layer3_chain, rule);
 3950                         size = RULESIZE(rule);
 3951                         if (!error && sopt->sopt_dir == SOPT_GET)
 3952                                 error = sooptcopyout(sopt, rule, size);
 3953                 }
 3954                 free(rule, M_TEMP);
 3955                 break;
 3956 
 3957         case IP_FW_DEL:
 3958                 /*
 3959                  * IP_FW_DEL is used for deleting single rules or sets,
 3960                  * and (ab)used to atomically manipulate sets. Argument size
 3961                  * is used to distinguish between the two:
 3962                  *    sizeof(u_int32_t)
 3963                  *      delete single rule or set of rules,
 3964                  *      or reassign rules (or sets) to a different set.
 3965                  *    2*sizeof(u_int32_t)
 3966                  *      atomic disable/enable sets.
 3967                  *      first u_int32_t contains sets to be disabled,
 3968                  *      second u_int32_t contains sets to be enabled.
 3969                  */
 3970                 error = sooptcopyin(sopt, rulenum,
 3971                         2*sizeof(u_int32_t), sizeof(u_int32_t));
 3972                 if (error)
 3973                         break;
 3974                 size = sopt->sopt_valsize;
 3975                 if (size == sizeof(u_int32_t))  /* delete or reassign */
 3976                         error = del_entry(&layer3_chain, rulenum[0]);
 3977                 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
 3978                         set_disable =
 3979                             (set_disable | rulenum[0]) & ~rulenum[1] &
 3980                             ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
 3981                 else
 3982                         error = EINVAL;
 3983                 break;
 3984 
 3985         case IP_FW_ZERO:
 3986         case IP_FW_RESETLOG: /* argument is an int, the rule number */
 3987                 rule_num = 0;
 3988                 if (sopt->sopt_val != 0) {
 3989                     error = sooptcopyin(sopt, &rule_num,
 3990                             sizeof(int), sizeof(int));
 3991                     if (error)
 3992                         break;
 3993                 }
 3994                 error = zero_entry(&layer3_chain, rule_num,
 3995                         sopt->sopt_name == IP_FW_RESETLOG);
 3996                 break;
 3997 
 3998         case IP_FW_TABLE_ADD:
 3999                 {
 4000                         ipfw_table_entry ent;
 4001 
 4002                         error = sooptcopyin(sopt, &ent,
 4003                             sizeof(ent), sizeof(ent));
 4004                         if (error)
 4005                                 break;
 4006                         error = add_table_entry(ent.tbl, ent.addr,
 4007                             ent.masklen, ent.value);
 4008                 }
 4009                 break;
 4010 
 4011         case IP_FW_TABLE_DEL:
 4012                 {
 4013                         ipfw_table_entry ent;
 4014 
 4015                         error = sooptcopyin(sopt, &ent,
 4016                             sizeof(ent), sizeof(ent));
 4017                         if (error)
 4018                                 break;
 4019                         error = del_table_entry(ent.tbl, ent.addr, ent.masklen);
 4020                 }
 4021                 break;
 4022 
 4023         case IP_FW_TABLE_FLUSH:
 4024                 {
 4025                         u_int16_t tbl;
 4026 
 4027                         error = sooptcopyin(sopt, &tbl,
 4028                             sizeof(tbl), sizeof(tbl));
 4029                         if (error)
 4030                                 break;
 4031                         error = flush_table(tbl);
 4032                 }
 4033                 break;
 4034 
 4035         case IP_FW_TABLE_GETSIZE:
 4036                 {
 4037                         u_int32_t tbl, cnt;
 4038 
 4039                         if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
 4040                             sizeof(tbl))))
 4041                                 break;
 4042                         if ((error = count_table(tbl, &cnt)))
 4043                                 break;
 4044                         error = sooptcopyout(sopt, &cnt, sizeof(cnt));
 4045                 }
 4046                 break;
 4047 
 4048         case IP_FW_TABLE_LIST:
 4049                 {
 4050                         ipfw_table *tbl;
 4051 
 4052                         if (sopt->sopt_valsize < sizeof(*tbl)) {
 4053                                 error = EINVAL;
 4054                                 break;
 4055                         }
 4056                         size = sopt->sopt_valsize;
 4057                         tbl = malloc(size, M_TEMP, M_WAITOK);
 4058                         if (tbl == NULL) {
 4059                                 error = ENOMEM;
 4060                                 break;
 4061                         }
 4062                         error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
 4063                         if (error) {
 4064                                 free(tbl, M_TEMP);
 4065                                 break;
 4066                         }
 4067                         tbl->size = (size - sizeof(*tbl)) /
 4068                             sizeof(ipfw_table_entry);
 4069                         error = dump_table(tbl);
 4070                         if (error) {
 4071                                 free(tbl, M_TEMP);
 4072                                 break;
 4073                         }
 4074                         error = sooptcopyout(sopt, tbl, size);
 4075                         free(tbl, M_TEMP);
 4076                 }
 4077                 break;
 4078 
 4079         default:
 4080                 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
 4081                 error = EINVAL;
 4082         }
 4083 
 4084         return (error);
 4085 #undef RULE_MAXSIZE
 4086 }
 4087 
 4088 /**
 4089  * dummynet needs a reference to the default rule, because rules can be
 4090  * deleted while packets hold a reference to them. When this happens,
 4091  * dummynet changes the reference to the default rule (it could well be a
 4092  * NULL pointer, but this way we do not need to check for the special
 4093  * case, plus here he have info on the default behaviour).
 4094  */
 4095 struct ip_fw *ip_fw_default_rule;
 4096 
 4097 /*
 4098  * This procedure is only used to handle keepalives. It is invoked
 4099  * every dyn_keepalive_period
 4100  */
 4101 static void
 4102 ipfw_tick(void * __unused unused)
 4103 {
 4104         struct mbuf *m0, *m, *mnext, **mtailp;
 4105         int i;
 4106         ipfw_dyn_rule *q;
 4107 
 4108         if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
 4109                 goto done;
 4110 
 4111         /*
 4112          * We make a chain of packets to go out here -- not deferring
 4113          * until after we drop the IPFW dynamic rule lock would result
 4114          * in a lock order reversal with the normal packet input -> ipfw
 4115          * call stack.
 4116          */
 4117         m0 = NULL;
 4118         mtailp = &m0;
 4119         IPFW_DYN_LOCK();
 4120         for (i = 0 ; i < curr_dyn_buckets ; i++) {
 4121                 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
 4122                         if (q->dyn_type == O_LIMIT_PARENT)
 4123                                 continue;
 4124                         if (q->id.proto != IPPROTO_TCP)
 4125                                 continue;
 4126                         if ( (q->state & BOTH_SYN) != BOTH_SYN)
 4127                                 continue;
 4128                         if (TIME_LEQ( time_second+dyn_keepalive_interval,
 4129                             q->expire))
 4130                                 continue;       /* too early */
 4131                         if (TIME_LEQ(q->expire, time_second))
 4132                                 continue;       /* too late, rule expired */
 4133 
 4134                         *mtailp = send_pkt(&(q->id), q->ack_rev - 1,
 4135                                 q->ack_fwd, TH_SYN);
 4136                         if (*mtailp != NULL)
 4137                                 mtailp = &(*mtailp)->m_nextpkt;
 4138                         *mtailp = send_pkt(&(q->id), q->ack_fwd - 1,
 4139                                 q->ack_rev, 0);
 4140                         if (*mtailp != NULL)
 4141                                 mtailp = &(*mtailp)->m_nextpkt;
 4142                 }
 4143         }
 4144         IPFW_DYN_UNLOCK();
 4145         for (m = mnext = m0; m != NULL; m = mnext) {
 4146                 mnext = m->m_nextpkt;
 4147                 m->m_nextpkt = NULL;
 4148                 ip_output(m, NULL, NULL, 0, NULL, NULL);
 4149         }
 4150 done:
 4151         callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
 4152 }
 4153 
 4154 int
 4155 ipfw_init(void)
 4156 {
 4157         struct ip_fw default_rule;
 4158         int error;
 4159 
 4160 #ifdef INET6
 4161         /* Setup IPv6 fw sysctl tree. */
 4162         sysctl_ctx_init(&ip6_fw_sysctl_ctx);
 4163         ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
 4164                 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
 4165                 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
 4166         SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
 4167                 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
 4168                 &fw_deny_unknown_exthdrs, 0,
 4169                 "Deny packets with unknown IPv6 Extension Headers");
 4170 #endif
 4171 
 4172         layer3_chain.rules = NULL;
 4173         layer3_chain.want_write = 0;
 4174         layer3_chain.busy_count = 0;
 4175         cv_init(&layer3_chain.cv, "Condition variable for IPFW rw locks");
 4176         IPFW_LOCK_INIT(&layer3_chain);
 4177         ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule zone",
 4178             sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
 4179             UMA_ALIGN_PTR, 0);
 4180         IPFW_DYN_LOCK_INIT();
 4181         callout_init(&ipfw_timeout, NET_CALLOUT_MPSAFE);
 4182 
 4183         bzero(&default_rule, sizeof default_rule);
 4184 
 4185         default_rule.act_ofs = 0;
 4186         default_rule.rulenum = IPFW_DEFAULT_RULE;
 4187         default_rule.cmd_len = 1;
 4188         default_rule.set = RESVD_SET;
 4189 
 4190         default_rule.cmd[0].len = 1;
 4191         default_rule.cmd[0].opcode =
 4192 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
 4193                                 1 ? O_ACCEPT :
 4194 #endif
 4195                                 O_DENY;
 4196 
 4197         error = add_rule(&layer3_chain, &default_rule);
 4198         if (error != 0) {
 4199                 printf("ipfw2: error %u initializing default rule "
 4200                         "(support disabled)\n", error);
 4201                 IPFW_DYN_LOCK_DESTROY();
 4202                 IPFW_LOCK_DESTROY(&layer3_chain);
 4203                 return (error);
 4204         }
 4205 
 4206         ip_fw_default_rule = layer3_chain.rules;
 4207         printf("ipfw2 (+ipv6) initialized, divert %s, "
 4208                 "rule-based forwarding "
 4209 #ifdef IPFIREWALL_FORWARD
 4210                 "enabled, "
 4211 #else
 4212                 "disabled, "
 4213 #endif
 4214                 "default to %s, logging ",
 4215 #ifdef IPDIVERT
 4216                 "enabled",
 4217 #else
 4218                 "loadable",
 4219 #endif
 4220                 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
 4221 
 4222 #ifdef IPFIREWALL_VERBOSE
 4223         fw_verbose = 1;
 4224 #endif
 4225 #ifdef IPFIREWALL_VERBOSE_LIMIT
 4226         verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
 4227 #endif
 4228         if (fw_verbose == 0)
 4229                 printf("disabled\n");
 4230         else if (verbose_limit == 0)
 4231                 printf("unlimited\n");
 4232         else
 4233                 printf("limited to %d packets/entry by default\n",
 4234                     verbose_limit);
 4235 
 4236         init_tables();
 4237         ip_fw_ctl_ptr = ipfw_ctl;
 4238         ip_fw_chk_ptr = ipfw_chk;
 4239         callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
 4240 
 4241         return (0);
 4242 }
 4243 
 4244 void
 4245 ipfw_destroy(void)
 4246 {
 4247         struct ip_fw *reap;
 4248 
 4249         ip_fw_chk_ptr = NULL;
 4250         ip_fw_ctl_ptr = NULL;
 4251         callout_drain(&ipfw_timeout);
 4252         IPFW_WLOCK(&layer3_chain);
 4253         layer3_chain.reap = NULL;
 4254         free_chain(&layer3_chain, 1 /* kill default rule */);
 4255         reap = layer3_chain.reap, layer3_chain.reap = NULL;
 4256         IPFW_WUNLOCK(&layer3_chain);
 4257         if (reap != NULL)
 4258                 reap_rules(reap);
 4259         flush_tables();
 4260         IPFW_DYN_LOCK_DESTROY();
 4261         uma_zdestroy(ipfw_dyn_rule_zone);
 4262         IPFW_LOCK_DESTROY(&layer3_chain);
 4263 
 4264 #ifdef INET6
 4265         /* Free IPv6 fw sysctl tree. */
 4266         sysctl_ctx_free(&ip6_fw_sysctl_ctx);
 4267 #endif
 4268 
 4269         printf("IP firewall unloaded\n");
 4270 }

Cache object: fae705b423966ef58ce38fab6aa47bec


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.