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


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

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

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

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

Cache object: 64236273adf349472472b5fd6752f5c3


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