2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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
25 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.12 2003/04/08 10:42:32 maxim Exp $
32 * Implement IP packet firewall (new version)
35 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
41 #error IPFIREWALL requires INET.
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
50 #include <sys/kernel.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/syslog.h>
56 #include <sys/ucred.h>
58 #include <net/route.h>
59 #include <netinet/in.h>
60 #include <netinet/in_systm.h>
61 #include <netinet/in_var.h>
62 #include <netinet/in_pcb.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/ip_icmp.h>
66 #include <netinet/ip_fw.h>
67 #include <netinet/ip_dummynet.h>
68 #include <netinet/tcp.h>
69 #include <netinet/tcp_timer.h>
70 #include <netinet/tcp_var.h>
71 #include <netinet/tcpip.h>
72 #include <netinet/udp.h>
73 #include <netinet/udp_var.h>
75 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
77 #include <machine/in_cksum.h> /* XXX for in_cksum */
80 * XXX This one should go in sys/mbuf.h. It is used to avoid that
81 * a firewall-generated packet loops forever through the firewall.
83 #ifndef M_SKIP_FIREWALL
84 #define M_SKIP_FIREWALL 0x4000
88 * set_disable contains one bit per set value (0..31).
89 * If the bit is set, all rules with the corresponding set
90 * are disabled. Set 31 is reserved for the default rule
91 * and CANNOT be disabled.
93 static u_int32_t set_disable;
95 static int fw_verbose;
96 static int verbose_limit;
98 static struct callout_handle ipfw_timeout_h;
99 #define IPFW_DEFAULT_RULE 65535
102 * list of rules for layer 3
104 static struct ip_fw *layer3_chain;
106 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
108 static int fw_debug = 1;
109 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
112 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
113 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
114 &fw_enable, 0, "Enable ipfw");
115 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
116 &autoinc_step, 0, "Rule number autincrement step");
117 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
119 "Only do a single pass through ipfw when using dummynet(4)");
120 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
121 &fw_debug, 0, "Enable printing of debug ip_fw statements");
122 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
123 &fw_verbose, 0, "Log matches to ipfw rules");
124 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
125 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
128 * Description of dynamic rules.
130 * Dynamic rules are stored in lists accessed through a hash table
131 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
132 * be modified through the sysctl variable dyn_buckets which is
133 * updated when the table becomes empty.
135 * XXX currently there is only one list, ipfw_dyn.
137 * When a packet is received, its address fields are first masked
138 * with the mask defined for the rule, then hashed, then matched
139 * against the entries in the corresponding list.
140 * Dynamic rules can be used for different purposes:
142 * + enforcing limits on the number of sessions;
143 * + in-kernel NAT (not implemented yet)
145 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
146 * measured in seconds and depending on the flags.
148 * The total number of dynamic rules is stored in dyn_count.
149 * The max number of dynamic rules is dyn_max. When we reach
150 * the maximum number of rules we do not create anymore. This is
151 * done to avoid consuming too much memory, but also too much
152 * time when searching on each packet (ideally, we should try instead
153 * to put a limit on the length of the list on each bucket...).
155 * Each dynamic rule holds a pointer to the parent ipfw rule so
156 * we know what action to perform. Dynamic rules are removed when
157 * the parent rule is deleted. XXX we should make them survive.
159 * There are some limitations with dynamic rules -- we do not
160 * obey the 'randomized match', and we do not do multiple
161 * passes through the firewall. XXX check the latter!!!
163 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
164 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
165 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
168 * Timeouts for various events in handing dynamic rules.
170 static u_int32_t dyn_ack_lifetime = 300;
171 static u_int32_t dyn_syn_lifetime = 20;
172 static u_int32_t dyn_fin_lifetime = 1;
173 static u_int32_t dyn_rst_lifetime = 1;
174 static u_int32_t dyn_udp_lifetime = 10;
175 static u_int32_t dyn_short_lifetime = 5;
178 * Keepalives are sent if dyn_keepalive is set. They are sent every
179 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
180 * seconds of lifetime of a rule.
181 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
182 * than dyn_keepalive_period.
185 static u_int32_t dyn_keepalive_interval = 20;
186 static u_int32_t dyn_keepalive_period = 5;
187 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
189 static u_int32_t static_count; /* # of static rules */
190 static u_int32_t static_len; /* size in bytes of static rules */
191 static u_int32_t dyn_count; /* # of dynamic rules */
192 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
194 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
195 &dyn_buckets, 0, "Number of dyn. buckets");
196 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
197 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
198 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
199 &dyn_count, 0, "Number of dyn. rules");
200 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
201 &dyn_max, 0, "Max number of dyn. rules");
202 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
203 &static_count, 0, "Number of static rules");
204 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
205 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
206 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
207 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
208 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
209 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
210 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
211 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
212 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
213 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
214 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
215 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
216 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
217 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
219 #endif /* SYSCTL_NODE */
222 static ip_fw_chk_t ipfw_chk;
224 ip_dn_ruledel_t *ip_dn_ruledel_ptr = NULL; /* hook into dummynet */
227 * This macro maps an ip pointer into a layer3 header pointer of type T
229 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
232 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
234 int type = L3HDR(struct icmp,ip)->icmp_type;
236 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
239 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
240 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
243 is_icmp_query(struct ip *ip)
245 int type = L3HDR(struct icmp, ip)->icmp_type;
246 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
251 * The following checks use two arrays of 8 or 16 bits to store the
252 * bits that we want set or clear, respectively. They are in the
253 * low and high half of cmd->arg1 or cmd->d[0].
255 * We scan options and store the bits we find set. We succeed if
257 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
259 * The code is sometimes optimized not to store additional variables.
263 flags_match(ipfw_insn *cmd, u_int8_t bits)
268 if ( ((cmd->arg1 & 0xff) & bits) != 0)
269 return 0; /* some bits we want set were clear */
270 want_clear = (cmd->arg1 >> 8) & 0xff;
271 if ( (want_clear & bits) != want_clear)
272 return 0; /* some bits we want clear were set */
277 ipopts_match(struct ip *ip, ipfw_insn *cmd)
279 int optlen, bits = 0;
280 u_char *cp = (u_char *)(ip + 1);
281 int x = (ip->ip_hl << 2) - sizeof (struct ip);
283 for (; x > 0; x -= optlen, cp += optlen) {
284 int opt = cp[IPOPT_OPTVAL];
286 if (opt == IPOPT_EOL)
288 if (opt == IPOPT_NOP)
291 optlen = cp[IPOPT_OLEN];
292 if (optlen <= 0 || optlen > x)
293 return 0; /* invalid or truncated */
301 bits |= IP_FW_IPOPT_LSRR;
305 bits |= IP_FW_IPOPT_SSRR;
309 bits |= IP_FW_IPOPT_RR;
313 bits |= IP_FW_IPOPT_TS;
317 return (flags_match(cmd, bits));
321 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
323 int optlen, bits = 0;
324 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
325 u_char *cp = (u_char *)(tcp + 1);
326 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
328 for (; x > 0; x -= optlen, cp += optlen) {
330 if (opt == TCPOPT_EOL)
332 if (opt == TCPOPT_NOP)
346 bits |= IP_FW_TCPOPT_MSS;
350 bits |= IP_FW_TCPOPT_WINDOW;
353 case TCPOPT_SACK_PERMITTED:
355 bits |= IP_FW_TCPOPT_SACK;
358 case TCPOPT_TIMESTAMP:
359 bits |= IP_FW_TCPOPT_TS;
365 bits |= IP_FW_TCPOPT_CC;
369 return (flags_match(cmd, bits));
373 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
375 if (ifp == NULL) /* no iface with this packet, match fails */
377 /* Check by name or by IP address */
378 if (cmd->name[0] != '\0') { /* match by name */
379 /* Check unit number (-1 is wildcard) */
380 if (cmd->p.unit != -1 && cmd->p.unit != ifp->if_unit)
383 if (!strncmp(ifp->if_name, cmd->name, IFNAMSIZ))
388 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
389 if (ia->ifa_addr == NULL)
391 if (ia->ifa_addr->sa_family != AF_INET)
393 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
394 (ia->ifa_addr))->sin_addr.s_addr)
395 return(1); /* match */
398 return(0); /* no match, fail ... */
401 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
403 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
404 #define SNP(buf) buf, sizeof(buf)
407 * We enter here when we have a rule with O_LOG.
408 * XXX this function alone takes about 2Kbytes of code!
411 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
412 struct mbuf *m, struct ifnet *oif)
415 int limit_reached = 0;
416 char action2[40], proto[48], fragment[28];
421 if (f == NULL) { /* bogus pkt */
422 if (verbose_limit != 0 && norule_counter >= verbose_limit)
425 if (norule_counter == verbose_limit)
426 limit_reached = verbose_limit;
428 } else { /* O_LOG is the first action, find the real one */
429 ipfw_insn *cmd = ACTION_PTR(f);
430 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
432 if (l->max_log != 0 && l->log_left == 0)
435 if (l->log_left == 0)
436 limit_reached = l->max_log;
437 cmd += F_LEN(cmd); /* point to first action */
438 if (cmd->opcode == O_PROB)
442 switch (cmd->opcode) {
448 if (cmd->arg1==ICMP_REJECT_RST)
450 else if (cmd->arg1==ICMP_UNREACH_HOST)
453 snprintf(SNPARGS(action2, 0), "Unreach %d",
464 snprintf(SNPARGS(action2, 0), "Divert %d",
468 snprintf(SNPARGS(action2, 0), "Tee %d",
472 snprintf(SNPARGS(action2, 0), "SkipTo %d",
476 snprintf(SNPARGS(action2, 0), "Pipe %d",
480 snprintf(SNPARGS(action2, 0), "Queue %d",
484 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
487 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
488 inet_ntoa(sa->sa.sin_addr));
490 snprintf(SNPARGS(action2, len), ":%d",
500 if (hlen == 0) { /* non-ip */
501 snprintf(SNPARGS(proto, 0), "MAC");
503 struct ip *ip = mtod(m, struct ip *);
504 /* these three are all aliases to the same thing */
505 struct icmp *const icmp = L3HDR(struct icmp, ip);
506 struct tcphdr *const tcp = (struct tcphdr *)icmp;
507 struct udphdr *const udp = (struct udphdr *)icmp;
509 int ip_off, offset, ip_len;
513 if (eh != NULL) { /* layer 2 packets are as on the wire */
514 ip_off = ntohs(ip->ip_off);
515 ip_len = ntohs(ip->ip_len);
520 offset = ip_off & IP_OFFMASK;
523 len = snprintf(SNPARGS(proto, 0), "TCP %s",
524 inet_ntoa(ip->ip_src));
526 snprintf(SNPARGS(proto, len), ":%d %s:%d",
527 ntohs(tcp->th_sport),
528 inet_ntoa(ip->ip_dst),
529 ntohs(tcp->th_dport));
531 snprintf(SNPARGS(proto, len), " %s",
532 inet_ntoa(ip->ip_dst));
536 len = snprintf(SNPARGS(proto, 0), "UDP %s",
537 inet_ntoa(ip->ip_src));
539 snprintf(SNPARGS(proto, len), ":%d %s:%d",
540 ntohs(udp->uh_sport),
541 inet_ntoa(ip->ip_dst),
542 ntohs(udp->uh_dport));
544 snprintf(SNPARGS(proto, len), " %s",
545 inet_ntoa(ip->ip_dst));
550 len = snprintf(SNPARGS(proto, 0),
552 icmp->icmp_type, icmp->icmp_code);
554 len = snprintf(SNPARGS(proto, 0), "ICMP ");
555 len += snprintf(SNPARGS(proto, len), "%s",
556 inet_ntoa(ip->ip_src));
557 snprintf(SNPARGS(proto, len), " %s",
558 inet_ntoa(ip->ip_dst));
562 len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
563 inet_ntoa(ip->ip_src));
564 snprintf(SNPARGS(proto, len), " %s",
565 inet_ntoa(ip->ip_dst));
569 if (ip_off & (IP_MF | IP_OFFMASK))
570 snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
571 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
573 (ip_off & IP_MF) ? "+" : "");
575 if (oif || m->m_pkthdr.rcvif)
576 log(LOG_SECURITY | LOG_INFO,
577 "ipfw: %d %s %s %s via %s%d%s\n",
579 action, proto, oif ? "out" : "in",
580 oif ? oif->if_name : m->m_pkthdr.rcvif->if_name,
581 oif ? oif->if_unit : m->m_pkthdr.rcvif->if_unit,
584 log(LOG_SECURITY | LOG_INFO,
585 "ipfw: %d %s %s [no if info]%s\n",
587 action, proto, fragment);
589 log(LOG_SECURITY | LOG_NOTICE,
590 "ipfw: limit %d reached on entry %d\n",
591 limit_reached, f ? f->rulenum : -1);
595 * IMPORTANT: the hash function for dynamic rules must be commutative
596 * in source and destination (ip,port), because rules are bidirectional
597 * and we want to find both in the same bucket.
600 hash_packet(struct ipfw_flow_id *id)
604 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
605 i &= (curr_dyn_buckets - 1);
610 * unlink a dynamic rule from a chain. prev is a pointer to
611 * the previous one, q is a pointer to the rule to delete,
612 * head is a pointer to the head of the queue.
613 * Modifies q and potentially also head.
615 #define UNLINK_DYN_RULE(prev, head, q) { \
616 ipfw_dyn_rule *old_q = q; \
618 /* remove a refcount to the parent */ \
619 if (q->dyn_type == O_LIMIT) \
620 q->parent->count--; \
621 DEB(printf("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
622 (q->id.src_ip), (q->id.src_port), \
623 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
625 prev->next = q = q->next; \
627 head = q = q->next; \
629 free(old_q, M_IPFW); }
631 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
634 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
636 * If keep_me == NULL, rules are deleted even if not expired,
637 * otherwise only expired rules are removed.
639 * The value of the second parameter is also used to point to identify
640 * a rule we absolutely do not want to remove (e.g. because we are
641 * holding a reference to it -- this is the case with O_LIMIT_PARENT
642 * rules). The pointer is only used for comparison, so any non-null
646 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
648 static u_int32_t last_remove = 0;
650 #define FORCE (keep_me == NULL)
652 ipfw_dyn_rule *prev, *q;
653 int i, pass = 0, max_pass = 0;
655 if (ipfw_dyn_v == NULL || dyn_count == 0)
657 /* do not expire more than once per second, it is useless */
658 if (!FORCE && last_remove == time_second)
660 last_remove = time_second;
663 * because O_LIMIT refer to parent rules, during the first pass only
664 * remove child and mark any pending LIMIT_PARENT, and remove
665 * them in a second pass.
668 for (i = 0 ; i < curr_dyn_buckets ; i++) {
669 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
671 * Logic can become complex here, so we split tests.
675 if (rule != NULL && rule != q->rule)
676 goto next; /* not the one we are looking for */
677 if (q->dyn_type == O_LIMIT_PARENT) {
679 * handle parent in the second pass,
680 * record we need one.
685 if (FORCE && q->count != 0 ) {
686 /* XXX should not happen! */
687 printf( "OUCH! cannot remove rule,"
688 " count %d\n", q->count);
692 !TIME_LEQ( q->expire, time_second ))
695 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
702 if (pass++ < max_pass)
708 * lookup a dynamic rule.
710 static ipfw_dyn_rule *
711 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
715 * stateful ipfw extensions.
716 * Lookup into dynamic session queue
718 #define MATCH_REVERSE 0
719 #define MATCH_FORWARD 1
721 #define MATCH_UNKNOWN 3
722 int i, dir = MATCH_NONE;
723 ipfw_dyn_rule *prev, *q=NULL;
725 if (ipfw_dyn_v == NULL)
726 goto done; /* not found */
727 i = hash_packet( pkt );
728 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
729 if (q->dyn_type == O_LIMIT_PARENT)
731 if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
732 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
735 if ( pkt->proto == q->id.proto) {
736 if (pkt->src_ip == q->id.src_ip &&
737 pkt->dst_ip == q->id.dst_ip &&
738 pkt->src_port == q->id.src_port &&
739 pkt->dst_port == q->id.dst_port ) {
743 if (pkt->src_ip == q->id.dst_ip &&
744 pkt->dst_ip == q->id.src_ip &&
745 pkt->src_port == q->id.dst_port &&
746 pkt->dst_port == q->id.src_port ) {
756 goto done; /* q = NULL, not found */
758 if ( prev != NULL) { /* found and not in front */
759 prev->next = q->next;
760 q->next = ipfw_dyn_v[i];
763 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
764 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
766 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
767 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
768 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
770 case TH_SYN: /* opening */
771 q->expire = time_second + dyn_syn_lifetime;
774 case BOTH_SYN: /* move to established */
775 case BOTH_SYN | TH_FIN : /* one side tries to close */
776 case BOTH_SYN | (TH_FIN << 8) :
778 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
779 u_int32_t ack = ntohl(tcp->th_ack);
780 if (dir == MATCH_FORWARD) {
781 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
783 else { /* ignore out-of-sequence */
787 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
789 else { /* ignore out-of-sequence */
794 q->expire = time_second + dyn_ack_lifetime;
797 case BOTH_SYN | BOTH_FIN: /* both sides closed */
798 if (dyn_fin_lifetime >= dyn_keepalive_period)
799 dyn_fin_lifetime = dyn_keepalive_period - 1;
800 q->expire = time_second + dyn_fin_lifetime;
806 * reset or some invalid combination, but can also
807 * occur if we use keep-state the wrong way.
809 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
810 printf("invalid state: 0x%x\n", q->state);
812 if (dyn_rst_lifetime >= dyn_keepalive_period)
813 dyn_rst_lifetime = dyn_keepalive_period - 1;
814 q->expire = time_second + dyn_rst_lifetime;
817 } else if (pkt->proto == IPPROTO_UDP) {
818 q->expire = time_second + dyn_udp_lifetime;
820 /* other protocols */
821 q->expire = time_second + dyn_short_lifetime;
825 *match_direction = dir;
830 realloc_dynamic_table(void)
833 * Try reallocation, make sure we have a power of 2 and do
834 * not allow more than 64k entries. In case of overflow,
838 if (dyn_buckets > 65536)
840 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
841 dyn_buckets = curr_dyn_buckets; /* reset */
844 curr_dyn_buckets = dyn_buckets;
845 if (ipfw_dyn_v != NULL)
846 free(ipfw_dyn_v, M_IPFW);
848 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
849 M_IPFW, M_NOWAIT | M_ZERO);
850 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
852 curr_dyn_buckets /= 2;
857 * Install state of type 'type' for a dynamic session.
858 * The hash table contains two type of rules:
859 * - regular rules (O_KEEP_STATE)
860 * - rules for sessions with limited number of sess per user
861 * (O_LIMIT). When they are created, the parent is
862 * increased by 1, and decreased on delete. In this case,
863 * the third parameter is the parent rule and not the chain.
864 * - "parent" rules for the above (O_LIMIT_PARENT).
866 static ipfw_dyn_rule *
867 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
872 if (ipfw_dyn_v == NULL ||
873 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
874 realloc_dynamic_table();
875 if (ipfw_dyn_v == NULL)
876 return NULL; /* failed ! */
880 r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
882 printf ("sorry cannot allocate state\n");
886 /* increase refcount on parent, and set pointer */
887 if (dyn_type == O_LIMIT) {
888 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
889 if ( parent->dyn_type != O_LIMIT_PARENT)
890 panic("invalid parent");
897 r->expire = time_second + dyn_syn_lifetime;
899 r->dyn_type = dyn_type;
900 r->pcnt = r->bcnt = 0;
904 r->next = ipfw_dyn_v[i];
907 DEB(printf("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
909 (r->id.src_ip), (r->id.src_port),
910 (r->id.dst_ip), (r->id.dst_port),
916 * lookup dynamic parent rule using pkt and rule as search keys.
917 * If the lookup fails, then install one.
919 static ipfw_dyn_rule *
920 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
926 i = hash_packet( pkt );
927 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
928 if (q->dyn_type == O_LIMIT_PARENT &&
930 pkt->proto == q->id.proto &&
931 pkt->src_ip == q->id.src_ip &&
932 pkt->dst_ip == q->id.dst_ip &&
933 pkt->src_port == q->id.src_port &&
934 pkt->dst_port == q->id.dst_port) {
935 q->expire = time_second + dyn_short_lifetime;
936 DEB(printf("lookup_dyn_parent found 0x%p\n",q);)
940 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
944 * Install dynamic state for rule type cmd->o.opcode
946 * Returns 1 (failure) if state is not installed because of errors or because
947 * session limitations are enforced.
950 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
951 struct ip_fw_args *args)
957 DEB(printf("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
959 (args->f_id.src_ip), (args->f_id.src_port),
960 (args->f_id.dst_ip), (args->f_id.dst_port) );)
962 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
964 if (q != NULL) { /* should never occur */
965 if (last_log != time_second) {
966 last_log = time_second;
967 printf(" install_state: entry already present, done\n");
972 if (dyn_count >= dyn_max)
974 * Run out of slots, try to remove any expired rule.
976 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
978 if (dyn_count >= dyn_max) {
979 if (last_log != time_second) {
980 last_log = time_second;
981 printf("install_state: Too many dynamic rules\n");
983 return 1; /* cannot install, notify caller */
986 switch (cmd->o.opcode) {
987 case O_KEEP_STATE: /* bidir rule */
988 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
991 case O_LIMIT: /* limit number of sessions */
993 u_int16_t limit_mask = cmd->limit_mask;
994 struct ipfw_flow_id id;
995 ipfw_dyn_rule *parent;
997 DEB(printf("installing dyn-limit rule %d\n", cmd->conn_limit);)
999 id.dst_ip = id.src_ip = 0;
1000 id.dst_port = id.src_port = 0;
1001 id.proto = args->f_id.proto;
1003 if (limit_mask & DYN_SRC_ADDR)
1004 id.src_ip = args->f_id.src_ip;
1005 if (limit_mask & DYN_DST_ADDR)
1006 id.dst_ip = args->f_id.dst_ip;
1007 if (limit_mask & DYN_SRC_PORT)
1008 id.src_port = args->f_id.src_port;
1009 if (limit_mask & DYN_DST_PORT)
1010 id.dst_port = args->f_id.dst_port;
1011 parent = lookup_dyn_parent(&id, rule);
1012 if (parent == NULL) {
1013 printf("add parent failed\n");
1016 if (parent->count >= cmd->conn_limit) {
1018 * See if we can remove some expired rule.
1020 remove_dyn_rule(rule, parent);
1021 if (parent->count >= cmd->conn_limit) {
1022 if (fw_verbose && last_log != time_second) {
1023 last_log = time_second;
1024 log(LOG_SECURITY | LOG_DEBUG,
1025 "drop session, too many entries\n");
1030 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1034 printf("unknown dynamic rule type %u\n", cmd->o.opcode);
1037 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1042 * Transmit a TCP packet, containing either a RST or a keepalive.
1043 * When flags & TH_RST, we are sending a RST packet, because of a
1044 * "reset" action matched the packet.
1045 * Otherwise we are sending a keepalive, and flags & TH_
1048 send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1053 struct route sro; /* fake route */
1055 MGETHDR(m, M_DONTWAIT, MT_HEADER);
1058 m->m_pkthdr.rcvif = (struct ifnet *)0;
1059 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1060 m->m_data += max_linkhdr;
1062 ip = mtod(m, struct ip *);
1063 bzero(ip, m->m_len);
1064 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1065 ip->ip_p = IPPROTO_TCP;
1068 * Assume we are sending a RST (or a keepalive in the reverse
1069 * direction), swap src and destination addresses and ports.
1071 ip->ip_src.s_addr = htonl(id->dst_ip);
1072 ip->ip_dst.s_addr = htonl(id->src_ip);
1073 tcp->th_sport = htons(id->dst_port);
1074 tcp->th_dport = htons(id->src_port);
1075 if (flags & TH_RST) { /* we are sending a RST */
1076 if (flags & TH_ACK) {
1077 tcp->th_seq = htonl(ack);
1078 tcp->th_ack = htonl(0);
1079 tcp->th_flags = TH_RST;
1083 tcp->th_seq = htonl(0);
1084 tcp->th_ack = htonl(seq);
1085 tcp->th_flags = TH_RST | TH_ACK;
1089 * We are sending a keepalive. flags & TH_SYN determines
1090 * the direction, forward if set, reverse if clear.
1091 * NOTE: seq and ack are always assumed to be correct
1092 * as set by the caller. This may be confusing...
1094 if (flags & TH_SYN) {
1096 * we have to rewrite the correct addresses!
1098 ip->ip_dst.s_addr = htonl(id->dst_ip);
1099 ip->ip_src.s_addr = htonl(id->src_ip);
1100 tcp->th_dport = htons(id->dst_port);
1101 tcp->th_sport = htons(id->src_port);
1103 tcp->th_seq = htonl(seq);
1104 tcp->th_ack = htonl(ack);
1105 tcp->th_flags = TH_ACK;
1108 * set ip_len to the payload size so we can compute
1109 * the tcp checksum on the pseudoheader
1110 * XXX check this, could save a couple of words ?
1112 ip->ip_len = htons(sizeof(struct tcphdr));
1113 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1115 * now fill fields left out earlier
1117 ip->ip_ttl = ip_defttl;
1118 ip->ip_len = m->m_pkthdr.len;
1119 bzero (&sro, sizeof (sro));
1120 ip_rtaddr(ip->ip_dst, &sro);
1121 m->m_flags |= M_SKIP_FIREWALL;
1122 ip_output(m, NULL, &sro, 0, NULL, NULL);
1128 * sends a reject message, consuming the mbuf passed as an argument.
1131 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1134 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1135 /* We need the IP header in host order for icmp_error(). */
1136 if (args->eh != NULL) {
1137 struct ip *ip = mtod(args->m, struct ip *);
1138 ip->ip_len = ntohs(ip->ip_len);
1139 ip->ip_off = ntohs(ip->ip_off);
1141 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1142 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1143 struct tcphdr *const tcp =
1144 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1145 if ( (tcp->th_flags & TH_RST) == 0)
1146 send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1148 tcp->th_flags | TH_RST);
1157 * Given an ip_fw *, lookup_next_rule will return a pointer
1158 * to the next rule, which can be either the jump
1159 * target (for skipto instructions) or the next one in the list (in
1160 * all other cases including a missing jump target).
1161 * The result is also written in the "next_rule" field of the rule.
1162 * Backward jumps are not allowed, so start looking from the next
1165 * This never returns NULL -- in case we do not have an exact match,
1166 * the next rule is returned. When the ruleset is changed,
1167 * pointers are flushed so we are always correct.
1170 static struct ip_fw *
1171 lookup_next_rule(struct ip_fw *me)
1173 struct ip_fw *rule = NULL;
1176 /* look for action, in case it is a skipto */
1177 cmd = ACTION_PTR(me);
1178 if (cmd->opcode == O_LOG)
1180 if ( cmd->opcode == O_SKIPTO )
1181 for (rule = me->next; rule ; rule = rule->next)
1182 if (rule->rulenum >= cmd->arg1)
1184 if (rule == NULL) /* failure or not a skipto */
1186 me->next_rule = rule;
1191 * The main check routine for the firewall.
1193 * All arguments are in args so we can modify them and return them
1194 * back to the caller.
1198 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1199 * Starts with the IP header.
1200 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1201 * args->oif Outgoing interface, or NULL if packet is incoming.
1202 * The incoming interface is in the mbuf. (in)
1203 * args->divert_rule (in/out)
1204 * Skip up to the first rule past this rule number;
1205 * upon return, non-zero port number for divert or tee.
1207 * args->rule Pointer to the last matching rule (in/out)
1208 * args->next_hop Socket we are forwarding to (out).
1209 * args->f_id Addresses grabbed from the packet (out)
1213 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1214 * 0 The packet is to be accepted and routed normally OR
1215 * the packet was denied/rejected and has been dropped;
1216 * in the latter case, *m is equal to NULL upon return.
1217 * port Divert the packet to port, with these caveats:
1219 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1220 * of diverting it (ie, 'ipfw tee').
1222 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1223 * 16 bits as a dummynet pipe number instead of diverting
1227 ipfw_chk(struct ip_fw_args *args)
1230 * Local variables hold state during the processing of a packet.
1232 * IMPORTANT NOTE: to speed up the processing of rules, there
1233 * are some assumption on the values of the variables, which
1234 * are documented here. Should you change them, please check
1235 * the implementation of the various instructions to make sure
1236 * that they still work.
1238 * args->eh The MAC header. It is non-null for a layer2
1239 * packet, it is NULL for a layer-3 packet.
1241 * m | args->m Pointer to the mbuf, as received from the caller.
1242 * It may change if ipfw_chk() does an m_pullup, or if it
1243 * consumes the packet because it calls send_reject().
1244 * XXX This has to change, so that ipfw_chk() never modifies
1245 * or consumes the buffer.
1246 * ip is simply an alias of the value of m, and it is kept
1247 * in sync with it (the packet is supposed to start with
1250 struct mbuf *m = args->m;
1251 struct ip *ip = mtod(m, struct ip *);
1254 * oif | args->oif If NULL, ipfw_chk has been called on the
1255 * inbound path (ether_input, bdg_forward, ip_input).
1256 * If non-NULL, ipfw_chk has been called on the outbound path
1257 * (ether_output, ip_output).
1259 struct ifnet *oif = args->oif;
1261 struct ip_fw *f = NULL; /* matching rule */
1265 * hlen The length of the IPv4 header.
1266 * hlen >0 means we have an IPv4 packet.
1268 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1271 * offset The offset of a fragment. offset != 0 means that
1272 * we have a fragment at this offset of an IPv4 packet.
1273 * offset == 0 means that (if this is an IPv4 packet)
1274 * this is the first or only fragment.
1279 * Local copies of addresses. They are only valid if we have
1282 * proto The protocol. Set to 0 for non-ip packets,
1283 * or to the protocol read from the packet otherwise.
1284 * proto != 0 means that we have an IPv4 packet.
1286 * src_port, dst_port port numbers, in HOST format. Only
1287 * valid for TCP and UDP packets.
1289 * src_ip, dst_ip ip addresses, in NETWORK format.
1290 * Only valid for IPv4 packets.
1293 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1294 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1296 int dyn_dir = MATCH_UNKNOWN;
1297 ipfw_dyn_rule *q = NULL;
1299 if (m->m_flags & M_SKIP_FIREWALL)
1300 return 0; /* accept */
1302 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1303 * MATCH_NONE when checked and not matched (q = NULL),
1304 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1307 if (args->eh == NULL || /* layer 3 packet */
1308 ( m->m_pkthdr.len >= sizeof(struct ip) &&
1309 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1310 hlen = ip->ip_hl << 2;
1313 * Collect parameters into local variables for faster matching.
1315 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1316 proto = args->f_id.proto = 0; /* mark f_id invalid */
1317 goto after_ip_checks;
1320 proto = args->f_id.proto = ip->ip_p;
1321 src_ip = ip->ip_src;
1322 dst_ip = ip->ip_dst;
1323 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1324 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1325 ip_len = ntohs(ip->ip_len);
1327 offset = ip->ip_off & IP_OFFMASK;
1328 ip_len = ip->ip_len;
1331 #define PULLUP_TO(len) \
1333 if ((m)->m_len < (len)) { \
1334 args->m = m = m_pullup(m, (len)); \
1336 goto pullup_failed; \
1337 ip = mtod(m, struct ip *); \
1347 PULLUP_TO(hlen + sizeof(struct tcphdr));
1348 tcp = L3HDR(struct tcphdr, ip);
1349 dst_port = tcp->th_dport;
1350 src_port = tcp->th_sport;
1351 args->f_id.flags = tcp->th_flags;
1359 PULLUP_TO(hlen + sizeof(struct udphdr));
1360 udp = L3HDR(struct udphdr, ip);
1361 dst_port = udp->uh_dport;
1362 src_port = udp->uh_sport;
1367 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1368 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1377 args->f_id.src_ip = ntohl(src_ip.s_addr);
1378 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1379 args->f_id.src_port = src_port = ntohs(src_port);
1380 args->f_id.dst_port = dst_port = ntohs(dst_port);
1385 * Packet has already been tagged. Look for the next rule
1386 * to restart processing.
1388 * If fw_one_pass != 0 then just accept it.
1389 * XXX should not happen here, but optimized out in
1395 f = args->rule->next_rule;
1397 f = lookup_next_rule(args->rule);
1400 * Find the starting rule. It can be either the first
1401 * one, or the one after divert_rule if asked so.
1403 int skipto = args->divert_rule;
1406 if (args->eh == NULL && skipto != 0) {
1407 if (skipto >= IPFW_DEFAULT_RULE)
1408 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1409 while (f && f->rulenum <= skipto)
1411 if (f == NULL) /* drop packet */
1412 return(IP_FW_PORT_DENY_FLAG);
1415 args->divert_rule = 0; /* reset to avoid confusion later */
1418 * Now scan the rules, and parse microinstructions for each rule.
1420 for (; f; f = f->next) {
1423 int skip_or; /* skip rest of OR block */
1426 if (set_disable & (1 << f->set) )
1430 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1431 l -= cmdlen, cmd += cmdlen) {
1435 * check_body is a jump target used when we find a
1436 * CHECK_STATE, and need to jump to the body of
1441 cmdlen = F_LEN(cmd);
1443 * An OR block (insn_1 || .. || insn_n) has the
1444 * F_OR bit set in all but the last instruction.
1445 * The first match will set "skip_or", and cause
1446 * the following instructions to be skipped until
1447 * past the one with the F_OR bit clear.
1449 if (skip_or) { /* skip this instruction */
1450 if ((cmd->len & F_OR) == 0)
1451 skip_or = 0; /* next one is good */
1454 match = 0; /* set to 1 if we succeed */
1456 switch (cmd->opcode) {
1458 * The first set of opcodes compares the packet's
1459 * fields with some pattern, setting 'match' if a
1460 * match is found. At the end of the loop there is
1461 * logic to deal with F_NOT and F_OR flags associated
1469 printf("ipfw: opcode %d unimplemented\n",
1476 * We only check offset == 0 && proto != 0,
1477 * as this ensures that we have an IPv4
1478 * packet with the ports info.
1483 struct inpcbinfo *pi;
1487 if (proto == IPPROTO_TCP) {
1490 } else if (proto == IPPROTO_UDP) {
1497 in_pcblookup_hash(pi,
1498 dst_ip, htons(dst_port),
1499 src_ip, htons(src_port),
1501 in_pcblookup_hash(pi,
1502 src_ip, htons(src_port),
1503 dst_ip, htons(dst_port),
1506 if (pcb == NULL || pcb->inp_socket == NULL)
1508 #if __FreeBSD_version < 500034
1509 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1511 if (cmd->opcode == O_UID) {
1513 !socheckuid(pcb->inp_socket,
1514 (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1516 match = groupmember(
1517 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1518 pcb->inp_socket->so_cred);
1524 match = iface_match(m->m_pkthdr.rcvif,
1525 (ipfw_insn_if *)cmd);
1529 match = iface_match(oif, (ipfw_insn_if *)cmd);
1533 match = iface_match(oif ? oif :
1534 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1538 if (args->eh != NULL) { /* have MAC header */
1539 u_int32_t *want = (u_int32_t *)
1540 ((ipfw_insn_mac *)cmd)->addr;
1541 u_int32_t *mask = (u_int32_t *)
1542 ((ipfw_insn_mac *)cmd)->mask;
1543 u_int32_t *hdr = (u_int32_t *)args->eh;
1546 ( want[0] == (hdr[0] & mask[0]) &&
1547 want[1] == (hdr[1] & mask[1]) &&
1548 want[2] == (hdr[2] & mask[2]) );
1553 if (args->eh != NULL) {
1555 ntohs(args->eh->ether_type);
1557 ((ipfw_insn_u16 *)cmd)->ports;
1560 for (i = cmdlen - 1; !match && i>0;
1562 match = (t>=p[0] && t<=p[1]);
1567 match = (hlen > 0 && offset != 0);
1570 case O_IN: /* "out" is "not in" */
1571 match = (oif == NULL);
1575 match = (args->eh != NULL);
1580 * We do not allow an arg of 0 so the
1581 * check of "proto" only suffices.
1583 match = (proto == cmd->arg1);
1587 match = (hlen > 0 &&
1588 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1593 match = (hlen > 0 &&
1594 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1596 ((ipfw_insn_ip *)cmd)->mask.s_addr));
1603 INADDR_TO_IFP(src_ip, tif);
1604 match = (tif != NULL);
1611 u_int32_t *d = (u_int32_t *)(cmd+1);
1613 cmd->opcode == O_IP_DST_SET ?
1619 addr -= d[0]; /* subtract base */
1620 match = (addr < cmd->arg1) &&
1621 ( d[ 1 + (addr>>5)] &
1622 (1<<(addr & 0x1f)) );
1627 match = (hlen > 0 &&
1628 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1633 match = (hlen > 0) &&
1634 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1636 ((ipfw_insn_ip *)cmd)->mask.s_addr));
1643 INADDR_TO_IFP(dst_ip, tif);
1644 match = (tif != NULL);
1651 * offset == 0 && proto != 0 is enough
1652 * to guarantee that we have an IPv4
1653 * packet with port info.
1655 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1658 (cmd->opcode == O_IP_SRCPORT) ?
1659 src_port : dst_port ;
1661 ((ipfw_insn_u16 *)cmd)->ports;
1664 for (i = cmdlen - 1; !match && i>0;
1666 match = (x>=p[0] && x<=p[1]);
1671 match = (offset == 0 && proto==IPPROTO_ICMP &&
1672 icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
1676 match = (hlen > 0 && ipopts_match(ip, cmd) );
1680 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1684 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1688 match = (hlen > 0 &&
1689 cmd->arg1 == ntohs(ip->ip_id));
1693 match = (hlen > 0 && cmd->arg1 == ip_len);
1696 case O_IPPRECEDENCE:
1697 match = (hlen > 0 &&
1698 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1702 match = (hlen > 0 &&
1703 flags_match(cmd, ip->ip_tos));
1707 match = (proto == IPPROTO_TCP && offset == 0 &&
1709 L3HDR(struct tcphdr,ip)->th_flags));
1713 match = (proto == IPPROTO_TCP && offset == 0 &&
1714 tcpopts_match(ip, cmd));
1718 match = (proto == IPPROTO_TCP && offset == 0 &&
1719 ((ipfw_insn_u32 *)cmd)->d[0] ==
1720 L3HDR(struct tcphdr,ip)->th_seq);
1724 match = (proto == IPPROTO_TCP && offset == 0 &&
1725 ((ipfw_insn_u32 *)cmd)->d[0] ==
1726 L3HDR(struct tcphdr,ip)->th_ack);
1730 match = (proto == IPPROTO_TCP && offset == 0 &&
1732 L3HDR(struct tcphdr,ip)->th_win);
1736 /* reject packets which have SYN only */
1737 /* XXX should i also check for TH_ACK ? */
1738 match = (proto == IPPROTO_TCP && offset == 0 &&
1739 (L3HDR(struct tcphdr,ip)->th_flags &
1740 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1745 ipfw_log(f, hlen, args->eh, m, oif);
1750 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1754 * The second set of opcodes represents 'actions',
1755 * i.e. the terminal part of a rule once the packet
1756 * matches all previous patterns.
1757 * Typically there is only one action for each rule,
1758 * and the opcode is stored at the end of the rule
1759 * (but there are exceptions -- see below).
1761 * In general, here we set retval and terminate the
1762 * outer loop (would be a 'break 3' in some language,
1763 * but we need to do a 'goto done').
1766 * O_COUNT and O_SKIPTO actions:
1767 * instead of terminating, we jump to the next rule
1768 * ('goto next_rule', equivalent to a 'break 2'),
1769 * or to the SKIPTO target ('goto again' after
1770 * having set f, cmd and l), respectively.
1772 * O_LIMIT and O_KEEP_STATE: these opcodes are
1773 * not real 'actions', and are stored right
1774 * before the 'action' part of the rule.
1775 * These opcodes try to install an entry in the
1776 * state tables; if successful, we continue with
1777 * the next opcode (match=1; break;), otherwise
1778 * the packet * must be dropped
1779 * ('goto done' after setting retval);
1781 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1782 * cause a lookup of the state table, and a jump
1783 * to the 'action' part of the parent rule
1784 * ('goto check_body') if an entry is found, or
1785 * (CHECK_STATE only) a jump to the next rule if
1786 * the entry is not found ('goto next_rule').
1787 * The result of the lookup is cached to make
1788 * further instances of these opcodes are
1793 if (install_state(f,
1794 (ipfw_insn_limit *)cmd, args)) {
1795 retval = IP_FW_PORT_DENY_FLAG;
1796 goto done; /* error/limit violation */
1804 * dynamic rules are checked at the first
1805 * keep-state or check-state occurrence,
1806 * with the result being stored in dyn_dir.
1807 * The compiler introduces a PROBE_STATE
1808 * instruction for us when we have a
1809 * KEEP_STATE (because PROBE_STATE needs
1812 if (dyn_dir == MATCH_UNKNOWN &&
1813 (q = lookup_dyn_rule(&args->f_id,
1814 &dyn_dir, proto == IPPROTO_TCP ?
1815 L3HDR(struct tcphdr, ip) : NULL))
1818 * Found dynamic entry, update stats
1819 * and jump to the 'action' part of
1825 cmd = ACTION_PTR(f);
1826 l = f->cmd_len - f->act_ofs;
1830 * Dynamic entry not found. If CHECK_STATE,
1831 * skip to next rule, if PROBE_STATE just
1832 * ignore and continue with next opcode.
1834 if (cmd->opcode == O_CHECK_STATE)
1840 retval = 0; /* accept */
1845 args->rule = f; /* report matching rule */
1846 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
1851 if (args->eh) /* not on layer 2 */
1853 args->divert_rule = f->rulenum;
1854 retval = (cmd->opcode == O_DIVERT) ?
1856 cmd->arg1 | IP_FW_PORT_TEE_FLAG;
1861 f->pcnt++; /* update stats */
1863 f->timestamp = time_second;
1864 if (cmd->opcode == O_COUNT)
1867 if (f->next_rule == NULL)
1868 lookup_next_rule(f);
1874 * Drop the packet and send a reject notice
1875 * if the packet is not ICMP (or is an ICMP
1876 * query), and it is not multicast/broadcast.
1879 (proto != IPPROTO_ICMP ||
1880 is_icmp_query(ip)) &&
1881 !(m->m_flags & (M_BCAST|M_MCAST)) &&
1882 !IN_MULTICAST(dst_ip.s_addr)) {
1883 send_reject(args, cmd->arg1,
1889 retval = IP_FW_PORT_DENY_FLAG;
1893 if (args->eh) /* not valid on layer2 pkts */
1895 if (!q || dyn_dir == MATCH_FORWARD)
1897 &((ipfw_insn_sa *)cmd)->sa;
1902 panic("-- unknown opcode %d\n", cmd->opcode);
1903 } /* end of switch() on opcodes */
1905 if (cmd->len & F_NOT)
1909 if (cmd->len & F_OR)
1912 if (!(cmd->len & F_OR)) /* not an OR block, */
1913 break; /* try next rule */
1916 } /* end of inner for, scan opcodes */
1918 next_rule:; /* try next rule */
1920 } /* end of outer for, scan rules */
1921 printf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
1922 return(IP_FW_PORT_DENY_FLAG);
1925 /* Update statistics */
1928 f->timestamp = time_second;
1933 printf("pullup failed\n");
1934 return(IP_FW_PORT_DENY_FLAG);
1938 * When a rule is added/deleted, clear the next_rule pointers in all rules.
1939 * These will be reconstructed on the fly as packets are matched.
1940 * Must be called at splimp().
1943 flush_rule_ptrs(void)
1947 for (rule = layer3_chain; rule; rule = rule->next)
1948 rule->next_rule = NULL;
1952 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
1953 * pipe/queue, or to all of them (match == NULL).
1954 * Must be called at splimp().
1957 flush_pipe_ptrs(struct dn_flow_set *match)
1961 for (rule = layer3_chain; rule; rule = rule->next) {
1962 ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
1964 if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
1966 if (match == NULL || cmd->pipe_ptr == match)
1967 cmd->pipe_ptr = NULL;
1972 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
1973 * possibly create a rule number and add the rule to the list.
1974 * Update the rule_number in the input struct so the caller knows it as well.
1977 add_rule(struct ip_fw **head, struct ip_fw *input_rule)
1979 struct ip_fw *rule, *f, *prev;
1981 int l = RULESIZE(input_rule);
1983 if (*head == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
1986 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
1990 bcopy(input_rule, rule, l);
1993 rule->next_rule = NULL;
1997 rule->timestamp = 0;
2001 if (*head == NULL) { /* default rule */
2007 * If rulenum is 0, find highest numbered rule before the
2008 * default rule, and add autoinc_step
2010 if (autoinc_step < 1)
2012 else if (autoinc_step > 1000)
2013 autoinc_step = 1000;
2014 if (rule->rulenum == 0) {
2016 * locate the highest numbered rule before default
2018 for (f = *head; f; f = f->next) {
2019 if (f->rulenum == IPFW_DEFAULT_RULE)
2021 rule->rulenum = f->rulenum;
2023 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2024 rule->rulenum += autoinc_step;
2025 input_rule->rulenum = rule->rulenum;
2029 * Now insert the new rule in the right place in the sorted list.
2031 for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2032 if (f->rulenum > rule->rulenum) { /* found the location */
2036 } else { /* head insert */
2048 DEB(printf("++ installed rule %d, static count now %d\n",
2049 rule->rulenum, static_count);)
2054 * Free storage associated with a static rule (including derived
2056 * The caller is in charge of clearing rule pointers to avoid
2057 * dangling pointers.
2058 * @return a pointer to the next entry.
2059 * Arguments are not checked, so they better be correct.
2060 * Must be called at splimp().
2062 static struct ip_fw *
2063 delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2066 int l = RULESIZE(rule);
2069 remove_dyn_rule(rule, NULL /* force removal */);
2077 if (DUMMYNET_LOADED)
2078 ip_dn_ruledel_ptr(rule);
2084 * Deletes all rules from a chain (including the default rule
2085 * if the second argument is set).
2086 * Must be called at splimp().
2089 free_chain(struct ip_fw **chain, int kill_default)
2093 flush_rule_ptrs(); /* more efficient to do outside the loop */
2095 while ( (rule = *chain) != NULL &&
2096 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE) )
2097 delete_rule(chain, NULL, rule);
2101 * Remove all rules with given number, and also do set manipulation.
2103 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2104 * the next 8 bits are the new set, the top 8 bits are the command:
2106 * 0 delete rules with given number
2107 * 1 delete rules with given set number
2108 * 2 move rules with given number to new set
2109 * 3 move rules with given set number to new set
2110 * 4 swap sets with given numbers
2113 del_entry(struct ip_fw **chain, u_int32_t arg)
2115 struct ip_fw *prev, *rule;
2118 u_int8_t cmd, new_set;
2120 rulenum = arg & 0xffff;
2121 cmd = (arg >> 24) & 0xff;
2122 new_set = (arg >> 16) & 0xff;
2128 if (cmd == 0 || cmd == 2) {
2129 if (rulenum == IPFW_DEFAULT_RULE)
2137 case 0: /* delete rules with given number */
2139 * locate first rule to delete
2141 for (prev = NULL, rule = *chain;
2142 rule && rule->rulenum < rulenum;
2143 prev = rule, rule = rule->next)
2145 if (rule->rulenum != rulenum)
2148 s = splimp(); /* no access to rules while removing */
2150 * flush pointers outside the loop, then delete all matching
2151 * rules. prev remains the same throughout the cycle.
2154 while (rule && rule->rulenum == rulenum)
2155 rule = delete_rule(chain, prev, rule);
2159 case 1: /* delete all rules with given set number */
2162 for (prev = NULL, rule = *chain; rule ; )
2163 if (rule->set == rulenum)
2164 rule = delete_rule(chain, prev, rule);
2172 case 2: /* move rules with given number to new set */
2174 for (rule = *chain; rule ; rule = rule->next)
2175 if (rule->rulenum == rulenum)
2176 rule->set = new_set;
2180 case 3: /* move rules with given set number to new set */
2182 for (rule = *chain; rule ; rule = rule->next)
2183 if (rule->set == rulenum)
2184 rule->set = new_set;
2188 case 4: /* swap two sets */
2190 for (rule = *chain; rule ; rule = rule->next)
2191 if (rule->set == rulenum)
2192 rule->set = new_set;
2193 else if (rule->set == new_set)
2194 rule->set = rulenum;
2202 * Clear counters for a specific rule.
2205 clear_counters(struct ip_fw *rule, int log_only)
2207 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2209 if (log_only == 0) {
2210 rule->bcnt = rule->pcnt = 0;
2211 rule->timestamp = 0;
2213 if (l->o.opcode == O_LOG)
2214 l->log_left = l->max_log;
2218 * Reset some or all counters on firewall rules.
2219 * @arg frwl is null to clear all entries, or contains a specific
2221 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2224 zero_entry(int rulenum, int log_only)
2233 for (rule = layer3_chain; rule; rule = rule->next)
2234 clear_counters(rule, log_only);
2236 msg = log_only ? "ipfw: All logging counts reset.\n" :
2237 "ipfw: Accounting cleared.\n";
2241 * We can have multiple rules with the same number, so we
2242 * need to clear them all.
2244 for (rule = layer3_chain; rule; rule = rule->next)
2245 if (rule->rulenum == rulenum) {
2247 while (rule && rule->rulenum == rulenum) {
2248 clear_counters(rule, log_only);
2255 if (!cleared) /* we did not find any matching rules */
2257 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2258 "ipfw: Entry %d cleared.\n";
2261 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2266 * Check validity of the structure before insert.
2267 * Fortunately rules are simple, so this mostly need to check rule sizes.
2270 check_ipfw_struct(struct ip_fw *rule, int size)
2276 if (size < sizeof(*rule)) {
2277 printf("ipfw: rule too short\n");
2280 /* first, check for valid size */
2283 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2287 * Now go for the individual checks. Very simple ones, basically only
2288 * instruction sizes.
2290 for (l = rule->cmd_len, cmd = rule->cmd ;
2291 l > 0 ; l -= cmdlen, cmd += cmdlen) {
2292 cmdlen = F_LEN(cmd);
2294 printf("ipfw: opcode %d size truncated\n",
2298 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2299 switch (cmd->opcode) {
2313 case O_IPPRECEDENCE:
2320 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2332 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2337 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2342 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2345 ((ipfw_insn_log *)cmd)->log_left =
2346 ((ipfw_insn_log *)cmd)->max_log;
2352 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2354 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2355 printf("ipfw: opcode %d, useless rule\n",
2363 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2364 printf("ipfw: invalid set size %d\n",
2368 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2374 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2380 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2381 if (cmdlen < 2 || cmdlen > 31)
2388 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2394 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2399 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2403 case O_FORWARD_MAC: /* XXX not implemented yet */
2412 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2416 printf("ipfw: opcode %d, multiple actions"
2423 printf("ipfw: opcode %d, action must be"
2430 printf("ipfw: opcode %d, unknown opcode\n",
2435 if (have_action == 0) {
2436 printf("ipfw: missing action\n");
2442 printf("ipfw: opcode %d size %d wrong\n",
2443 cmd->opcode, cmdlen);
2449 * {set|get}sockopt parser.
2452 ipfw_ctl(struct sockopt *sopt)
2454 int error, s, rulenum;
2456 struct ip_fw *bp , *buf, *rule;
2458 static u_int32_t rule_buf[255]; /* we copy the data here */
2461 * Disallow modifications in really-really secure mode, but still allow
2462 * the logging counters to be reset.
2464 if (sopt->sopt_name == IP_FW_ADD ||
2465 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
2466 #if __FreeBSD_version >= 500034
2467 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2470 #else /* FreeBSD 4.x */
2471 if (securelevel >= 3)
2478 switch (sopt->sopt_name) {
2481 * pass up a copy of the current rules. Static rules
2482 * come first (the last of which has number IPFW_DEFAULT_RULE),
2483 * followed by a possibly empty list of dynamic rule.
2484 * The last dynamic rule has NULL in the "next" field.
2487 size = static_len; /* size of static rules */
2488 if (ipfw_dyn_v) /* add size of dyn.rules */
2489 size += (dyn_count * sizeof(ipfw_dyn_rule));
2492 * XXX todo: if the user passes a short length just to know
2493 * how much room is needed, do not bother filling up the
2494 * buffer, just jump to the sooptcopyout.
2496 buf = malloc(size, M_TEMP, M_WAITOK);
2504 for (rule = layer3_chain; rule ; rule = rule->next) {
2505 int i = RULESIZE(rule);
2508 * abuse 'next_rule' to store the set_disable word
2510 (u_int32_t)(((struct ip_fw *)bp)->next_rule) =
2512 bp = (struct ip_fw *)((char *)bp + i);
2516 ipfw_dyn_rule *p, *dst, *last = NULL;
2518 dst = (ipfw_dyn_rule *)bp;
2519 for (i = 0 ; i < curr_dyn_buckets ; i++ )
2520 for ( p = ipfw_dyn_v[i] ; p != NULL ;
2521 p = p->next, dst++ ) {
2522 bcopy(p, dst, sizeof *p);
2523 (int)dst->rule = p->rule->rulenum ;
2525 * store a non-null value in "next".
2526 * The userland code will interpret a
2527 * NULL here as a marker
2528 * for the last dynamic rule.
2533 TIME_LEQ(dst->expire, time_second) ?
2534 0 : dst->expire - time_second ;
2536 if (last != NULL) /* mark last dynamic rule */
2541 error = sooptcopyout(sopt, buf, size);
2547 * Normally we cannot release the lock on each iteration.
2548 * We could do it here only because we start from the head all
2549 * the times so there is no risk of missing some entries.
2550 * On the other hand, the risk is that we end up with
2551 * a very inconsistent ruleset, so better keep the lock
2552 * around the whole cycle.
2554 * XXX this code can be improved by resetting the head of
2555 * the list to point to the default rule, and then freeing
2556 * the old list without the need for a lock.
2560 free_chain(&layer3_chain, 0 /* keep default rule */);
2565 rule = (struct ip_fw *)rule_buf; /* XXX do a malloc */
2566 error = sooptcopyin(sopt, rule, sizeof(rule_buf),
2567 sizeof(struct ip_fw) );
2568 size = sopt->sopt_valsize;
2569 if (error || (error = check_ipfw_struct(rule, size)))
2572 error = add_rule(&layer3_chain, rule);
2573 size = RULESIZE(rule);
2574 if (!error && sopt->sopt_dir == SOPT_GET)
2575 error = sooptcopyout(sopt, rule, size);
2580 * IP_FW_DEL is used for deleting single rules or sets,
2581 * and (ab)used to atomically manipulate sets. Argument size
2582 * is used to distinguish between the two:
2584 * delete single rule or set of rules,
2585 * or reassign rules (or sets) to a different set.
2586 * 2*sizeof(u_int32_t)
2587 * atomic disable/enable sets.
2588 * first u_int32_t contains sets to be disabled,
2589 * second u_int32_t contains sets to be enabled.
2591 error = sooptcopyin(sopt, rule_buf,
2592 2*sizeof(u_int32_t), sizeof(u_int32_t));
2595 size = sopt->sopt_valsize;
2596 if (size == sizeof(u_int32_t)) /* delete or reassign */
2597 error = del_entry(&layer3_chain, rule_buf[0]);
2598 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
2600 (set_disable | rule_buf[0]) & ~rule_buf[1] &
2601 ~(1<<31); /* set 31 always enabled */
2607 case IP_FW_RESETLOG: /* argument is an int, the rule number */
2610 if (sopt->sopt_val != 0) {
2611 error = sooptcopyin(sopt, &rulenum,
2612 sizeof(int), sizeof(int));
2616 error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
2620 printf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
2628 * dummynet needs a reference to the default rule, because rules can be
2629 * deleted while packets hold a reference to them. When this happens,
2630 * dummynet changes the reference to the default rule (it could well be a
2631 * NULL pointer, but this way we do not need to check for the special
2632 * case, plus here he have info on the default behaviour).
2634 struct ip_fw *ip_fw_default_rule;
2637 * This procedure is only used to handle keepalives. It is invoked
2638 * every dyn_keepalive_period
2641 ipfw_tick(void * __unused unused)
2647 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2651 for (i = 0 ; i < curr_dyn_buckets ; i++) {
2652 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
2653 if (q->dyn_type == O_LIMIT_PARENT)
2655 if (q->id.proto != IPPROTO_TCP)
2657 if ( (q->state & BOTH_SYN) != BOTH_SYN)
2659 if (TIME_LEQ( time_second+dyn_keepalive_interval,
2661 continue; /* too early */
2662 if (TIME_LEQ(q->expire, time_second))
2663 continue; /* too late, rule expired */
2665 send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
2666 send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
2671 ipfw_timeout_h = timeout(ipfw_tick, NULL, dyn_keepalive_period*hz);
2677 struct ip_fw default_rule;
2679 ip_fw_chk_ptr = ipfw_chk;
2680 ip_fw_ctl_ptr = ipfw_ctl;
2681 layer3_chain = NULL;
2683 bzero(&default_rule, sizeof default_rule);
2685 default_rule.act_ofs = 0;
2686 default_rule.rulenum = IPFW_DEFAULT_RULE;
2687 default_rule.cmd_len = 1;
2688 default_rule.set = 31;
2690 default_rule.cmd[0].len = 1;
2691 default_rule.cmd[0].opcode =
2692 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2697 add_rule(&layer3_chain, &default_rule);
2699 ip_fw_default_rule = layer3_chain;
2700 printf("ipfw2 initialized, divert %s, "
2701 "rule-based forwarding enabled, default to %s, logging ",
2707 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
2709 #ifdef IPFIREWALL_VERBOSE
2712 #ifdef IPFIREWALL_VERBOSE_LIMIT
2713 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2715 if (fw_verbose == 0)
2716 printf("disabled\n");
2717 else if (verbose_limit == 0)
2718 printf("unlimited\n");
2720 printf("limited to %d packets/entry by default\n",
2722 bzero(&ipfw_timeout_h, sizeof(struct callout_handle));
2723 ipfw_timeout_h = timeout(ipfw_tick, NULL, hz);
2727 ipfw_modevent(module_t mod, int type, void *unused)
2737 printf("IP firewall already loaded\n");
2746 #if !defined(KLD_MODULE)
2747 printf("ipfw statically compiled, cannot unload\n");
2751 untimeout(ipfw_tick, NULL, ipfw_timeout_h);
2752 ip_fw_chk_ptr = NULL;
2753 ip_fw_ctl_ptr = NULL;
2754 free_chain(&layer3_chain, 1 /* kill default rule */);
2756 printf("IP firewall unloaded\n");
2765 static moduledata_t ipfwmod = {
2770 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2771 MODULE_VERSION(ipfw, 1);