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

Cache object: f8aa02d5cac5f67513394f3c5ba2eb16


[ 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.