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