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

Cache object: f4477a791e3f26a8b1994dc66701b6f7


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