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_fw.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) 1993 Daniel Boulet
    3  * Copyright (c) 1994 Ugen J.S.Antsilevich
    4  * Copyright (c) 1996 Alex Nash
    5  * Copyright (c) 2000 Luigi Rizzo
    6  *
    7  * Redistribution and use in source forms, with and without modification,
    8  * are permitted provided that this entire comment appears intact.
    9  *
   10  * Redistribution in binary form may occur without any restrictions.
   11  * Obviously, it would be nice if you gave credit where credit is due
   12  * but requiring it would be too onerous.
   13  *
   14  * This software is provided ``AS IS'' without any warranties of any kind.
   15  *
   16  * $FreeBSD$
   17  */
   18 
   19 #define STATEFUL        1
   20 #define DEB(x)
   21 #define DDB(x)  x
   22 
   23 /*
   24  * Implement IP packet firewall
   25  */
   26 
   27 #if !defined(KLD_MODULE) && !defined(IPFIREWALL_MODULE)
   28 #include "opt_ipfw.h"
   29 #include "opt_ipdn.h"
   30 #include "opt_ipdivert.h"
   31 #include "opt_inet.h"
   32 #ifndef INET
   33 #error IPFIREWALL requires INET.
   34 #endif /* INET */
   35 #endif
   36 
   37 #include <sys/param.h>
   38 #include <sys/systm.h>
   39 #include <sys/malloc.h>
   40 #include <sys/mbuf.h>
   41 #include <sys/kernel.h>
   42 #include <sys/proc.h>
   43 #include <sys/socket.h>
   44 #include <sys/socketvar.h>
   45 #include <sys/sysctl.h>
   46 #include <sys/ucred.h>
   47 #include <net/if.h>
   48 #include <net/route.h>
   49 #include <netinet/in.h>
   50 #include <netinet/in_systm.h>
   51 #include <netinet/in_pcb.h>
   52 #include <netinet/ip.h>
   53 #include <netinet/ip_var.h>
   54 #include <netinet/ip_icmp.h>
   55 #include <netinet/ip_fw.h>
   56 #ifdef DUMMYNET
   57 #include <netinet/ip_dummynet.h>
   58 #endif
   59 #include <netinet/tcp.h>
   60 #include <netinet/tcp_timer.h>
   61 #include <netinet/tcp_var.h>
   62 #include <netinet/tcpip.h>
   63 #include <netinet/udp.h>
   64 #include <netinet/udp_var.h>
   65 
   66 #include <netinet/if_ether.h> /* XXX ethertype_ip */
   67 
   68 static int fw_debug = 1;
   69 #ifdef IPFIREWALL_VERBOSE
   70 static int fw_verbose = 1;
   71 #else
   72 static int fw_verbose = 0;
   73 #endif
   74 int fw_one_pass = 1 ;
   75 #ifdef IPFIREWALL_VERBOSE_LIMIT
   76 static int fw_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
   77 #else
   78 static int fw_verbose_limit = 0;
   79 #endif
   80 
   81 static u_int64_t counter;       /* counter for ipfw_report(NULL...) */
   82 struct ipfw_flow_id last_pkt ;
   83 
   84 #define IPFW_DEFAULT_RULE       ((u_int)(u_short)~0)
   85 
   86 LIST_HEAD (ip_fw_head, ip_fw_chain) ip_fw_chain;
   87 
   88 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
   89 
   90 #ifdef SYSCTL_NODE
   91 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
   92 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
   93     &fw_enable, 0, "Enable ipfw");
   94 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
   95     &fw_one_pass, 0,
   96     "Only do a single pass through ipfw when using divert(4)/dummynet(4)");
   97 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
   98     &fw_debug, 0, "Enable printing of debug ip_fw statements");
   99 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
  100     &fw_verbose, 0, "Log matches to ipfw rules");
  101 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
  102     &fw_verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
  103 
  104 #if STATEFUL
  105 /*
  106  * Extension for stateful ipfw.
  107  *
  108  * Dynamic rules are stored in lists accessed through a hash table
  109  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
  110  * be modified through the sysctl variable dyn_buckets which is
  111  * updated when the table becomes empty.
  112  *
  113  * XXX currently there is only one list, ipfw_dyn.
  114  *
  115  * When a packet is received, it is first hashed, then matched
  116  * against the entries in the corresponding list.
  117  * Matching occurs according to the rule type. The default is to
  118  * match the four fields and the protocol, and rules are bidirectional.
  119  *
  120  * For a busy proxy/web server we will have lots of connections to
  121  * the server. We could decide for a rule type where we ignore
  122  * ports (different hashing) and avoid special SYN/RST/FIN handling.
  123  *
  124  * XXX when we decide to support more than one rule type, we should
  125  * repeat the hashing multiple times uing only the useful fields.
  126  * Or, we could run the various tests in parallel, because the
  127  * 'move to front' technique should shorten the average search.
  128  *
  129  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
  130  * measured in seconds and depending on the flags.
  131  *
  132  * The total number of dynamic rules is stored in dyn_count.
  133  * The max number of dynamic rules is dyn_max. When we reach
  134  * the maximum number of rules we do not create anymore. This is
  135  * done to avoid consuming too much memory, but also too much
  136  * time when searching on each packet (ideally, we should try instead
  137  * to put a limit on the length of the list on each bucket...).
  138  *
  139  * Each dynamic rules holds a pointer to the parent ipfw rule so
  140  * we know what action to perform. Dynamic rules are removed when
  141  * the parent rule is deleted.
  142  * There are some limitations with dynamic rules -- we do not
  143  * obey the 'randomized match', and we do not do multiple
  144  * passes through the firewall.
  145  * XXX check the latter!!!
  146  */
  147 static struct ipfw_dyn_rule **ipfw_dyn_v = NULL ;
  148 static u_int32_t dyn_buckets = 256 ; /* must be power of 2 */
  149 static u_int32_t curr_dyn_buckets = 256 ; /* must be power of 2 */
  150 static u_int32_t dyn_ack_lifetime = 300 ;
  151 static u_int32_t dyn_syn_lifetime = 20 ;
  152 static u_int32_t dyn_fin_lifetime = 20 ;
  153 static u_int32_t dyn_rst_lifetime = 5 ;
  154 static u_int32_t dyn_short_lifetime = 30 ;
  155 static u_int32_t dyn_count = 0 ;
  156 static u_int32_t dyn_max = 1000 ;
  157 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
  158     &dyn_buckets, 0, "Number of dyn. buckets");
  159 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
  160     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
  161 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
  162     &dyn_count, 0, "Number of dyn. rules");
  163 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
  164     &dyn_max, 0, "Max number of dyn. rules");
  165 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
  166     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
  167 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
  168     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
  169 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
  170     &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
  171 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
  172     &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
  173 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
  174     &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for other situations");
  175 #endif /* STATEFUL */
  176 
  177 #endif
  178 
  179 #define dprintf(a)      if (!fw_debug); else printf a
  180 
  181 #define print_ip(a)     printf("%d.%d.%d.%d",                           \
  182                             (int)(ntohl(a.s_addr) >> 24) & 0xFF,        \
  183                             (int)(ntohl(a.s_addr) >> 16) & 0xFF,        \
  184                             (int)(ntohl(a.s_addr) >> 8) & 0xFF,         \
  185                             (int)(ntohl(a.s_addr)) & 0xFF);
  186 
  187 #define dprint_ip(a)    if (!fw_debug); else print_ip(a)
  188 
  189 static int      add_entry __P((struct ip_fw_head *chainptr, struct ip_fw *frwl));
  190 static int      del_entry __P((struct ip_fw_head *chainptr, u_short number));
  191 static int      zero_entry __P((struct ip_fw *));
  192 static int      resetlog_entry __P((struct ip_fw *));
  193 static int      check_ipfw_struct __P((struct ip_fw *m));
  194 static __inline int
  195                 iface_match __P((struct ifnet *ifp, union ip_fw_if *ifu,
  196                                  int byname));
  197 static int      ipopts_match __P((struct ip *ip, struct ip_fw *f));
  198 static __inline int
  199                 port_match __P((u_short *portptr, int nports, u_short port,
  200                                 int range_flag, int mask));
  201 static int      tcpflg_match __P((struct tcphdr *tcp, struct ip_fw *f));
  202 static int      icmptype_match __P((struct icmp *  icmp, struct ip_fw * f));
  203 static void     ipfw_report __P((struct ip_fw *f, struct ip *ip,
  204                                 struct ifnet *rif, struct ifnet *oif));
  205 
  206 static void flush_rule_ptrs(void);
  207 
  208 static int      ip_fw_chk __P((struct ip **pip, int hlen,
  209                         struct ifnet *oif, u_int16_t *cookie, struct mbuf **m,
  210                         struct ip_fw_chain **flow_id,
  211                         struct sockaddr_in **next_hop));
  212 static int      ip_fw_ctl __P((struct sockopt *sopt));
  213 
  214 static char err_prefix[] = "ip_fw_ctl:";
  215 
  216 /*
  217  * Returns 1 if the port is matched by the vector, 0 otherwise
  218  */
  219 static __inline int 
  220 port_match(u_short *portptr, int nports, u_short port, int range_flag, int mask)
  221 {
  222         if (!nports)
  223                 return 1;
  224         if (mask) {
  225                 if ( 0 == ((portptr[0] ^ port) & portptr[1]) )
  226                         return 1;
  227                 nports -= 2;
  228                 portptr += 2;
  229         }
  230         if (range_flag) {
  231                 if (portptr[0] <= port && port <= portptr[1]) {
  232                         return 1;
  233                 }
  234                 nports -= 2;
  235                 portptr += 2;
  236         }
  237         while (nports-- > 0) {
  238                 if (*portptr++ == port) {
  239                         return 1;
  240                 }
  241         }
  242         return 0;
  243 }
  244 
  245 static int
  246 tcpflg_match(struct tcphdr *tcp, struct ip_fw *f)
  247 {
  248         u_char          flg_set, flg_clr;
  249 
  250         /*
  251          * If an established connection is required, reject packets that
  252          * have only SYN of RST|ACK|SYN set.  Otherwise, fall through to
  253          * other flag requirements.
  254          */
  255         if ((f->fw_ipflg & IP_FW_IF_TCPEST) &&
  256             ((tcp->th_flags & (IP_FW_TCPF_RST | IP_FW_TCPF_ACK |
  257             IP_FW_TCPF_SYN)) == IP_FW_TCPF_SYN))
  258                 return 0;
  259 
  260         flg_set = tcp->th_flags & f->fw_tcpf;
  261         flg_clr = tcp->th_flags & f->fw_tcpnf;
  262 
  263         if (flg_set != f->fw_tcpf)
  264                 return 0;
  265         if (flg_clr)
  266                 return 0;
  267 
  268         return 1;
  269 }
  270 
  271 static int
  272 icmptype_match(struct icmp *icmp, struct ip_fw *f)
  273 {
  274         int type;
  275 
  276         if (!(f->fw_flg & IP_FW_F_ICMPBIT))
  277                 return(1);
  278 
  279         type = icmp->icmp_type;
  280 
  281         /* check for matching type in the bitmap */
  282         if (type < IP_FW_ICMPTYPES_MAX &&
  283                 (f->fw_uar.fw_icmptypes[type / (sizeof(unsigned) * 8)] & 
  284                 (1U << (type % (8 * sizeof(unsigned))))))
  285                 return(1);
  286 
  287         return(0); /* no match */
  288 }
  289 
  290 static int
  291 is_icmp_query(struct ip *ip)
  292 {
  293         const struct icmp *icmp;
  294         int icmp_type;
  295 
  296         icmp = (struct icmp *)((u_int32_t *)ip + ip->ip_hl);
  297         icmp_type = icmp->icmp_type;
  298 
  299         if (icmp_type == ICMP_ECHO || icmp_type == ICMP_ROUTERSOLICIT ||
  300             icmp_type == ICMP_TSTAMP || icmp_type == ICMP_IREQ ||
  301             icmp_type == ICMP_MASKREQ)
  302                 return(1);
  303 
  304         return(0);
  305 }
  306 
  307 static int
  308 ipopts_match(struct ip *ip, struct ip_fw *f)
  309 {
  310         register u_char *cp;
  311         int opt, optlen, cnt;
  312         u_char  opts, nopts, nopts_sve;
  313 
  314         cp = (u_char *)(ip + 1);
  315         cnt = (ip->ip_hl << 2) - sizeof (struct ip);
  316         opts = f->fw_ipopt;
  317         nopts = nopts_sve = f->fw_ipnopt;
  318 
  319         for (; cnt > 0; cnt -= optlen, cp += optlen) {
  320                 opt = cp[IPOPT_OPTVAL];
  321                 if (opt == IPOPT_EOL)
  322                         break;
  323                 if (opt == IPOPT_NOP)
  324                         optlen = 1;
  325                 else {
  326                         optlen = cp[IPOPT_OLEN];
  327                         if (optlen <= 0 || optlen > cnt) {
  328                                 return 0; /*XXX*/
  329                         }
  330                 }
  331                 switch (opt) {
  332 
  333                 default:
  334                         break;
  335 
  336                 case IPOPT_LSRR:
  337                         opts &= ~IP_FW_IPOPT_LSRR;
  338                         nopts &= ~IP_FW_IPOPT_LSRR;
  339                         break;
  340 
  341                 case IPOPT_SSRR:
  342                         opts &= ~IP_FW_IPOPT_SSRR;
  343                         nopts &= ~IP_FW_IPOPT_SSRR;
  344                         break;
  345 
  346                 case IPOPT_RR:
  347                         opts &= ~IP_FW_IPOPT_RR;
  348                         nopts &= ~IP_FW_IPOPT_RR;
  349                         break;
  350                 case IPOPT_TS:
  351                         opts &= ~IP_FW_IPOPT_TS;
  352                         nopts &= ~IP_FW_IPOPT_TS;
  353                         break;
  354                 }
  355                 if (opts == nopts)
  356                         break;
  357         }
  358         if (opts == 0 && nopts == nopts_sve)
  359                 return 1;
  360         else
  361                 return 0;
  362 }
  363 
  364 static __inline int
  365 iface_match(struct ifnet *ifp, union ip_fw_if *ifu, int byname)
  366 {
  367         /* Check by name or by IP address */
  368         if (byname) {
  369                 /* Check unit number (-1 is wildcard) */
  370                 if (ifu->fu_via_if.unit != -1
  371                     && ifp->if_unit != ifu->fu_via_if.unit)
  372                         return(0);
  373                 /* Check name */
  374                 if (strncmp(ifp->if_name, ifu->fu_via_if.name, FW_IFNLEN))
  375                         return(0);
  376                 return(1);
  377         } else if (ifu->fu_via_ip.s_addr != 0) {        /* Zero == wildcard */
  378                 struct ifaddr *ia;
  379 
  380                 for (ia = ifp->if_addrhead.tqh_first;
  381                     ia != NULL; ia = ia->ifa_link.tqe_next) {
  382                         if (ia->ifa_addr == NULL)
  383                                 continue;
  384                         if (ia->ifa_addr->sa_family != AF_INET)
  385                                 continue;
  386                         if (ifu->fu_via_ip.s_addr != ((struct sockaddr_in *)
  387                             (ia->ifa_addr))->sin_addr.s_addr)
  388                                 continue;
  389                         return(1);
  390                 }
  391                 return(0);
  392         }
  393         return(1);
  394 }
  395 
  396 static void
  397 ipfw_report(struct ip_fw *f, struct ip *ip,
  398         struct ifnet *rif, struct ifnet *oif)
  399 {
  400     if (ip) {
  401         struct tcphdr *const tcp = (struct tcphdr *) ((u_int32_t *) ip+ ip->ip_hl);
  402         struct udphdr *const udp = (struct udphdr *) ((u_int32_t *) ip+ ip->ip_hl);
  403         struct icmp *const icmp = (struct icmp *) ((u_int32_t *) ip + ip->ip_hl);
  404         u_int64_t count;
  405 
  406         count = f ? f->fw_pcnt : ++counter;
  407         if ((f == NULL && fw_verbose_limit != 0 && count > fw_verbose_limit) ||
  408             (f && f->fw_logamount != 0 && count > f->fw_loghighest))
  409                 return;
  410 
  411         /* Print command name */
  412         printf("ipfw: %d ", f ? f->fw_number : -1);
  413         if (!f)
  414                 printf("Refuse");
  415         else
  416                 switch (f->fw_flg & IP_FW_F_COMMAND) {
  417                 case IP_FW_F_DENY:
  418                         printf("Deny");
  419                         break;
  420                 case IP_FW_F_REJECT:
  421                         if (f->fw_reject_code == IP_FW_REJECT_RST)
  422                                 printf("Reset");
  423                         else
  424                                 printf("Unreach");
  425                         break;
  426                 case IP_FW_F_ACCEPT:
  427                         printf("Accept");
  428                         break;
  429                 case IP_FW_F_COUNT:
  430                         printf("Count");
  431                         break;
  432 #ifdef IPDIVERT
  433                 case IP_FW_F_DIVERT:
  434                         printf("Divert %d", f->fw_divert_port);
  435                         break;
  436                 case IP_FW_F_TEE:
  437                         printf("Tee %d", f->fw_divert_port);
  438                         break;
  439 #endif
  440                 case IP_FW_F_SKIPTO:
  441                         printf("SkipTo %d", f->fw_skipto_rule);
  442                         break;
  443 #ifdef DUMMYNET
  444                 case IP_FW_F_PIPE:
  445                         printf("Pipe %d", f->fw_skipto_rule);
  446                         break;
  447 #endif
  448 #ifdef IPFIREWALL_FORWARD
  449                 case IP_FW_F_FWD:
  450                         printf("Forward to ");
  451                         print_ip(f->fw_fwd_ip.sin_addr);
  452                         if (f->fw_fwd_ip.sin_port)
  453                                 printf(":%d", f->fw_fwd_ip.sin_port);
  454                         break;
  455 #endif
  456                 default:        
  457                         printf("UNKNOWN");
  458                         break;
  459                 }
  460         printf(" ");
  461 
  462         switch (ip->ip_p) {
  463         case IPPROTO_TCP:
  464                 printf("TCP ");
  465                 print_ip(ip->ip_src);
  466                 if ((ip->ip_off & IP_OFFMASK) == 0)
  467                         printf(":%d ", ntohs(tcp->th_sport));
  468                 else
  469                         printf(" ");
  470                 print_ip(ip->ip_dst);
  471                 if ((ip->ip_off & IP_OFFMASK) == 0)
  472                         printf(":%d", ntohs(tcp->th_dport));
  473                 break;
  474         case IPPROTO_UDP:
  475                 printf("UDP ");
  476                 print_ip(ip->ip_src);
  477                 if ((ip->ip_off & IP_OFFMASK) == 0)
  478                         printf(":%d ", ntohs(udp->uh_sport));
  479                 else
  480                         printf(" ");
  481                 print_ip(ip->ip_dst);
  482                 if ((ip->ip_off & IP_OFFMASK) == 0)
  483                         printf(":%d", ntohs(udp->uh_dport));
  484                 break;
  485         case IPPROTO_ICMP:
  486                 if ((ip->ip_off & IP_OFFMASK) == 0)
  487                         printf("ICMP:%u.%u ", icmp->icmp_type, icmp->icmp_code);
  488                 else
  489                         printf("ICMP ");
  490                 print_ip(ip->ip_src);
  491                 printf(" ");
  492                 print_ip(ip->ip_dst);
  493                 break;
  494         default:
  495                 printf("P:%d ", ip->ip_p);
  496                 print_ip(ip->ip_src);
  497                 printf(" ");
  498                 print_ip(ip->ip_dst);
  499                 break;
  500         }
  501         if (oif)
  502                 printf(" out via %s%d", oif->if_name, oif->if_unit);
  503         else if (rif)
  504                 printf(" in via %s%d", rif->if_name, rif->if_unit);
  505         if ((ip->ip_off & IP_OFFMASK)) 
  506                 printf(" Fragment = %d",ip->ip_off & IP_OFFMASK);
  507         printf("\n");
  508         if ((f ? f->fw_logamount != 0 : 1) &&
  509             count == (f ? f->fw_loghighest : fw_verbose_limit))
  510                 printf("ipfw: limit %d reached on rule #%d\n",
  511                     f ? f->fw_logamount : fw_verbose_limit,
  512                     f ? f->fw_number : -1);
  513     }
  514 }
  515 
  516 #if STATEFUL
  517 static __inline int
  518 hash_packet(struct ipfw_flow_id *id)
  519 {
  520     u_int32_t i ;
  521 
  522     i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
  523     i &= (curr_dyn_buckets - 1) ;
  524     return i ;
  525 }
  526 
  527 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
  528 /*
  529  * Remove all dynamic rules pointing to a given chain, or all
  530  * rules if chain == NULL. Second parameter is 1 if we want to
  531  * delete unconditionally, otherwise only expired rules are removed.
  532  */
  533 static void
  534 remove_dyn_rule(struct ip_fw_chain *chain, int force)
  535 {
  536     struct ipfw_dyn_rule *prev, *q, *old_q ;
  537     int i ;
  538     static u_int32_t last_remove = 0 ;
  539 
  540     if (ipfw_dyn_v == NULL || dyn_count == 0)
  541         return ;
  542     /* do not expire more than once per second, it is useless */
  543     if (force == 0 && last_remove == time_second)
  544         return ;
  545     last_remove = time_second ;
  546 
  547     for (i = 0 ; i < curr_dyn_buckets ; i++) {
  548         for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
  549             if ( (chain == NULL || chain == q->chain) &&
  550                 (force || TIME_LEQ( q->expire , time_second ) ) ) {
  551                 DEB(printf("-- remove entry 0x%08x %d -> 0x%08x %d, %d left\n",
  552                     (q->id.src_ip), (q->id.src_port),
  553                     (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )
  554                 old_q = q ;
  555                 if (prev != NULL)
  556                     prev->next = q = q->next ;
  557                 else
  558                     ipfw_dyn_v[i] = q = q->next ;
  559                 dyn_count-- ;
  560                 free(old_q, M_IPFW);
  561                 continue ;
  562             } else {
  563                 prev = q ;
  564                 q = q->next ;
  565             }
  566         }
  567     }
  568 }
  569 
  570 static struct ipfw_dyn_rule *
  571 lookup_dyn_rule(struct ipfw_flow_id *pkt)
  572 {
  573     /*
  574      * stateful ipfw extensions.
  575      * Lookup into dynamic session queue
  576      */
  577     struct ipfw_dyn_rule *prev, *q, *old_q ;
  578     int i, dir = 0;
  579 #define MATCH_FORWARD 1
  580 
  581     if (ipfw_dyn_v == NULL)
  582         return NULL ;
  583     i = hash_packet( pkt );
  584     for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
  585         switch (q->type) {
  586         default:        /* bidirectional rule, no masks */
  587             if ( pkt->proto == q->id.proto) {
  588                 if (pkt->src_ip == q->id.src_ip &&
  589                         pkt->dst_ip == q->id.dst_ip &&
  590                         pkt->src_port == q->id.src_port &&
  591                         pkt->dst_port == q->id.dst_port ) {
  592                     dir = MATCH_FORWARD ;
  593                     goto found ;
  594                 }
  595                 if (pkt->src_ip == q->id.dst_ip &&
  596                         pkt->dst_ip == q->id.src_ip &&
  597                         pkt->src_port == q->id.dst_port &&
  598                         pkt->dst_port == q->id.src_port ) {
  599                     dir = 0 ;
  600                     goto found ;
  601                 }
  602             }
  603             break ;
  604         }
  605         if (TIME_LEQ( q->expire , time_second ) ) {
  606             /* expire entry */
  607             old_q = q ;
  608             if (prev != NULL)
  609                 prev->next = q = q->next ;
  610             else
  611                 ipfw_dyn_v[i] = q = q->next ;
  612             dyn_count-- ;
  613             free(old_q, M_IPFW);
  614             continue ;
  615         } else {
  616             prev = q ;
  617             q = q->next ;
  618         }
  619     }
  620     return NULL ; /* clearly not found */
  621 found:
  622     if (q != NULL) { /* redundant check! */
  623         if ( prev != NULL) { /* found and not in front */
  624             prev->next = q->next ;
  625             q->next = ipfw_dyn_v[i] ;
  626             ipfw_dyn_v[i] = q ;
  627         }
  628         if (pkt->proto == IPPROTO_TCP) {
  629             /* update state according to flags */
  630             u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
  631             q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
  632             switch (q->state) {
  633             case TH_SYN :
  634                 /* opening */
  635                 q->expire = time_second + dyn_syn_lifetime ;
  636                 break ;
  637             case TH_SYN | (TH_SYN << 8) :
  638                 /* move to established */
  639                 q->expire = time_second + dyn_ack_lifetime ;
  640                 break ;
  641             case TH_SYN | (TH_SYN << 8) | TH_FIN :
  642             case TH_SYN | (TH_SYN << 8) | (TH_FIN << 8) :
  643                 /* one side tries to close */
  644                 q->expire = time_second + dyn_fin_lifetime ;
  645                 break ;
  646             case TH_SYN | (TH_SYN << 8) | TH_FIN | (TH_FIN << 8) :
  647                 /* both sides closed */
  648                 q->expire = time_second + dyn_fin_lifetime ;
  649                 break ;
  650             default:
  651 #if 0
  652                 /* reset or some invalid combination, but can also
  653                  * occur if we use keep-state the wrong way.
  654                  */
  655                 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
  656                     printf("invalid state: 0x%x\n", q->state);
  657 #endif
  658                 q->expire = time_second + dyn_rst_lifetime ;
  659                 break ;
  660             }
  661         } else {
  662             /* should do something for UDP and others... */
  663             q->expire = time_second + dyn_short_lifetime ;
  664         }
  665     }
  666     return q ;
  667 }
  668 
  669 /*
  670  * Install state for a dynamic session.
  671  */
  672 
  673 static void
  674 add_dyn_rule(struct ipfw_flow_id *id, struct ipfw_flow_id *mask,
  675         struct ip_fw_chain *chain)
  676 {
  677     struct ipfw_dyn_rule *r ;
  678 
  679     int i ;
  680     if (ipfw_dyn_v == NULL ||
  681         (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
  682         /* try reallocation, make sure we have a power of 2 */
  683         u_int32_t i = dyn_buckets ;
  684         while ( i > 0 && (i & 1) == 0 )
  685             i >>= 1 ;
  686         if (i != 1) /* not a power of 2 */
  687             dyn_buckets = curr_dyn_buckets ; /* reset */
  688         else {
  689             if (ipfw_dyn_v != NULL)
  690                 free(ipfw_dyn_v, M_IPFW);
  691             ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof r,
  692                     M_IPFW, M_DONTWAIT);
  693             if (ipfw_dyn_v == NULL)
  694                 return ; /* failed ! */
  695             bzero(ipfw_dyn_v, curr_dyn_buckets * sizeof r);
  696         }
  697     }
  698     i = hash_packet(id);
  699 
  700     r = malloc(sizeof *r, M_IPFW, M_DONTWAIT);
  701     if (r == NULL) {
  702         printf ("sorry cannot allocate state\n");
  703         return ;
  704     }
  705     bzero (r, sizeof (*r) );
  706 
  707     if (mask)
  708         r->mask = *mask ;
  709     r->id = *id ;
  710     r->expire = time_second + dyn_syn_lifetime ;
  711     r->chain = chain ;
  712     r->type = ((struct ip_fw_ext *)chain->rule)->dyn_type ;
  713 
  714     r->bucket = i ;
  715     r->next = ipfw_dyn_v[i] ;
  716     ipfw_dyn_v[i] = r ;
  717     dyn_count++ ;
  718     DEB(printf("-- add entry 0x%08x %d -> 0x%08x %d, %d left\n",
  719         (r->id.src_ip), (r->id.src_port),
  720         (r->id.dst_ip), (r->id.dst_port),
  721         dyn_count ); )
  722 }
  723 
  724 /*
  725  * Install dynamic state.
  726  * There are different types of dynamic rules which can be installed.
  727  * The type is in chain->dyn_type.
  728  * Type 0 (default) is a bidirectional rule
  729  */
  730 static void
  731 install_state(struct ip_fw_chain *chain, struct ip **pip, struct ip *ip)
  732 {
  733     struct ipfw_dyn_rule *q ;
  734     static int last_log ;
  735 
  736     u_long type = ((struct ip_fw_ext *)chain->rule)->dyn_type ;
  737 
  738     DEB(printf("-- install state type %d 0x%08lx %u -> 0x%08lx %u\n",
  739         type,
  740         (last_pkt.src_ip), (last_pkt.src_port),
  741         (last_pkt.dst_ip), (last_pkt.dst_port) );)
  742 
  743     q = lookup_dyn_rule(&last_pkt) ;
  744     if (q != NULL) {
  745         if (last_log == time_second)
  746             return ;
  747         last_log = time_second ;
  748         printf(" entry already present, done\n");
  749         return ;
  750     }
  751     if (dyn_count >= dyn_max) /* try remove old ones... */
  752         remove_dyn_rule(NULL, 0 /* expire */);
  753     if (dyn_count >= dyn_max) {
  754         if (last_log == time_second)
  755             return ;
  756         last_log = time_second ;
  757         printf(" Too many dynamic rules, sorry\n");
  758         return ;
  759     }
  760     switch (type) {
  761     default: /* bidir rule */
  762         add_dyn_rule(&last_pkt, NULL, chain);
  763         break ;
  764     }
  765     q = lookup_dyn_rule(&last_pkt) ; /* XXX this just sets the lifetime ... */
  766 }
  767 #endif /* STATEFUL */
  768 
  769 /*
  770  * given an ip_fw_chain *, lookup_next_rule will return a pointer
  771  * of the same type to the next one. This can be either the jump
  772  * target (for skipto instructions) or the next one in the chain (in
  773  * all other cases including a missing jump target).
  774  * Backward jumps are not allowed, so start looking from the next
  775  * rule...
  776  */ 
  777 static struct ip_fw_chain * lookup_next_rule(struct ip_fw_chain *me);
  778 
  779 static struct ip_fw_chain *
  780 lookup_next_rule(struct ip_fw_chain *me)
  781 {
  782     struct ip_fw_chain *chain ;
  783     int rule = me->rule->fw_skipto_rule ; /* guess... */
  784 
  785     if ( (me->rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_SKIPTO )
  786         for (chain = me->chain.le_next; chain ; chain = chain->chain.le_next )
  787             if (chain->rule->fw_number >= rule)
  788                 return chain ;
  789     return me->chain.le_next ; /* failure or not a skipto */
  790 }
  791 
  792 /*
  793  * Parameters:
  794  *
  795  *      pip     Pointer to packet header (struct ip **)
  796  *      bridge_ipfw extension: pip = NULL means a complete ethernet packet
  797  *      including ethernet header in the mbuf. Other fields
  798  *      are ignored/invalid.
  799  *
  800  *      hlen    Packet header length
  801  *      oif     Outgoing interface, or NULL if packet is incoming
  802  *      *cookie Skip up to the first rule past this rule number;
  803  *              upon return, non-zero port number for divert or tee
  804  *      *m      The packet; we set to NULL when/if we nuke it.
  805  *      *flow_id pointer to the last matching rule (in/out)
  806  *      *next_hop socket we are forwarding to (in/out).
  807  *
  808  * Return value:
  809  *
  810  *      0       The packet is to be accepted and routed normally OR
  811  *              the packet was denied/rejected and has been dropped;
  812  *              in the latter case, *m is equal to NULL upon return.
  813  *      port    Divert the packet to port, with these caveats:
  814  *
  815  *              - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
  816  *                of diverting it (ie, 'ipfw tee').
  817  *
  818  *              - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
  819  *                16 bits as a dummynet pipe number instead of diverting
  820  */
  821 
  822 static int 
  823 ip_fw_chk(struct ip **pip, int hlen,
  824         struct ifnet *oif, u_int16_t *cookie, struct mbuf **m,
  825         struct ip_fw_chain **flow_id,
  826         struct sockaddr_in **next_hop)
  827 {
  828         struct ip_fw_chain *chain;
  829         struct ip_fw *f = NULL, *rule = NULL;
  830         struct ip *ip = NULL ;
  831         struct ifnet *const rif = (*m)->m_pkthdr.rcvif;
  832         u_short offset = 0 ;
  833         u_short src_port = 0, dst_port = 0;
  834         struct in_addr src_ip, dst_ip; /* XXX */
  835         u_int8_t proto= 0, flags = 0 ; /* XXX */
  836         u_int16_t skipto ;
  837 
  838 #if STATEFUL
  839         int dyn_checked = 0 ; /* set after dyn.rules have been checked. */
  840         struct ipfw_dyn_rule *q = NULL ;
  841 #endif
  842         /* Grab and reset cookie */
  843         skipto = *cookie;
  844         *cookie = 0;
  845 
  846 /*
  847  * here, pip==NULL for bridged pkts -- they include the ethernet
  848  * header so i have to adjust lengths accordingly
  849  */
  850 #define PULLUP_TO(l)    do {                                            \
  851                             int len = (pip ? (l) : (l) + 14 ) ;         \
  852                             if ((*m)->m_len < (len) ) {                 \
  853                                 if ( (*m = m_pullup(*m, (len))) == 0)   \
  854                                     goto bogusfrag;                     \
  855                                 ip = mtod(*m, struct ip *);             \
  856                                 if (pip)                                \
  857                                     *pip = ip ;                         \
  858                                 else                                    \
  859                                     ip = (struct ip *)((char *)ip + 14);\
  860                                 offset = (ip->ip_off & IP_OFFMASK);     \
  861                             }                                           \
  862                         } while (0)
  863 
  864         if (pip) { /* normal ip packet */
  865             ip = *pip;
  866             offset = (ip->ip_off & IP_OFFMASK);
  867         } else { /* bridged or non-ip packet */
  868             struct ether_header *eh = mtod(*m, struct ether_header *);
  869             switch (ntohs(eh->ether_type)) {
  870             case ETHERTYPE_IP :
  871                 if ((*m)->m_len<sizeof(struct ether_header) + sizeof(struct ip))
  872                     goto non_ip ;
  873                 ip = (struct ip *)(eh + 1 );
  874                 if (ip->ip_v != IPVERSION)
  875                     goto non_ip ;
  876                 hlen = ip->ip_hl << 2;
  877                 if (hlen < sizeof(struct ip)) /* minimum header length */
  878                     goto non_ip ;
  879                 if ((*m)->m_len < 14 + hlen + 14) {
  880                     printf("-- m_len %d, need more...\n", (*m)->m_len);
  881                     goto non_ip ;
  882                 }
  883                 offset = (ip->ip_off & IP_OFFMASK);
  884                 break ;
  885             default :
  886 non_ip:         ip = NULL ;
  887                 break ;
  888             }
  889         }
  890 
  891         /*
  892          * collect parameters into local variables for faster matching.
  893          */
  894         if (ip) {
  895             struct tcphdr *tcp;
  896             struct udphdr *udp;
  897 
  898             dst_ip = ip->ip_dst ;
  899             src_ip = ip->ip_src ;
  900             proto = ip->ip_p ;
  901             /*
  902              * warning - if offset != 0, port values are bogus.
  903              * Not a problem for ipfw, but could be for dummynet.
  904              */
  905             switch (proto) {
  906             case IPPROTO_TCP :
  907                 PULLUP_TO(hlen + 14);
  908                 tcp =(struct tcphdr *)((u_int32_t *)ip + ip->ip_hl);
  909                 dst_port = tcp->th_dport ;
  910                 src_port = tcp->th_sport ;
  911                 flags = tcp->th_flags ;
  912                 break ;
  913 
  914             case IPPROTO_UDP :
  915                 PULLUP_TO(hlen + 4);
  916                 udp =(struct udphdr *)((u_int32_t *)ip + ip->ip_hl);
  917                 dst_port = udp->uh_dport ;
  918                 src_port = udp->uh_sport ;
  919                 break ;
  920 
  921             case IPPROTO_ICMP:
  922                 PULLUP_TO(hlen + 2);
  923                 flags = ((struct icmp *)
  924                          ((u_int32_t *)ip + ip->ip_hl))->icmp_type ;
  925                 break ;
  926 
  927             default :
  928                 src_port = dst_port = 0 ;
  929             }
  930 #undef PULLUP_TO
  931             last_pkt.src_ip = ntohl(src_ip.s_addr) ;
  932             last_pkt.dst_ip = ntohl(dst_ip.s_addr) ;
  933             last_pkt.proto = proto ;
  934             last_pkt.src_port = ntohs(src_port) ;
  935             last_pkt.dst_port = ntohs(dst_port) ;
  936             last_pkt.flags = flags ;
  937         }
  938 
  939         if (*flow_id) {
  940             /* Accept if passed first test */
  941             if (fw_one_pass)
  942                 return 0 ;
  943             /*
  944              * Packet has already been tagged. Look for the next rule
  945              * to restart processing.
  946              */
  947             chain = LIST_NEXT( *flow_id, chain);
  948 
  949             if ( (chain = (*flow_id)->rule->next_rule_ptr) == NULL )
  950                 chain = (*flow_id)->rule->next_rule_ptr =
  951                         lookup_next_rule(*flow_id) ;
  952             if (chain == NULL)
  953                 goto dropit;
  954         } else {
  955             /*
  956              * Go down the chain, looking for enlightment.
  957              * If we've been asked to start at a given rule, do so.
  958              */
  959             chain = LIST_FIRST(&ip_fw_chain);
  960             if ( skipto != 0 ) {
  961                 if (skipto >= IPFW_DEFAULT_RULE)
  962                         goto dropit;
  963                 while (chain && chain->rule->fw_number <= skipto)
  964                     chain = LIST_NEXT(chain, chain);
  965                 if ( chain == NULL )
  966                     goto dropit;
  967             }
  968         }
  969 
  970 
  971         for (; chain; chain = LIST_NEXT(chain, chain)) {
  972 again:
  973                 f = chain->rule;
  974                 if (f->fw_number == IPFW_DEFAULT_RULE)
  975                     goto got_match ;
  976 
  977 #if STATEFUL
  978                 /*
  979                  * dynamic rules are checked at the first keep-state or
  980                  * check-state occurrence.
  981                  */
  982                 if (f->fw_flg & (IP_FW_F_KEEP_S|IP_FW_F_CHECK_S) &&
  983                         dyn_checked == 0 ) {
  984                     dyn_checked = 1 ;
  985                     if (ip)
  986                         q = lookup_dyn_rule(&last_pkt);
  987                     if (q != NULL) {
  988                         DEB(printf("-- dynamic match 0x%08x %d -> 0x%08x %d\n",
  989                             (q->id.src_ip), (q->id.src_port),
  990                             (q->id.dst_ip), (q->id.dst_port) ); )
  991                         chain = q->chain ;
  992                         q->pcnt++ ;
  993                         if (ip)
  994                             q->bcnt += ip->ip_len;
  995                         goto got_match ; /* random not allowed here */
  996                     }
  997                     /* if this was a check-only rule, continue with next */
  998                     if (f->fw_flg & IP_FW_F_CHECK_S)
  999                         continue ;
 1000                 }
 1001 #endif  /* stateful ipfw */
 1002                 /*
 1003                  * Rule only valid for bridged packets, skip if this
 1004                  * is not one of those (pip != NULL)
 1005                  */
 1006                 if (pip != NULL && f->fw_flg & IP_FW_BRIDGED )
 1007                         continue ;
 1008 
 1009                 if (oif) {
 1010                         /* Check direction outbound */
 1011                         if (!(f->fw_flg & IP_FW_F_OUT))
 1012                                 continue;
 1013                 } else {
 1014                         /* Check direction inbound */
 1015                         if (!(f->fw_flg & IP_FW_F_IN))
 1016                                 continue;
 1017                 }
 1018                 if (ip == NULL ) {
 1019                     /*
 1020                      * do relevant checks for non-ip packets:
 1021                      * after this, only goto got_match or continue
 1022                      */
 1023                     struct ether_header *eh = mtod(*m, struct ether_header *);
 1024                     /*
 1025                      * temporary hack: 
 1026                      *   udp from 0.0.0.0 means this rule applies.
 1027                      *   1 src port is match ether type
 1028                      *   2 src ports (interval) is match ether type
 1029                      *   3 src ports is match ether address
 1030                      */
 1031                     if ( f->fw_src.s_addr != 0 || f->fw_prot != IPPROTO_UDP
 1032                         || f->fw_smsk.s_addr != 0xffffffff )
 1033                         continue;
 1034                     switch (IP_FW_GETNSRCP(f)) {
 1035                     case 1: /* match one type */
 1036                         if (  /* ( (f->fw_flg & IP_FW_F_INVSRC) != 0) ^ */
 1037                                 ( f->fw_uar.fw_pts[0] == ntohs(eh->ether_type) )  ) {
 1038                             goto got_match ;
 1039                         }
 1040                         break ;
 1041                     default:
 1042                         break ;
 1043                     }
 1044                     continue ;
 1045                 }
 1046 
 1047                 /* Fragments */
 1048                 if ((f->fw_flg & IP_FW_F_FRAG) && offset == 0 )
 1049                         continue;
 1050 
 1051                 /* If src-addr doesn't match, not this rule. */
 1052                 if (((f->fw_flg & IP_FW_F_INVSRC) != 0) ^ ((src_ip.s_addr
 1053                     & f->fw_smsk.s_addr) != f->fw_src.s_addr))
 1054                         continue;
 1055 
 1056                 /* If dest-addr doesn't match, not this rule. */
 1057                 if (((f->fw_flg & IP_FW_F_INVDST) != 0) ^ ((dst_ip.s_addr
 1058                     & f->fw_dmsk.s_addr) != f->fw_dst.s_addr))
 1059                         continue;
 1060 
 1061                 /* Interface check */
 1062                 if ((f->fw_flg & IF_FW_F_VIAHACK) == IF_FW_F_VIAHACK) {
 1063                         struct ifnet *const iface = oif ? oif : rif;
 1064 
 1065                         /* Backwards compatibility hack for "via" */
 1066                         if (!iface || !iface_match(iface,
 1067                             &f->fw_in_if, f->fw_flg & IP_FW_F_OIFNAME))
 1068                                 continue;
 1069                 } else {
 1070                         /* Check receive interface */
 1071                         if ((f->fw_flg & IP_FW_F_IIFACE)
 1072                             && (!rif || !iface_match(rif,
 1073                               &f->fw_in_if, f->fw_flg & IP_FW_F_IIFNAME)))
 1074                                 continue;
 1075                         /* Check outgoing interface */
 1076                         if ((f->fw_flg & IP_FW_F_OIFACE)
 1077                             && (!oif || !iface_match(oif,
 1078                               &f->fw_out_if, f->fw_flg & IP_FW_F_OIFNAME)))
 1079                                 continue;
 1080                 }
 1081 
 1082                 /* Check IP options */
 1083                 if (f->fw_ipopt != f->fw_ipnopt && !ipopts_match(ip, f))
 1084                         continue;
 1085 
 1086                 /* Check protocol; if wildcard, and no [ug]id, match */
 1087                 if (f->fw_prot == IPPROTO_IP) {
 1088                         if (!(f->fw_flg & (IP_FW_F_UID|IP_FW_F_GID)))
 1089                                 goto rnd_then_got_match;
 1090                 } else
 1091                         /* If different, don't match */
 1092                         if (proto != f->fw_prot) 
 1093                                 continue;
 1094 
 1095                 /* Protocol specific checks for uid only */
 1096                 if (f->fw_flg & (IP_FW_F_UID|IP_FW_F_GID)) {
 1097                     switch (proto) {
 1098                     case IPPROTO_TCP:
 1099                         {
 1100                             struct inpcb *P;
 1101 
 1102                             if (offset == 1)    /* cf. RFC 1858 */
 1103                                     goto bogusfrag;
 1104                             if (offset != 0)
 1105                                     continue;
 1106 
 1107                             if (oif)
 1108                                 P = in_pcblookup_hash(&tcbinfo, dst_ip,
 1109                                    dst_port, src_ip, src_port, 0);
 1110                             else
 1111                                 P = in_pcblookup_hash(&tcbinfo, src_ip,
 1112                                    src_port, dst_ip, dst_port, 0);
 1113 
 1114                             if (P && P->inp_socket && P->inp_socket->so_cred) {
 1115                                 if (f->fw_flg & IP_FW_F_UID) {
 1116                                         if (P->inp_socket->so_cred->p_ruid !=
 1117                                             f->fw_uid)
 1118                                                 continue;
 1119                                 } else if (!groupmember(f->fw_gid,
 1120                                             P->inp_socket->so_cred->pc_ucred))
 1121                                                 continue;
 1122                             } else continue;
 1123 
 1124                             break;
 1125                         }
 1126 
 1127                     case IPPROTO_UDP:
 1128                         {
 1129                             struct inpcb *P;
 1130 
 1131                             if (offset != 0)
 1132                                 continue;
 1133 
 1134                             if (oif)
 1135                                 P = in_pcblookup_hash(&udbinfo, dst_ip,
 1136                                    dst_port, src_ip, src_port, 1);
 1137                             else
 1138                                 P = in_pcblookup_hash(&udbinfo, src_ip,
 1139                                    src_port, dst_ip, dst_port, 1);
 1140 
 1141                             if (P && P->inp_socket && P->inp_socket->so_cred) {
 1142                                 if (f->fw_flg & IP_FW_F_UID) {
 1143                                         if (P->inp_socket->so_cred->p_ruid !=
 1144                                             f->fw_uid)
 1145                                                 continue;
 1146                                 } else if (!groupmember(f->fw_gid,
 1147                                             P->inp_socket->so_cred->pc_ucred))
 1148                                                 continue;
 1149                             } else continue;
 1150 
 1151                             break;
 1152                         }
 1153 
 1154                         default:
 1155                                 continue;
 1156                         }
 1157                 }
 1158                     
 1159                 /* Protocol specific checks */
 1160                 switch (proto) {
 1161                 case IPPROTO_TCP:
 1162                     {
 1163                         struct tcphdr *tcp;
 1164 
 1165                         if (offset == 1)        /* cf. RFC 1858 */
 1166                                 goto bogusfrag;
 1167                         if (offset != 0) {
 1168                                 /*
 1169                                  * TCP flags and ports aren't available in this
 1170                                  * packet -- if this rule specified either one,
 1171                                  * we consider the rule a non-match.
 1172                                  */
 1173                                 if (f->fw_nports != 0 ||
 1174                                     f->fw_tcpf != f->fw_tcpnf)
 1175                                         continue;
 1176 
 1177                                 break;
 1178                         }
 1179                         tcp = (struct tcphdr *) ((u_int32_t *)ip + ip->ip_hl);
 1180                         if (((f->fw_tcpf != f->fw_tcpnf) ||
 1181                             (f->fw_ipflg & IP_FW_IF_TCPEST)) &&
 1182                             !tcpflg_match(tcp, f))
 1183                                 continue;
 1184                         goto check_ports;
 1185                     }
 1186 
 1187                 case IPPROTO_UDP:
 1188                         if (offset != 0) {
 1189                                 /*
 1190                                  * Port specification is unavailable -- if this
 1191                                  * rule specifies a port, we consider the rule
 1192                                  * a non-match.
 1193                                  */
 1194                                 if (f->fw_nports != 0)
 1195                                         continue;
 1196 
 1197                                 break;
 1198                         }
 1199 check_ports:
 1200                         if (!port_match(&f->fw_uar.fw_pts[0],
 1201                             IP_FW_GETNSRCP(f), ntohs(src_port),
 1202                             f->fw_flg & IP_FW_F_SRNG,
 1203                             f->fw_flg & IP_FW_F_SMSK))
 1204                                 continue;
 1205                         if (!port_match(&f->fw_uar.fw_pts[IP_FW_GETNSRCP(f)],
 1206                             IP_FW_GETNDSTP(f), ntohs(dst_port),
 1207                             f->fw_flg & IP_FW_F_DRNG,
 1208                             f->fw_flg & IP_FW_F_DMSK)) 
 1209                                 continue;
 1210                         break;
 1211 
 1212                 case IPPROTO_ICMP:
 1213                     {
 1214                         struct icmp *icmp;
 1215 
 1216                         if (offset != 0)        /* Type isn't valid */
 1217                                 break;
 1218                         icmp = (struct icmp *) ((u_int32_t *)ip + ip->ip_hl);
 1219                         if (!icmptype_match(icmp, f))
 1220                                 continue;
 1221                         break;
 1222                     }
 1223 
 1224                 default:
 1225                         break;
 1226 
 1227 bogusfrag:
 1228                 if (fw_verbose)
 1229                         ipfw_report(NULL, ip, rif, oif);
 1230                 goto dropit;
 1231 
 1232                 }
 1233 
 1234 rnd_then_got_match:
 1235                 if ( ((struct ip_fw_ext *)f)->dont_match_prob &&
 1236                     random() < ((struct ip_fw_ext *)f)->dont_match_prob )
 1237                         continue ;
 1238 got_match:
 1239 #if STATEFUL    /* stateful ipfw */
 1240                 /*
 1241                  * If have a dynamic match (q != NULL) set f to the right rule;
 1242                  * else, if have keep-state, install a new dynamic entry.
 1243                  * The packet info is in last_pkt.
 1244                  */
 1245                 if (q != NULL)
 1246                     f = chain->rule ;
 1247                 else if (f->fw_flg & IP_FW_F_KEEP_S)
 1248                     install_state(chain, pip, ip);
 1249 #endif
 1250                 *flow_id = chain ; /* XXX set flow id */
 1251                 /* Update statistics */
 1252                 f->fw_pcnt += 1;
 1253                 if (ip) {
 1254                     f->fw_bcnt += ip->ip_len;
 1255                 }
 1256                 f->timestamp = time_second;
 1257 
 1258                 /* Log to console if desired */
 1259                 if ((f->fw_flg & IP_FW_F_PRN) && fw_verbose)
 1260                         ipfw_report(f, ip, rif, oif);
 1261 
 1262                 /* Take appropriate action */
 1263                 switch (f->fw_flg & IP_FW_F_COMMAND) {
 1264                 case IP_FW_F_ACCEPT:
 1265                         return(0);
 1266                 case IP_FW_F_COUNT:
 1267                         continue;
 1268 #ifdef IPDIVERT
 1269                 case IP_FW_F_DIVERT:
 1270                         *cookie = f->fw_number;
 1271                         return(f->fw_divert_port);
 1272                 case IP_FW_F_TEE:
 1273                         /*
 1274                          * XXX someday tee packet here, but beware that you
 1275                          * can't use m_copym() or m_copypacket() because
 1276                          * the divert input routine modifies the mbuf
 1277                          * (and these routines only increment reference
 1278                          * counts in the case of mbuf clusters), so need
 1279                          * to write custom routine.
 1280                          */
 1281                         continue;
 1282 #endif
 1283                 case IP_FW_F_SKIPTO: /* XXX check */
 1284                         if ( f->next_rule_ptr )
 1285                             chain = f->next_rule_ptr ;
 1286                         else
 1287                             chain = lookup_next_rule(chain) ;
 1288                         if (! chain) goto dropit;
 1289                         goto again ;
 1290 #ifdef DUMMYNET
 1291                 case IP_FW_F_PIPE:
 1292                         return(f->fw_pipe_nr | IP_FW_PORT_DYNT_FLAG );
 1293 #endif
 1294 #ifdef IPFIREWALL_FORWARD
 1295                 case IP_FW_F_FWD:
 1296                         /* Change the next-hop address for this packet.
 1297                          * Initially we'll only worry about directly
 1298                          * reachable next-hop's, but ultimately
 1299                          * we will work out for next-hops that aren't
 1300                          * direct the route we would take for it. We
 1301                          * [cs]ould leave this latter problem to
 1302                          * ip_output.c. We hope to high [name the abode of
 1303                          * your favourite deity] that ip_output doesn't modify
 1304                          * the new value of next_hop (which is dst there)
 1305                          */
 1306                         if (next_hop != NULL) /* Make sure, first... */
 1307                                 *next_hop = &(f->fw_fwd_ip);
 1308                         return(0); /* Allow the packet */
 1309 #endif
 1310                 }
 1311 
 1312                 /* Deny/reject this packet using this rule */
 1313                 rule = f;
 1314                 break;
 1315 
 1316         }
 1317 
 1318 #ifdef DIAGNOSTIC
 1319         /* Rule IPFW_DEFAULT_RULE should always be there and should always match */
 1320         if (!chain)
 1321                 panic("ip_fw: chain");
 1322 #endif
 1323 
 1324         /*
 1325          * At this point, we're going to drop the packet.
 1326          * Send a reject notice if all of the following are true:
 1327          *
 1328          * - The packet matched a reject rule
 1329          * - The packet is not an ICMP packet, or is an ICMP query packet
 1330          * - The packet is not a multicast or broadcast packet
 1331          */
 1332         if ((rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_REJECT
 1333             && ip
 1334             && (ip->ip_p != IPPROTO_ICMP || is_icmp_query(ip))
 1335             && !((*m)->m_flags & (M_BCAST|M_MCAST))
 1336             && !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
 1337                 switch (rule->fw_reject_code) {
 1338                 case IP_FW_REJECT_RST:
 1339                   {
 1340                         struct tcphdr *const tcp =
 1341                                 (struct tcphdr *) ((u_int32_t *)ip + ip->ip_hl);
 1342                         struct tcpiphdr ti, *const tip = (struct tcpiphdr *) ip;
 1343 
 1344                         if (offset != 0 || (tcp->th_flags & TH_RST))
 1345                                 break;
 1346                         ti.ti_i = *((struct ipovly *) ip);
 1347                         ti.ti_t = *tcp;
 1348                         bcopy(&ti, ip, sizeof(ti));
 1349                         NTOHL(tip->ti_seq);
 1350                         NTOHL(tip->ti_ack);
 1351                         tip->ti_len = ip->ip_len - hlen - (tip->ti_off << 2);
 1352                         if (tcp->th_flags & TH_ACK) {
 1353                                 tcp_respond(NULL, tip, *m,
 1354                                     (tcp_seq)0, ntohl(tcp->th_ack), TH_RST);
 1355                         } else {
 1356                                 if (tcp->th_flags & TH_SYN)
 1357                                         tip->ti_len++;
 1358                                 tcp_respond(NULL, tip, *m, tip->ti_seq
 1359                                     + tip->ti_len, (tcp_seq)0, TH_RST|TH_ACK);
 1360                         }
 1361                         *m = NULL;
 1362                         break;
 1363                   }
 1364                 default:        /* Send an ICMP unreachable using code */
 1365                         icmp_error(*m, ICMP_UNREACH,
 1366                             rule->fw_reject_code, 0L, 0);
 1367                         *m = NULL;
 1368                         break;
 1369                 }
 1370         }
 1371 
 1372 dropit:
 1373         /*
 1374          * Finally, drop the packet.
 1375          */
 1376         if (*m) {
 1377                 m_freem(*m);
 1378                 *m = NULL;
 1379         }
 1380         return(0);
 1381 }
 1382 
 1383 /*
 1384  * when a rule is added/deleted, zero the direct pointers within
 1385  * all firewall rules. These will be reconstructed on the fly
 1386  * as packets are matched.
 1387  * Must be called at splnet().
 1388  */
 1389 static void
 1390 flush_rule_ptrs()
 1391 {
 1392     struct ip_fw_chain *fcp ;
 1393 
 1394     for (fcp = ip_fw_chain.lh_first; fcp; fcp = fcp->chain.le_next) {
 1395         fcp->rule->next_rule_ptr = NULL ;
 1396     }
 1397 }
 1398 
 1399 static int
 1400 add_entry(struct ip_fw_head *chainptr, struct ip_fw *frwl)
 1401 {
 1402         struct ip_fw *ftmp = 0;
 1403         struct ip_fw_ext *ftmp_ext = 0 ;
 1404         struct ip_fw_chain *fwc = 0, *fcp, *fcpl = 0;
 1405         u_short nbr = 0;
 1406         int s;
 1407 
 1408         fwc = malloc(sizeof *fwc, M_IPFW, M_DONTWAIT);
 1409         ftmp_ext = malloc(sizeof *ftmp_ext, M_IPFW, M_DONTWAIT);
 1410         ftmp = &ftmp_ext->rule ;
 1411         if (!fwc || !ftmp) {
 1412                 dprintf(("%s malloc said no\n", err_prefix));
 1413                 if (fwc)  free(fwc, M_IPFW);
 1414                 if (ftmp) free(ftmp, M_IPFW);
 1415                 return (ENOSPC);
 1416         }
 1417 
 1418         bzero(ftmp_ext, sizeof(*ftmp_ext)); /* play safe! */
 1419         bcopy(frwl, ftmp, sizeof(*ftmp));
 1420         if (ftmp->fw_flg & IP_FW_F_RND_MATCH)
 1421                 ftmp_ext->dont_match_prob = (long)(ftmp->pipe_ptr) ;
 1422         if (ftmp->fw_flg & IP_FW_F_KEEP_S)
 1423                 ftmp_ext->dyn_type = (u_long)(ftmp->next_rule_ptr) ;
 1424 
 1425         ftmp->fw_in_if.fu_via_if.name[FW_IFNLEN - 1] = '\0';
 1426         ftmp->fw_pcnt = 0L;
 1427         ftmp->fw_bcnt = 0L;
 1428         ftmp->next_rule_ptr = NULL ;
 1429         ftmp->pipe_ptr = NULL ;
 1430         fwc->rule = ftmp;
 1431         
 1432         s = splnet();
 1433 
 1434         if (chainptr->lh_first == 0) {
 1435                 LIST_INSERT_HEAD(chainptr, fwc, chain);
 1436                 splx(s);
 1437                 return(0);
 1438         }
 1439 
 1440         /* If entry number is 0, find highest numbered rule and add 100 */
 1441         if (ftmp->fw_number == 0) {
 1442                 for (fcp = LIST_FIRST(chainptr); fcp; fcp = LIST_NEXT(fcp, chain)) {
 1443                         if (fcp->rule->fw_number != (u_short)-1)
 1444                                 nbr = fcp->rule->fw_number;
 1445                         else
 1446                                 break;
 1447                 }
 1448                 if (nbr < IPFW_DEFAULT_RULE - 100)
 1449                         nbr += 100;
 1450                 ftmp->fw_number = nbr;
 1451         }
 1452 
 1453         /* Got a valid number; now insert it, keeping the list ordered */
 1454         for (fcp = LIST_FIRST(chainptr); fcp; fcp = LIST_NEXT(fcp, chain)) {
 1455                 if (fcp->rule->fw_number > ftmp->fw_number) {
 1456                         if (fcpl) {
 1457                                 LIST_INSERT_AFTER(fcpl, fwc, chain);
 1458                         } else {
 1459                                 LIST_INSERT_HEAD(chainptr, fwc, chain);
 1460                         }
 1461                         break;
 1462                 } else {
 1463                         fcpl = fcp;
 1464                 }
 1465         }
 1466         flush_rule_ptrs();
 1467 
 1468         splx(s);
 1469         return (0);
 1470 }
 1471 
 1472 static int
 1473 del_entry(struct ip_fw_head *chainptr, u_short number)
 1474 {
 1475         struct ip_fw_chain *fcp;
 1476 
 1477         fcp = LIST_FIRST(chainptr);
 1478         if (number != (u_short)-1) {
 1479                 for (; fcp; fcp = LIST_NEXT(fcp, chain)) {
 1480                         if (fcp->rule->fw_number == number) {
 1481                                 int s;
 1482 
 1483                                 /* prevent access to rules while removing them */
 1484                                 s = splnet();
 1485                                 while (fcp && fcp->rule->fw_number == number) {
 1486                                         struct ip_fw_chain *next;
 1487 
 1488 #if STATEFUL
 1489                                         remove_dyn_rule(fcp, 1 /* force_delete */);
 1490 #endif
 1491                                         next = LIST_NEXT(fcp, chain);
 1492                                         LIST_REMOVE(fcp, chain);
 1493 #ifdef DUMMYNET
 1494                                         dn_rule_delete(fcp) ;
 1495 #endif
 1496                                         flush_rule_ptrs();
 1497                                         free(fcp->rule, M_IPFW);
 1498                                         free(fcp, M_IPFW);
 1499                                         fcp = next;
 1500                                 }
 1501                                 splx(s);
 1502                                 return 0;
 1503                         }
 1504                 }
 1505         }
 1506 
 1507         return (EINVAL);
 1508 }
 1509 
 1510 static int
 1511 zero_entry(struct ip_fw *frwl)
 1512 {
 1513         struct ip_fw_chain *fcp;
 1514         int s, cleared;
 1515 
 1516         if (frwl == 0) {
 1517                 s = splnet();
 1518                 for (fcp = LIST_FIRST(&ip_fw_chain); fcp; fcp = LIST_NEXT(fcp, chain)) {
 1519                         fcp->rule->fw_bcnt = fcp->rule->fw_pcnt = 0;
 1520                         fcp->rule->fw_loghighest = fcp->rule->fw_logamount;
 1521                         fcp->rule->timestamp = 0;
 1522                 }
 1523                 splx(s);
 1524         }
 1525         else {
 1526                 cleared = 0;
 1527 
 1528                 /*
 1529                  *      It's possible to insert multiple chain entries with the
 1530                  *      same number, so we don't stop after finding the first
 1531                  *      match if zeroing a specific entry.
 1532                  */
 1533                 for (fcp = LIST_FIRST(&ip_fw_chain); fcp; fcp = LIST_NEXT(fcp, chain))
 1534                         if (frwl->fw_number == fcp->rule->fw_number) {
 1535                                 s = splnet();
 1536                                 while (fcp && frwl->fw_number == fcp->rule->fw_number) {
 1537                                         fcp->rule->fw_bcnt = fcp->rule->fw_pcnt = 0;
 1538                                         fcp->rule->fw_loghighest =
 1539                                             fcp->rule->fw_logamount;
 1540                                         fcp->rule->timestamp = 0;
 1541                                         fcp = LIST_NEXT(fcp, chain);
 1542                                 }
 1543                                 splx(s);
 1544                                 cleared = 1;
 1545                                 break;
 1546                         }
 1547                 if (!cleared)   /* we didn't find any matching rules */
 1548                         return (EINVAL);
 1549         }
 1550 
 1551         if (fw_verbose) {
 1552                 if (frwl)
 1553                         printf("ipfw: Entry %d cleared.\n", frwl->fw_number);
 1554                 else
 1555                         printf("ipfw: Accounting cleared.\n");
 1556         }
 1557 
 1558         return (0);
 1559 }
 1560 
 1561 static int
 1562 resetlog_entry(struct ip_fw *frwl)
 1563 {
 1564         struct ip_fw_chain *fcp;
 1565         int s, cleared;
 1566 
 1567         if (frwl == 0) {
 1568                 s = splnet();
 1569                 counter = 0;
 1570                 for (fcp = LIST_FIRST(&ip_fw_chain); fcp; fcp = LIST_NEXT(fcp, chain))
 1571                         fcp->rule->fw_loghighest = fcp->rule->fw_pcnt +
 1572                             fcp->rule->fw_logamount;
 1573                 splx(s);
 1574         }
 1575         else {
 1576                 cleared = 0;
 1577 
 1578                 /*
 1579                  *      It's possible to insert multiple chain entries with the
 1580                  *      same number, so we don't stop after finding the first
 1581                  *      match if zeroing a specific entry.
 1582                  */
 1583                 for (fcp = LIST_FIRST(&ip_fw_chain); fcp; fcp = LIST_NEXT(fcp, chain))
 1584                         if (frwl->fw_number == fcp->rule->fw_number) {
 1585                                 s = splnet();
 1586                                 while (fcp && frwl->fw_number == fcp->rule->fw_number) {
 1587                                         fcp->rule->fw_loghighest =
 1588                                             fcp->rule->fw_pcnt +
 1589                                             fcp->rule->fw_logamount;
 1590                                         fcp = LIST_NEXT(fcp, chain);
 1591                                 }
 1592                                 splx(s);
 1593                                 cleared = 1;
 1594                                 break;
 1595                         }
 1596                 if (!cleared)   /* we didn't find any matching rules */
 1597                         return (EINVAL);
 1598         }
 1599 
 1600         if (fw_verbose) {
 1601                 if (frwl)
 1602                         printf("ipfw: Entry %d logging count reset.\n",
 1603                             frwl->fw_number);
 1604                 else
 1605                         printf("ipfw: All logging counts cleared.\n");
 1606         }
 1607 
 1608         return (0);
 1609 }
 1610 
 1611 static int
 1612 check_ipfw_struct(struct ip_fw *frwl)
 1613 {
 1614         /* Check for invalid flag bits */
 1615         if ((frwl->fw_flg & ~IP_FW_F_MASK) != 0) {
 1616                 dprintf(("%s undefined flag bits set (flags=%x)\n",
 1617                     err_prefix, frwl->fw_flg));
 1618                 return (EINVAL);
 1619         }
 1620         if (frwl->fw_flg == IP_FW_F_CHECK_S) {
 1621                 /* check-state */
 1622                 return 0 ;
 1623         }
 1624         /* Must apply to incoming or outgoing (or both) */
 1625         if (!(frwl->fw_flg & (IP_FW_F_IN | IP_FW_F_OUT))) {
 1626                 dprintf(("%s neither in nor out\n", err_prefix));
 1627                 return (EINVAL);
 1628         }
 1629         /* Empty interface name is no good */
 1630         if (((frwl->fw_flg & IP_FW_F_IIFNAME)
 1631               && !*frwl->fw_in_if.fu_via_if.name)
 1632             || ((frwl->fw_flg & IP_FW_F_OIFNAME)
 1633               && !*frwl->fw_out_if.fu_via_if.name)) {
 1634                 dprintf(("%s empty interface name\n", err_prefix));
 1635                 return (EINVAL);
 1636         }
 1637         /* Sanity check interface matching */
 1638         if ((frwl->fw_flg & IF_FW_F_VIAHACK) == IF_FW_F_VIAHACK) {
 1639                 ;               /* allow "via" backwards compatibility */
 1640         } else if ((frwl->fw_flg & IP_FW_F_IN)
 1641             && (frwl->fw_flg & IP_FW_F_OIFACE)) {
 1642                 dprintf(("%s outgoing interface check on incoming\n",
 1643                     err_prefix));
 1644                 return (EINVAL);
 1645         }
 1646         /* Sanity check port ranges */
 1647         if ((frwl->fw_flg & IP_FW_F_SRNG) && IP_FW_GETNSRCP(frwl) < 2) {
 1648                 dprintf(("%s src range set but n_src_p=%d\n",
 1649                     err_prefix, IP_FW_GETNSRCP(frwl)));
 1650                 return (EINVAL);
 1651         }
 1652         if ((frwl->fw_flg & IP_FW_F_DRNG) && IP_FW_GETNDSTP(frwl) < 2) {
 1653                 dprintf(("%s dst range set but n_dst_p=%d\n",
 1654                     err_prefix, IP_FW_GETNDSTP(frwl)));
 1655                 return (EINVAL);
 1656         }
 1657         if (IP_FW_GETNSRCP(frwl) + IP_FW_GETNDSTP(frwl) > IP_FW_MAX_PORTS) {
 1658                 dprintf(("%s too many ports (%d+%d)\n",
 1659                     err_prefix, IP_FW_GETNSRCP(frwl), IP_FW_GETNDSTP(frwl)));
 1660                 return (EINVAL);
 1661         }
 1662         /*
 1663          *      Protocols other than TCP/UDP don't use port range
 1664          */
 1665         if ((frwl->fw_prot != IPPROTO_TCP) &&
 1666             (frwl->fw_prot != IPPROTO_UDP) &&
 1667             (IP_FW_GETNSRCP(frwl) || IP_FW_GETNDSTP(frwl))) {
 1668                 dprintf(("%s port(s) specified for non TCP/UDP rule\n",
 1669                     err_prefix));
 1670                 return (EINVAL);
 1671         }
 1672 
 1673         /*
 1674          *      Rather than modify the entry to make such entries work, 
 1675          *      we reject this rule and require user level utilities
 1676          *      to enforce whatever policy they deem appropriate.
 1677          */
 1678         if ((frwl->fw_src.s_addr & (~frwl->fw_smsk.s_addr)) || 
 1679                 (frwl->fw_dst.s_addr & (~frwl->fw_dmsk.s_addr))) {
 1680                 dprintf(("%s rule never matches\n", err_prefix));
 1681                 return (EINVAL);
 1682         }
 1683 
 1684         if ((frwl->fw_flg & IP_FW_F_FRAG) &&
 1685                 (frwl->fw_prot == IPPROTO_UDP || frwl->fw_prot == IPPROTO_TCP)) {
 1686                 if (frwl->fw_nports) {
 1687                         dprintf(("%s cannot mix 'frag' and ports\n", err_prefix));
 1688                         return (EINVAL);
 1689                 }
 1690                 if (frwl->fw_prot == IPPROTO_TCP &&
 1691                         frwl->fw_tcpf != frwl->fw_tcpnf) {
 1692                         dprintf(("%s cannot mix 'frag' and TCP flags\n", err_prefix));
 1693                         return (EINVAL);
 1694                 }
 1695         }
 1696 
 1697         /* Check command specific stuff */
 1698         switch (frwl->fw_flg & IP_FW_F_COMMAND)
 1699         {
 1700         case IP_FW_F_REJECT:
 1701                 if (frwl->fw_reject_code >= 0x100
 1702                     && !(frwl->fw_prot == IPPROTO_TCP
 1703                       && frwl->fw_reject_code == IP_FW_REJECT_RST)) {
 1704                         dprintf(("%s unknown reject code\n", err_prefix));
 1705                         return (EINVAL);
 1706                 }
 1707                 break;
 1708 #if defined(IPDIVERT) || defined(DUMMYNET)
 1709 #ifdef IPDIVERT
 1710         case IP_FW_F_DIVERT:            /* Diverting to port zero is invalid */
 1711         case IP_FW_F_TEE:
 1712 #endif
 1713 #ifdef DUMMYNET
 1714         case IP_FW_F_PIPE:              /* piping through 0 is invalid */
 1715 #endif
 1716                 if (frwl->fw_divert_port == 0) {
 1717                         dprintf(("%s can't divert to port 0\n", err_prefix));
 1718                         return (EINVAL);
 1719                 }
 1720                 break;
 1721 #endif /* IPDIVERT || DUMMYNET */
 1722         case IP_FW_F_DENY:
 1723         case IP_FW_F_ACCEPT:
 1724         case IP_FW_F_COUNT:
 1725         case IP_FW_F_SKIPTO:
 1726 #ifdef IPFIREWALL_FORWARD
 1727         case IP_FW_F_FWD:
 1728 #endif
 1729         case IP_FW_F_UID:
 1730         case IP_FW_F_GID:
 1731                 break;
 1732         default:
 1733                 dprintf(("%s invalid command\n", err_prefix));
 1734                 return (EINVAL);
 1735         }
 1736 
 1737         return 0;
 1738 }
 1739 
 1740 static int
 1741 ip_fw_ctl(struct sockopt *sopt)
 1742 {
 1743         int error, s;
 1744         size_t size;
 1745         struct ip_fw_chain *fcp;
 1746         struct ip_fw frwl, *bp , *buf;
 1747 
 1748         /*
 1749          * Disallow sets in really-really secure mode, but still allow
 1750          * the logging counters to be reset.
 1751          */
 1752         if (sopt->sopt_dir == SOPT_SET && securelevel >= 3 &&
 1753             sopt->sopt_name != IP_FW_RESETLOG)
 1754                         return (EPERM);
 1755         error = 0;
 1756 
 1757         switch (sopt->sopt_name) {
 1758         case IP_FW_GET:
 1759                 for (fcp = LIST_FIRST(&ip_fw_chain), size = 0; fcp;
 1760                      fcp = LIST_NEXT(fcp, chain))
 1761                         size += sizeof *fcp->rule;
 1762 #if STATEFUL
 1763                 if (ipfw_dyn_v) {
 1764                     int i ;
 1765                     struct ipfw_dyn_rule *p ;
 1766 
 1767                     for (i = 0 ; i < curr_dyn_buckets ; i++ )
 1768                         for ( p = ipfw_dyn_v[i] ; p != NULL ; p = p->next )
 1769                             size += sizeof(*p) ;
 1770                 }
 1771 #endif
 1772                 buf = malloc(size, M_TEMP, M_WAITOK);
 1773                 if (buf == 0) {
 1774                         error = ENOBUFS;
 1775                         break;
 1776                 }
 1777 
 1778                 for (fcp = LIST_FIRST(&ip_fw_chain), bp = buf; fcp;
 1779                      fcp = LIST_NEXT(fcp, chain)) {
 1780                         bcopy(fcp->rule, bp, sizeof *fcp->rule);
 1781                         bp->pipe_ptr = (void *)(intptr_t)
 1782                             ((struct ip_fw_ext *)fcp->rule)->dont_match_prob;
 1783                         bp->next_rule_ptr = (void *)(intptr_t)
 1784                             ((struct ip_fw_ext *)fcp->rule)->dyn_type;
 1785                         bp ++ ;
 1786                 }
 1787 #if STATEFUL
 1788                 if (ipfw_dyn_v) {
 1789                     int i ;
 1790                     struct ipfw_dyn_rule *p, *dst, *last = NULL ;
 1791 
 1792                     dst = (struct ipfw_dyn_rule *)bp ;
 1793                     for (i = 0 ; i < curr_dyn_buckets ; i++ )
 1794                         for (p=ipfw_dyn_v[i] ; p!=NULL ; p=p->next, dst++ ) {
 1795                         bcopy(p, dst, sizeof *p);
 1796                         (int)dst->chain = p->chain->rule->fw_number ;
 1797                         dst->next = dst ; /* fake non-null pointer... */
 1798                         last = dst ;
 1799                         if (TIME_LEQ(dst->expire, time_second) )
 1800                             dst->expire = 0 ;
 1801                         else
 1802                             dst->expire -= time_second ;
 1803                     }
 1804                     if (last != NULL)
 1805                         last->next = NULL ;
 1806                 }
 1807 #endif
 1808                 error = sooptcopyout(sopt, buf, size);
 1809                 FREE(buf, M_TEMP);
 1810                 break;
 1811 
 1812         case IP_FW_FLUSH:
 1813 #if STATEFUL
 1814                 s = splnet();
 1815                 remove_dyn_rule(NULL, 1 /* force delete */);
 1816                 splx(s);
 1817 #endif
 1818                 for (fcp = ip_fw_chain.lh_first; 
 1819                      fcp != 0 && fcp->rule->fw_number != IPFW_DEFAULT_RULE;
 1820                      fcp = ip_fw_chain.lh_first) {
 1821                         s = splnet();
 1822                         LIST_REMOVE(fcp, chain);
 1823 #ifdef DUMMYNET
 1824                         dn_rule_delete(fcp);
 1825 #endif
 1826                         FREE(fcp->rule, M_IPFW);
 1827                         FREE(fcp, M_IPFW);
 1828                         splx(s);
 1829                 }
 1830                 break;
 1831 
 1832         case IP_FW_ZERO:
 1833                 if (sopt->sopt_val != 0) {
 1834                         error = sooptcopyin(sopt, &frwl, sizeof frwl,
 1835                                             sizeof frwl);
 1836                         if (error || (error = zero_entry(&frwl)))
 1837                                 break;
 1838                 } else {
 1839                         error = zero_entry(0);
 1840                 }
 1841                 break;
 1842 
 1843         case IP_FW_ADD:
 1844                 error = sooptcopyin(sopt, &frwl, sizeof frwl, sizeof frwl);
 1845                 if (error || (error = check_ipfw_struct(&frwl)))
 1846                         break;
 1847 
 1848                 if (frwl.fw_number == IPFW_DEFAULT_RULE) {
 1849                         dprintf(("%s can't add rule %u\n", err_prefix,
 1850                                  (unsigned)IPFW_DEFAULT_RULE));
 1851                         error = EINVAL;
 1852                 } else {
 1853                         error = add_entry(&ip_fw_chain, &frwl);
 1854                 }
 1855                 break;
 1856 
 1857         case IP_FW_DEL:
 1858                 error = sooptcopyin(sopt, &frwl, sizeof frwl, sizeof frwl);
 1859                 if (error)
 1860                         break;
 1861 
 1862                 if (frwl.fw_number == IPFW_DEFAULT_RULE) {
 1863                         dprintf(("%s can't delete rule %u\n", err_prefix,
 1864                                  (unsigned)IPFW_DEFAULT_RULE));
 1865                         error = EINVAL;
 1866                 } else {
 1867                         error = del_entry(&ip_fw_chain, frwl.fw_number);
 1868                 }
 1869                 break;
 1870 
 1871         case IP_FW_RESETLOG:
 1872                 if (sopt->sopt_val != 0) {
 1873                         error = sooptcopyin(sopt, &frwl, sizeof frwl,
 1874                                             sizeof frwl);
 1875                         if (error || (error = resetlog_entry(&frwl)))
 1876                                 break;
 1877                 } else {
 1878                         error = resetlog_entry(0);
 1879                 }
 1880                 break;
 1881 
 1882         default:
 1883                 printf("ip_fw_ctl invalid option %d\n", sopt->sopt_name);
 1884                 error = EINVAL ;
 1885         }
 1886 
 1887         return (error);
 1888 }
 1889 
 1890 struct ip_fw_chain *ip_fw_default_rule ;
 1891 
 1892 void
 1893 ip_fw_init(void)
 1894 {
 1895         struct ip_fw default_rule;
 1896 
 1897         ip_fw_chk_ptr = ip_fw_chk;
 1898         ip_fw_ctl_ptr = ip_fw_ctl;
 1899         LIST_INIT(&ip_fw_chain);
 1900 
 1901         bzero(&default_rule, sizeof default_rule);
 1902         default_rule.fw_prot = IPPROTO_IP;
 1903         default_rule.fw_number = IPFW_DEFAULT_RULE;
 1904 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
 1905         default_rule.fw_flg |= IP_FW_F_ACCEPT;
 1906 #else
 1907         default_rule.fw_flg |= IP_FW_F_DENY;
 1908 #endif
 1909         default_rule.fw_flg |= IP_FW_F_IN | IP_FW_F_OUT;
 1910         if (check_ipfw_struct(&default_rule) != 0 ||
 1911             add_entry(&ip_fw_chain, &default_rule))
 1912                 panic("ip_fw_init");
 1913 
 1914         ip_fw_default_rule = ip_fw_chain.lh_first ;
 1915         printf("IP packet filtering initialized, "
 1916 #ifdef IPDIVERT
 1917                 "divert enabled, "
 1918 #else
 1919                 "divert disabled, "
 1920 #endif
 1921 #ifdef IPFIREWALL_FORWARD
 1922                 "rule-based forwarding enabled, "
 1923 #else
 1924                 "rule-based forwarding disabled, "
 1925 #endif
 1926 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
 1927                 "default to accept, " );
 1928 #else
 1929                 "default to deny, " );
 1930 #endif
 1931 #ifndef IPFIREWALL_VERBOSE
 1932         printf("logging disabled\n");
 1933 #else
 1934         if (fw_verbose_limit == 0)
 1935                 printf("unlimited logging\n");
 1936         else
 1937                 printf("logging limited to %d packets/entry by default\n",
 1938                     fw_verbose_limit);
 1939 #endif
 1940 }
 1941 
 1942 static ip_fw_chk_t *old_chk_ptr;
 1943 static ip_fw_ctl_t *old_ctl_ptr;
 1944 
 1945 #if defined(IPFIREWALL_MODULE) && !defined(KLD_MODULE)
 1946 
 1947 #include <sys/exec.h>
 1948 #include <sys/sysent.h>
 1949 #include <sys/lkm.h>
 1950 
 1951 MOD_MISC(ipfw);
 1952 
 1953 static int
 1954 ipfw_load(struct lkm_table *lkmtp, int cmd)
 1955 {
 1956         int s=splnet();
 1957 
 1958         old_chk_ptr = ip_fw_chk_ptr;
 1959         old_ctl_ptr = ip_fw_ctl_ptr;
 1960 
 1961         ip_fw_init();
 1962         splx(s);
 1963         return 0;
 1964 }
 1965 
 1966 static int
 1967 ipfw_unload(struct lkm_table *lkmtp, int cmd)
 1968 {
 1969         int s=splnet();
 1970 
 1971         ip_fw_chk_ptr =  old_chk_ptr;
 1972         ip_fw_ctl_ptr =  old_ctl_ptr;
 1973 #if STATEFUL
 1974         remove_dyn_rule(NULL, 1 /* force delete */);
 1975 #endif
 1976         while (LIST_FIRST(&ip_fw_chain) != NULL) {
 1977                 struct ip_fw_chain *fcp = LIST_FIRST(&ip_fw_chain);
 1978                 LIST_REMOVE(LIST_FIRST(&ip_fw_chain), chain);
 1979 #ifdef DUMMYNET
 1980                 dn_rule_delete(fcp);
 1981 #endif
 1982                 free(fcp->rule, M_IPFW);
 1983                 free(fcp, M_IPFW);
 1984         }
 1985         
 1986         splx(s);
 1987         printf("IP firewall unloaded\n");
 1988         return 0;
 1989 }
 1990 
 1991 int
 1992 ipfw_mod(struct lkm_table *lkmtp, int cmd, int ver)
 1993 {
 1994         MOD_DISPATCH(ipfw, lkmtp, cmd, ver,
 1995                 ipfw_load, ipfw_unload, lkm_nullcmd);
 1996 }
 1997 #else
 1998 static int
 1999 ipfw_modevent(module_t mod, int type, void *unused)
 2000 {
 2001         int s;
 2002         
 2003         switch (type) {
 2004         case MOD_LOAD:
 2005                 s = splnet();
 2006 
 2007                 old_chk_ptr = ip_fw_chk_ptr;
 2008                 old_ctl_ptr = ip_fw_ctl_ptr;
 2009 
 2010                 ip_fw_init();
 2011                 splx(s);
 2012                 return 0;
 2013         case MOD_UNLOAD:
 2014                 s = splnet();
 2015                 ip_fw_chk_ptr =  old_chk_ptr;
 2016                 ip_fw_ctl_ptr =  old_ctl_ptr;
 2017 #if STATEFUL
 2018                 remove_dyn_rule(NULL, 1 /* force delete */);
 2019 #endif
 2020                 while (LIST_FIRST(&ip_fw_chain) != NULL) {
 2021                         struct ip_fw_chain *fcp = LIST_FIRST(&ip_fw_chain);
 2022                         LIST_REMOVE(LIST_FIRST(&ip_fw_chain), chain);
 2023 #ifdef DUMMYNET
 2024                         dn_rule_delete(fcp);
 2025 #endif
 2026                         free(fcp->rule, M_IPFW);
 2027                         free(fcp, M_IPFW);
 2028                 }
 2029         
 2030                 splx(s);
 2031                 printf("IP firewall unloaded\n");
 2032                 return 0;
 2033         default:
 2034                 break;
 2035         }
 2036         return 0;
 2037 }
 2038 
 2039 static moduledata_t ipfwmod = {
 2040         "ipfw",
 2041         ipfw_modevent,
 2042         0
 2043 };
 2044 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
 2045 #endif

Cache object: 7b2c613b3997d7df94311a887bb157fe


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