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

Cache object: 8ec212ce3e2374318d79bdf15fb6f58f


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