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