ip_state.c revision 89316
1/*
2 * Copyright (C) 1995-2001 by Darren Reed.
3 *
4 * See the IPFILTER.LICENCE file for details on licencing.
5 */
6
7#include <sys/errno.h>
8#include <sys/types.h>
9#include <sys/param.h>
10#if (__FreeBSD_version >= 500028)
11#include <sys/queue.h>
12#endif
13#include <sys/file.h>
14#if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
15    defined(_KERNEL)
16# include "opt_ipfilter_log.h"
17#endif
18#if defined(_KERNEL) && defined(__FreeBSD_version) && \
19    (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
20#include "opt_inet6.h"
21#endif
22#if !defined(_KERNEL) && !defined(KERNEL) && !defined(__KERNEL__)
23# include <stdio.h>
24# include <stdlib.h>
25# include <string.h>
26#else
27# ifdef linux
28#  include <linux/kernel.h>
29#  include <linux/module.h>
30# endif
31#endif
32#if (defined(KERNEL) || defined(_KERNEL)) && (__FreeBSD_version >= 220000)
33# include <sys/filio.h>
34# include <sys/fcntl.h>
35# if (__FreeBSD_version >= 300000) && !defined(IPFILTER_LKM)
36#  include "opt_ipfilter.h"
37# endif
38#else
39# include <sys/ioctl.h>
40#endif
41#include <sys/time.h>
42#include <sys/uio.h>
43#ifndef linux
44# include <sys/protosw.h>
45#endif
46#include <sys/socket.h>
47#if (defined(_KERNEL) || defined(KERNEL)) && !defined(linux)
48# include <sys/systm.h>
49#endif
50#if !defined(__SVR4) && !defined(__svr4__)
51# ifndef linux
52#  include <sys/mbuf.h>
53# endif
54#else
55# include <sys/filio.h>
56# include <sys/byteorder.h>
57# ifdef _KERNEL
58#  include <sys/dditypes.h>
59# endif
60# include <sys/stream.h>
61# include <sys/kmem.h>
62#endif
63
64#include <net/if.h>
65#ifdef sun
66# include <net/af.h>
67#endif
68#include <net/route.h>
69#include <netinet/in.h>
70#include <netinet/in_systm.h>
71#include <netinet/ip.h>
72#include <netinet/tcp.h>
73#ifndef linux
74# include <netinet/ip_var.h>
75# include <netinet/tcp_fsm.h>
76#endif
77#include <netinet/udp.h>
78#include <netinet/ip_icmp.h>
79#include "netinet/ip_compat.h"
80#include <netinet/tcpip.h>
81#include "netinet/ip_fil.h"
82#include "netinet/ip_nat.h"
83#include "netinet/ip_frag.h"
84#include "netinet/ip_proxy.h"
85#include "netinet/ip_state.h"
86#ifdef	USE_INET6
87#include <netinet/icmp6.h>
88#endif
89#if (__FreeBSD_version >= 300000)
90# include <sys/malloc.h>
91# if (defined(_KERNEL) || defined(KERNEL)) && !defined(IPFILTER_LKM)
92#  include <sys/libkern.h>
93#  include <sys/systm.h>
94# endif
95#endif
96
97#if !defined(lint)
98static const char sccsid[] = "@(#)ip_state.c	1.8 6/5/96 (C) 1993-2000 Darren Reed";
99/* static const char rcsid[] = "@(#)$Id: ip_state.c,v 2.30.2.38 2001/07/23 13:49:46 darrenr Exp $"; */
100static const char rcsid[] = "@(#)$FreeBSD: head/sys/contrib/ipfilter/netinet/ip_state.c 89316 2002-01-13 21:37:49Z alfred $";
101#endif
102
103#ifndef	MIN
104# define	MIN(a,b)	(((a)<(b))?(a):(b))
105#endif
106
107#define	TCP_CLOSE	(TH_FIN|TH_RST)
108
109static ipstate_t **ips_table = NULL;
110static ipstate_t *ips_list = NULL;
111static int	ips_num = 0;
112static int	ips_wild = 0;
113static ips_stat_t ips_stats;
114#if	(SOLARIS || defined(__sgi)) && defined(_KERNEL)
115extern	KRWLOCK_T	ipf_state, ipf_mutex;
116extern	kmutex_t	ipf_rw;
117#endif
118
119#ifdef	USE_INET6
120static frentry_t *fr_checkicmp6matchingstate __P((ip6_t *, fr_info_t *));
121#endif
122static int fr_matchsrcdst __P((ipstate_t *, union i6addr, union i6addr,
123			       fr_info_t *, tcphdr_t *));
124static frentry_t *fr_checkicmpmatchingstate __P((ip_t *, fr_info_t *));
125static int fr_matchicmpqueryreply __P((int, ipstate_t *, icmphdr_t *));
126static int fr_state_flush __P((int));
127static ips_stat_t *fr_statetstats __P((void));
128static void fr_delstate __P((ipstate_t *));
129static int fr_state_remove __P((caddr_t));
130static void fr_ipsmove __P((ipstate_t **, ipstate_t *, u_int));
131int fr_stputent __P((caddr_t));
132int fr_stgetent __P((caddr_t));
133void fr_stinsert __P((ipstate_t *));
134
135
136#define	FIVE_DAYS	(2 * 5 * 86400)	/* 5 days: half closed session */
137
138#define	TCP_MSL	240			/* 2 minutes */
139u_long	fr_tcpidletimeout = FIVE_DAYS,
140	fr_tcpclosewait = 2 * TCP_MSL,
141	fr_tcplastack = 2 * TCP_MSL,
142	fr_tcptimeout = 2 * TCP_MSL,
143	fr_tcpclosed = 120,
144	fr_tcphalfclosed = 2 * 2 * 3600,    /* 2 hours */
145	fr_udptimeout = 240,
146	fr_udpacktimeout = 24,
147	fr_icmptimeout = 120,
148	fr_icmpacktimeout = 12;
149int	fr_statemax = IPSTATE_MAX,
150	fr_statesize = IPSTATE_SIZE;
151int	fr_state_doflush = 0,
152	fr_state_lock = 0;
153
154static 	int icmpreplytype4[ICMP_MAXTYPE + 1];
155
156int fr_stateinit()
157{
158	int i;
159
160	KMALLOCS(ips_table, ipstate_t **, fr_statesize * sizeof(ipstate_t *));
161	if (ips_table != NULL)
162		bzero((char *)ips_table, fr_statesize * sizeof(ipstate_t *));
163	else
164		return -1;
165
166	/* fill icmp reply type table */
167	for (i = 0; i <= ICMP_MAXTYPE; i++)
168		icmpreplytype4[i] = -1;
169	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
170	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
171	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
172	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
173
174	return 0;
175}
176
177
178static ips_stat_t *fr_statetstats()
179{
180	ips_stats.iss_active = ips_num;
181	ips_stats.iss_table = ips_table;
182	ips_stats.iss_list = ips_list;
183	return &ips_stats;
184}
185
186
187/*
188 * flush state tables.  two actions currently defined:
189 * which == 0 : flush all state table entries
190 * which == 1 : flush TCP connections which have started to close but are
191 *	        stuck for some reason.
192 */
193static int fr_state_flush(which)
194int which;
195{
196	register ipstate_t *is, **isp;
197#if defined(_KERNEL) && !SOLARIS
198	int s;
199#endif
200	int delete, removed = 0;
201
202	SPL_NET(s);
203	for (isp = &ips_list; (is = *isp); ) {
204		delete = 0;
205
206		switch (which)
207		{
208		case 0 :
209			delete = 1;
210			break;
211		case 1 :
212			if (is->is_p != IPPROTO_TCP)
213				break;
214			if ((is->is_state[0] != TCPS_ESTABLISHED) ||
215			    (is->is_state[1] != TCPS_ESTABLISHED))
216				delete = 1;
217			break;
218		}
219
220		if (delete) {
221			if (is->is_p == IPPROTO_TCP)
222				ips_stats.iss_fin++;
223			else
224				ips_stats.iss_expire++;
225#ifdef	IPFILTER_LOG
226			ipstate_log(is, ISL_FLUSH);
227#endif
228			fr_delstate(is);
229			removed++;
230		} else
231			isp = &is->is_next;
232	}
233	SPL_X(s);
234	return removed;
235}
236
237
238static int fr_state_remove(data)
239caddr_t data;
240{
241	ipstate_t *sp, st;
242	int error;
243
244	sp = &st;
245	error = IRCOPYPTR(data, (caddr_t)&st, sizeof(st));
246	if (error)
247		return EFAULT;
248
249	WRITE_ENTER(&ipf_state);
250	for (sp = ips_list; sp; sp = sp->is_next)
251		if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
252		    !bcmp((char *)&sp->is_src, (char *)&st.is_src,
253			  sizeof(st.is_src)) &&
254		    !bcmp((char *)&sp->is_dst, (char *)&st.is_src,
255			  sizeof(st.is_dst)) &&
256		    !bcmp((char *)&sp->is_ps, (char *)&st.is_ps,
257			  sizeof(st.is_ps))) {
258#ifdef	IPFILTER_LOG
259			ipstate_log(sp, ISL_REMOVE);
260#endif
261			fr_delstate(sp);
262			RWLOCK_EXIT(&ipf_state);
263			return 0;
264		}
265	RWLOCK_EXIT(&ipf_state);
266	return ESRCH;
267}
268
269
270int fr_state_ioctl(data, cmd, mode)
271caddr_t data;
272#if defined(__NetBSD__) || defined(__OpenBSD__)
273u_long cmd;
274#else
275int cmd;
276#endif
277int mode;
278{
279	int arg, ret, error = 0;
280
281	switch (cmd)
282	{
283	case SIOCDELST :
284		error = fr_state_remove(data);
285		break;
286	case SIOCIPFFL :
287		error = IRCOPY(data, (caddr_t)&arg, sizeof(arg));
288		if (error)
289			break;
290		if (arg == 0 || arg == 1) {
291			WRITE_ENTER(&ipf_state);
292			ret = fr_state_flush(arg);
293			RWLOCK_EXIT(&ipf_state);
294			error = IWCOPY((caddr_t)&ret, data, sizeof(ret));
295		} else
296			error = EINVAL;
297		break;
298#ifdef	IPFILTER_LOG
299	case SIOCIPFFB :
300		if (!(mode & FWRITE))
301			error = EPERM;
302		else {
303			int tmp;
304
305			tmp = ipflog_clear(IPL_LOGSTATE);
306			IWCOPY((char *)&tmp, data, sizeof(tmp));
307		}
308		break;
309#endif
310	case SIOCGETFS :
311		error = IWCOPYPTR((caddr_t)fr_statetstats(), data,
312				  sizeof(ips_stat_t));
313		break;
314	case FIONREAD :
315#ifdef	IPFILTER_LOG
316		arg = (int)iplused[IPL_LOGSTATE];
317		error = IWCOPY((caddr_t)&arg, (caddr_t)data, sizeof(arg));
318#endif
319		break;
320	case SIOCSTLCK :
321		error = fr_lock(data, &fr_state_lock);
322		break;
323	case SIOCSTPUT :
324		if (!fr_state_lock) {
325			error = EACCES;
326			break;
327		}
328		error = fr_stputent(data);
329		break;
330	case SIOCSTGET :
331		if (!fr_state_lock) {
332			error = EACCES;
333			break;
334		}
335		error = fr_stgetent(data);
336		break;
337	default :
338		error = EINVAL;
339		break;
340	}
341	return error;
342}
343
344
345int fr_stgetent(data)
346caddr_t data;
347{
348	register ipstate_t *is, *isn;
349	ipstate_save_t ips, *ipsp;
350	int error;
351
352	error = IRCOPY(data, (caddr_t)&ipsp, sizeof(ipsp));
353	if (error)
354		return EFAULT;
355	error = IRCOPY((caddr_t)ipsp, (caddr_t)&ips, sizeof(ips));
356	if (error)
357		return EFAULT;
358
359	isn = ips.ips_next;
360	if (!isn) {
361		isn = ips_list;
362		if (isn == NULL) {
363			if (ips.ips_next == NULL)
364				return ENOENT;
365			return 0;
366		}
367	} else {
368		/*
369		 * Make sure the pointer we're copying from exists in the
370		 * current list of entries.  Security precaution to prevent
371		 * copying of random kernel data.
372		 */
373		for (is = ips_list; is; is = is->is_next)
374			if (is == isn)
375				break;
376		if (!is)
377			return ESRCH;
378	}
379	ips.ips_next = isn->is_next;
380	bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
381	if (isn->is_rule)
382		bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
383		      sizeof(ips.ips_fr));
384	error = IWCOPY((caddr_t)&ips, ipsp, sizeof(ips));
385	if (error)
386		error = EFAULT;
387	return error;
388}
389
390
391int fr_stputent(data)
392caddr_t data;
393{
394	register ipstate_t *is, *isn;
395	ipstate_save_t ips, *ipsp;
396	int error, out;
397	frentry_t *fr;
398
399	error = IRCOPY(data, (caddr_t)&ipsp, sizeof(ipsp));
400	if (error)
401		return EFAULT;
402	error = IRCOPY((caddr_t)ipsp, (caddr_t)&ips, sizeof(ips));
403	if (error)
404		return EFAULT;
405
406	KMALLOC(isn, ipstate_t *);
407	if (isn == NULL)
408		return ENOMEM;
409
410	bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
411	fr = isn->is_rule;
412	if (fr != NULL) {
413		if (isn->is_flags & FI_NEWFR) {
414			KMALLOC(fr, frentry_t *);
415			if (fr == NULL) {
416				KFREE(isn);
417				return ENOMEM;
418			}
419			bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
420			out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
421			isn->is_rule = fr;
422			ips.ips_is.is_rule = fr;
423			if (*fr->fr_ifname) {
424				fr->fr_ifa = GETUNIT(fr->fr_ifname, fr->fr_v);
425				if (fr->fr_ifa == NULL)
426					fr->fr_ifa = (void *)-1;
427#ifdef	_KERNEL
428				else {
429					strncpy(isn->is_ifname[out],
430						IFNAME(fr->fr_ifa), IFNAMSIZ);
431					isn->is_ifp[out] = fr->fr_ifa;
432				}
433#endif
434			} else
435				fr->fr_ifa = NULL;
436			/*
437			 * send a copy back to userland of what we ended up
438			 * to allow for verification.
439			 */
440			error = IWCOPY((caddr_t)&ips, ipsp, sizeof(ips));
441			if (error) {
442				KFREE(isn);
443				KFREE(fr);
444				return EFAULT;
445			}
446		} else {
447			for (is = ips_list; is; is = is->is_next)
448				if (is->is_rule == fr)
449					break;
450			if (!is) {
451				KFREE(isn);
452				return ESRCH;
453			}
454		}
455	}
456	fr_stinsert(isn);
457	return 0;
458}
459
460
461void fr_stinsert(is)
462register ipstate_t *is;
463{
464	register u_int hv = is->is_hv;
465
466	MUTEX_INIT(&is->is_lock, "ipf state entry", NULL);
467
468	is->is_ifname[0][sizeof(is->is_ifname[0]) - 1] = '\0';
469	if (is->is_ifname[0][0] != '\0') {
470		is->is_ifp[0] = GETUNIT(is->is_ifname[0], is->is_v);
471	}
472	is->is_ifname[1][sizeof(is->is_ifname[0]) - 1] = '\0';
473	if (is->is_ifname[1][0] != '\0') {
474		is->is_ifp[1] = GETUNIT(is->is_ifname[1], is->is_v);
475	}
476
477	/*
478	 * add into list table.
479	 */
480	if (ips_list)
481		ips_list->is_pnext = &is->is_next;
482	is->is_pnext = &ips_list;
483	is->is_next = ips_list;
484	ips_list = is;
485	if (ips_table[hv])
486		ips_table[hv]->is_phnext = &is->is_hnext;
487	else
488		ips_stats.iss_inuse++;
489	is->is_phnext = ips_table + hv;
490	is->is_hnext = ips_table[hv];
491	ips_table[hv] = is;
492	ips_num++;
493}
494
495
496/*
497 * Create a new ipstate structure and hang it off the hash table.
498 */
499ipstate_t *fr_addstate(ip, fin, flags)
500ip_t *ip;
501fr_info_t *fin;
502u_int flags;
503{
504	register tcphdr_t *tcp = NULL;
505	register ipstate_t *is;
506	register u_int hv;
507	ipstate_t ips;
508	u_int pass;
509	int out;
510
511	if (fr_state_lock || (fin->fin_off != 0) || (fin->fin_fl & FI_SHORT))
512		return NULL;
513	if (ips_num == fr_statemax) {
514		ips_stats.iss_max++;
515		fr_state_doflush = 1;
516		return NULL;
517	}
518	out = fin->fin_out;
519	is = &ips;
520	bzero((char *)is, sizeof(*is));
521	ips.is_age = 1;
522	ips.is_state[0] = 0;
523	ips.is_state[1] = 0;
524	/*
525	 * Copy and calculate...
526	 */
527	hv = (is->is_p = fin->fin_fi.fi_p);
528	is->is_src = fin->fin_fi.fi_src;
529	hv += is->is_saddr;
530	is->is_dst = fin->fin_fi.fi_dst;
531	hv += is->is_daddr;
532#ifdef	USE_INET6
533	if (fin->fin_v == 6) {
534		if (is->is_p == IPPROTO_ICMPV6) {
535			if (IN6_IS_ADDR_MULTICAST(&is->is_dst.in6))
536				flags |= FI_W_DADDR;
537			if (out)
538				hv -= is->is_daddr;
539			else
540				hv -= is->is_saddr;
541		}
542	}
543#endif
544
545	switch (is->is_p)
546	{
547#ifdef	USE_INET6
548	case IPPROTO_ICMPV6 :
549#endif
550	case IPPROTO_ICMP :
551	    {
552		struct icmp *ic = (struct icmp *)fin->fin_dp;
553
554#ifdef	USE_INET6
555		if ((is->is_p == IPPROTO_ICMPV6) &&
556		    ((ic->icmp_type & ICMP6_INFOMSG_MASK) == 0))
557			return NULL;
558#endif
559		switch (ic->icmp_type)
560		{
561#ifdef	USE_INET6
562		case ICMP6_ECHO_REQUEST :
563			is->is_icmp.ics_type = ICMP6_ECHO_REPLY;
564			hv += (is->is_icmp.ics_id = ic->icmp_id);
565			hv += (is->is_icmp.ics_seq = ic->icmp_seq);
566			break;
567		case ICMP6_MEMBERSHIP_QUERY :
568		case ND_ROUTER_SOLICIT :
569		case ND_NEIGHBOR_SOLICIT :
570			is->is_icmp.ics_type = ic->icmp_type + 1;
571			break;
572#endif
573		case ICMP_ECHO :
574		case ICMP_TSTAMP :
575		case ICMP_IREQ :
576		case ICMP_MASKREQ :
577			is->is_icmp.ics_type = ic->icmp_type;
578			hv += (is->is_icmp.ics_id = ic->icmp_id);
579			hv += (is->is_icmp.ics_seq = ic->icmp_seq);
580			break;
581		default :
582			return NULL;
583		}
584		ATOMIC_INCL(ips_stats.iss_icmp);
585		is->is_age = fr_icmptimeout;
586		break;
587	    }
588	case IPPROTO_TCP :
589	    {
590		tcp = (tcphdr_t *)fin->fin_dp;
591
592		if (tcp->th_flags & TH_RST)
593			return NULL;
594		/*
595		 * The endian of the ports doesn't matter, but the ack and
596		 * sequence numbers do as we do mathematics on them later.
597		 */
598		is->is_dport = tcp->th_dport;
599		is->is_sport = tcp->th_sport;
600		if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
601			hv += tcp->th_dport;
602			hv += tcp->th_sport;
603		}
604		is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
605			      (tcp->th_off << 2) +
606			      ((tcp->th_flags & TH_SYN) ? 1 : 0) +
607			      ((tcp->th_flags & TH_FIN) ? 1 : 0);
608		is->is_maxsend = is->is_send;
609		is->is_dend = 0;
610		is->is_maxdwin = 1;
611		is->is_maxswin = ntohs(tcp->th_win);
612		if (is->is_maxswin == 0)
613			is->is_maxswin = 1;
614		/*
615		 * If we're creating state for a starting connection, start the
616		 * timer on it as we'll never see an error if it fails to
617		 * connect.
618		 */
619		ATOMIC_INCL(ips_stats.iss_tcp);
620		break;
621	    }
622	case IPPROTO_UDP :
623	    {
624		tcp = (tcphdr_t *)fin->fin_dp;
625
626		is->is_dport = tcp->th_dport;
627		is->is_sport = tcp->th_sport;
628		if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
629			hv += tcp->th_dport;
630			hv += tcp->th_sport;
631		}
632		ATOMIC_INCL(ips_stats.iss_udp);
633		is->is_age = fr_udptimeout;
634		break;
635	    }
636	default :
637		return NULL;
638	}
639
640	KMALLOC(is, ipstate_t *);
641	if (is == NULL) {
642		ATOMIC_INCL(ips_stats.iss_nomem);
643		return NULL;
644	}
645	bcopy((char *)&ips, (char *)is, sizeof(*is));
646	hv %= fr_statesize;
647	is->is_hv = hv;
648	is->is_rule = fin->fin_fr;
649	if (is->is_rule != NULL) {
650		ATOMIC_INC32(is->is_rule->fr_ref);
651		pass = is->is_rule->fr_flags;
652	} else
653		pass = fr_flags;
654	WRITE_ENTER(&ipf_state);
655
656	is->is_pass = pass;
657	is->is_pkts = 1;
658	is->is_bytes = fin->fin_dlen + fin->fin_hlen;
659	/*
660	 * We want to check everything that is a property of this packet,
661	 * but we don't (automatically) care about it's fragment status as
662	 * this may change.
663	 */
664	is->is_v = fin->fin_fi.fi_v;
665	is->is_opt = fin->fin_fi.fi_optmsk;
666	is->is_optmsk = 0xffffffff;
667	is->is_sec = fin->fin_fi.fi_secmsk;
668	is->is_secmsk = 0xffff;
669	is->is_auth = fin->fin_fi.fi_auth;
670	is->is_authmsk = 0xffff;
671	is->is_flags = fin->fin_fl & FI_CMP;
672	is->is_flags |= FI_CMP << 4;
673	is->is_flags |= flags & (FI_WILDP|FI_WILDA);
674	if (flags & (FI_WILDP|FI_WILDA))
675		ips_wild++;
676	is->is_ifp[1 - out] = NULL;
677	is->is_ifp[out] = fin->fin_ifp;
678#ifdef	_KERNEL
679	strncpy(is->is_ifname[out], IFNAME(fin->fin_ifp), IFNAMSIZ);
680#endif
681	is->is_ifname[1 - out][0] = '\0';
682	if (pass & FR_LOGFIRST)
683		is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
684	fr_stinsert(is);
685	if (is->is_p == IPPROTO_TCP) {
686		MUTEX_ENTER(&is->is_lock);
687		fr_tcp_age(&is->is_age, is->is_state, fin,
688			   0); /* 0 = packet from the source */
689		MUTEX_EXIT(&is->is_lock);
690	}
691#ifdef	IPFILTER_LOG
692	ipstate_log(is, ISL_NEW);
693#endif
694	RWLOCK_EXIT(&ipf_state);
695	fin->fin_rev = IP6NEQ(is->is_dst, fin->fin_fi.fi_dst);
696	if ((fin->fin_fi.fi_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
697		ipfr_newfrag(ip, fin, pass ^ FR_KEEPSTATE);
698	return is;
699}
700
701
702
703/*
704 * check to see if a packet with TCP headers fits within the TCP window.
705 * change timeout depending on whether new packet is a SYN-ACK returning for a
706 * SYN or a RST or FIN which indicate time to close up shop.
707 */
708int fr_tcpstate(is, fin, ip, tcp)
709register ipstate_t *is;
710fr_info_t *fin;
711ip_t *ip;
712tcphdr_t *tcp;
713{
714	register tcp_seq seq, ack, end;
715	register int ackskew;
716	tcpdata_t  *fdata, *tdata;
717	u_short	win, maxwin;
718	int ret = 0;
719	int source;
720
721	/*
722	 * Find difference between last checked packet and this packet.
723	 */
724	source = IP6EQ(fin->fin_fi.fi_src, is->is_src);
725	if (source && (ntohs(is->is_sport) != fin->fin_data[0]))
726		source = 0;
727	fdata = &is->is_tcp.ts_data[!source];
728	tdata = &is->is_tcp.ts_data[source];
729	seq = ntohl(tcp->th_seq);
730	ack = ntohl(tcp->th_ack);
731	win = ntohs(tcp->th_win);
732	end = seq + fin->fin_dlen - (tcp->th_off << 2) +
733	       ((tcp->th_flags & TH_SYN) ? 1 : 0) +
734	       ((tcp->th_flags & TH_FIN) ? 1 : 0);
735
736	MUTEX_ENTER(&is->is_lock);
737	if (fdata->td_end == 0) {
738		/*
739		 * Must be a (outgoing) SYN-ACK in reply to a SYN.
740		 */
741		fdata->td_end = end;
742		fdata->td_maxwin = 1;
743		fdata->td_maxend = end + 1;
744	}
745
746	if (!(tcp->th_flags & TH_ACK)) {  /* Pretend an ack was sent */
747		ack = tdata->td_end;
748	} else if (((tcp->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
749		   (ack == 0)) {
750		/* gross hack to get around certain broken tcp stacks */
751		ack = tdata->td_end;
752	}
753
754	if (seq == end)
755		seq = end = fdata->td_end;
756
757	maxwin = tdata->td_maxwin;
758	ackskew = tdata->td_end - ack;
759
760#define	SEQ_GE(a,b)	((int)((a) - (b)) >= 0)
761#define	SEQ_GT(a,b)	((int)((a) - (b)) > 0)
762	if ((SEQ_GE(fdata->td_maxend, end)) &&
763	    (SEQ_GE(seq, fdata->td_end - maxwin)) &&
764/* XXX what about big packets */
765#define MAXACKWINDOW 66000
766	    (ackskew >= -MAXACKWINDOW) &&
767	    (ackskew <= MAXACKWINDOW)) {
768		/* if ackskew < 0 then this should be due to fragented
769		 * packets. There is no way to know the length of the
770		 * total packet in advance.
771		 * We do know the total length from the fragment cache though.
772		 * Note however that there might be more sessions with
773		 * exactly the same source and destination paramters in the
774		 * state cache (and source and destination is the only stuff
775		 * that is saved in the fragment cache). Note further that
776		 * some TCP connections in the state cache are hashed with
777		 * sport and dport as well which makes it not worthwhile to
778		 * look for them.
779		 * Thus, when ackskew is negative but still seems to belong
780		 * to this session, we bump up the destinations end value.
781		 */
782		if (ackskew < 0)
783			tdata->td_end = ack;
784
785		/* update max window seen */
786		if (fdata->td_maxwin < win)
787			fdata->td_maxwin = win;
788		if (SEQ_GT(end, fdata->td_end))
789			fdata->td_end = end;
790		if (SEQ_GE(ack + win, tdata->td_maxend)) {
791			tdata->td_maxend = ack + win;
792			if (win == 0)
793				tdata->td_maxend++;
794		}
795
796		ATOMIC_INCL(ips_stats.iss_hits);
797		/*
798		 * Nearing end of connection, start timeout.
799		 */
800		/* source ? 0 : 1 -> !source */
801		fr_tcp_age(&is->is_age, is->is_state, fin, !source);
802		ret = 1;
803	}
804	MUTEX_EXIT(&is->is_lock);
805	return ret;
806}
807
808
809static int fr_matchsrcdst(is, src, dst, fin, tcp)
810ipstate_t *is;
811union i6addr src, dst;
812fr_info_t *fin;
813tcphdr_t *tcp;
814{
815	int ret = 0, rev, out, flags;
816	u_short sp, dp;
817	void *ifp;
818
819	rev = IP6NEQ(is->is_dst, dst);
820	ifp = fin->fin_ifp;
821	out = fin->fin_out;
822
823	if (tcp != NULL) {
824		flags = is->is_flags;
825		sp = tcp->th_sport;
826		dp = tcp->th_dport;
827		if (!rev) {
828			if (!(flags & FI_W_SPORT) && (sp != is->is_sport))
829				rev = 1;
830			else if (!(flags & FI_W_DPORT) && (dp != is->is_dport))
831				rev = 1;
832		}
833	} else {
834		flags = is->is_flags & FI_WILDA;
835		sp = 0;
836		dp = 0;
837	}
838
839	if (rev == 0) {
840		if (!out) {
841			if (is->is_ifpin == NULL || is->is_ifpin == ifp)
842				ret = 1;
843		} else {
844			if (is->is_ifpout == NULL || is->is_ifpout == ifp)
845				ret = 1;
846		}
847	} else {
848		if (out) {
849			if (is->is_ifpin == NULL || is->is_ifpin == ifp)
850				ret = 1;
851		} else {
852			if (is->is_ifpout == NULL || is->is_ifpout == ifp)
853				ret = 1;
854		}
855	}
856	if (ret == 0)
857		return 0;
858	ret = 0;
859
860	if (rev == 0) {
861		if (
862		    (IP6EQ(is->is_dst, dst) || (flags & FI_W_DADDR)) &&
863		    (IP6EQ(is->is_src, src) || (flags & FI_W_SADDR)) &&
864		    (!tcp || ((sp == is->is_sport || flags & FI_W_SPORT) &&
865		     (dp == is->is_dport || flags & FI_W_DPORT)))) {
866			ret = 1;
867		}
868	} else {
869		if (
870		    (IP6EQ(is->is_dst, src) || (flags & FI_W_DADDR)) &&
871		    (IP6EQ(is->is_src, dst) || (flags & FI_W_SADDR)) &&
872		    (!tcp || ((sp == is->is_dport || flags & FI_W_DPORT) &&
873		     (dp == is->is_sport || flags & FI_W_SPORT)))) {
874			ret = 1;
875		}
876	}
877	if (ret == 0)
878		return 0;
879
880	/*
881	 * Whether or not this should be here, is questionable, but the aim
882	 * is to get this out of the main line.
883	 */
884	if (tcp == NULL)
885		flags = is->is_flags & (FI_CMP|(FI_CMP<<4));
886
887	if (((fin->fin_fl & (flags >> 4)) != (flags & FI_CMP)) ||
888	    (fin->fin_fi.fi_optmsk != is->is_opt) ||
889	    (fin->fin_fi.fi_secmsk != is->is_sec) ||
890	    (fin->fin_fi.fi_auth != is->is_auth))
891		return 0;
892
893	if ((flags & (FI_W_SPORT|FI_W_DPORT))) {
894		if ((flags & FI_W_SPORT) != 0) {
895			if (rev == 0) {
896				is->is_sport = sp;
897				is->is_send = htonl(tcp->th_seq);
898			} else {
899				is->is_sport = dp;
900				is->is_send = htonl(tcp->th_ack);
901			}
902			is->is_maxsend = is->is_send + 1;
903		} else if ((flags & FI_W_DPORT) != 0) {
904			if (rev == 0) {
905				is->is_dport = dp;
906				is->is_dend = htonl(tcp->th_ack);
907			} else {
908				is->is_dport = sp;
909				is->is_dend = htonl(tcp->th_seq);
910			}
911			is->is_maxdend = is->is_dend + 1;
912		}
913		is->is_flags &= ~(FI_W_SPORT|FI_W_DPORT);
914		ips_wild--;
915	}
916
917	ret = -1;
918
919	if (!rev) {
920		if (out) {
921			if (!is->is_ifpout)
922				ret = 1;
923		} else {
924			if (!is->is_ifpin)
925				ret = 0;
926		}
927	} else {
928		if (out) {
929			if (!is->is_ifpin)
930				ret = 0;
931		} else {
932			if (!is->is_ifpout)
933				ret = 1;
934		}
935	}
936
937	if (ret >= 0) {
938		is->is_ifp[ret] = ifp;
939#ifdef	_KERNEL
940		strncpy(is->is_ifname[ret], IFNAME(fin->fin_ifp),
941			sizeof(is->is_ifname[ret]));
942#endif
943	}
944	fin->fin_rev = rev;
945	return 1;
946}
947
948static int fr_matchicmpqueryreply(v, is, icmp)
949int v;
950ipstate_t *is;
951icmphdr_t *icmp;
952{
953	if (v == 4) {
954		/*
955		 * If we matched its type on the way in, then when going out
956		 * it will still be the same type.
957		 */
958		if (((icmp->icmp_type == is->is_type) ||
959		     (icmpreplytype4[is->is_type] == icmp->icmp_type)) &&
960		    (icmp->icmp_id == is->is_icmp.ics_id) &&
961		    (icmp->icmp_seq == is->is_icmp.ics_seq)) {
962			return 1;
963		};
964	}
965#ifdef	USE_INET6
966	else if (is->is_v == 6) {
967		if ((is->is_type == ICMP6_ECHO_REPLY) &&
968		    (icmp->icmp_type == ICMP6_ECHO_REQUEST) &&
969		    (icmp->icmp_id == is->is_icmp.ics_id) &&
970		    (icmp->icmp_seq == is->is_icmp.ics_seq)) {
971			return 1;
972		};
973	}
974#endif
975	return 0;
976}
977
978static frentry_t *fr_checkicmpmatchingstate(ip, fin)
979ip_t *ip;
980fr_info_t *fin;
981{
982	register ipstate_t *is, **isp;
983	register u_short sport, dport;
984	register u_char	pr;
985	union i6addr dst, src;
986	struct icmp *ic;
987	u_short savelen;
988	icmphdr_t *icmp;
989	fr_info_t ofin;
990	int type, len;
991	tcphdr_t *tcp;
992	frentry_t *fr;
993	ip_t *oip;
994	u_int hv;
995
996	/*
997	 * Does it at least have the return (basic) IP header ?
998	 * Only a basic IP header (no options) should be with
999	 * an ICMP error header.
1000	 */
1001	if (((ip->ip_v != 4) || (ip->ip_hl != 5)) ||
1002	    (fin->fin_plen < ICMPERR_MINPKTLEN))
1003		return NULL;
1004	ic = (struct icmp *)fin->fin_dp;
1005	type = ic->icmp_type;
1006	/*
1007	 * If it's not an error type, then return
1008	 */
1009	if ((type != ICMP_UNREACH) && (type != ICMP_SOURCEQUENCH) &&
1010    	    (type != ICMP_REDIRECT) && (type != ICMP_TIMXCEED) &&
1011    	    (type != ICMP_PARAMPROB))
1012		return NULL;
1013
1014	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
1015	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((oip->ip_hl - 5) << 2))
1016		return NULL;
1017
1018	/*
1019	 * Sanity checks.
1020	 */
1021	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
1022	if ((len <= 0) || ((oip->ip_hl << 2) > len))
1023		return NULL;
1024
1025	/*
1026	 * Is the buffer big enough for all of it ?  It's the size of the IP
1027	 * header claimed in the encapsulated part which is of concern.  It
1028	 * may be too big to be in this buffer but not so big that it's
1029	 * outside the ICMP packet, leading to TCP deref's causing problems.
1030	 * This is possible because we don't know how big oip_hl is when we
1031	 * do the pullup early in fr_check() and thus can't gaurantee it is
1032	 * all here now.
1033	 */
1034#ifdef  _KERNEL
1035	{
1036	mb_t *m;
1037
1038# if SOLARIS
1039	m = fin->fin_qfm;
1040	if ((char *)oip + len > (char *)m->b_wptr)
1041		return NULL;
1042# else
1043	m = *(mb_t **)fin->fin_mp;
1044	if ((char *)oip + len > (char *)ip + m->m_len)
1045		return NULL;
1046# endif
1047	}
1048#endif
1049
1050	/*
1051	 * in the IPv4 case we must zero the i6addr union otherwise
1052	 * the IP6EQ and IP6NEQ macros produce the wrong results because
1053	 * of the 'junk' in the unused part of the union
1054	 */
1055	bzero((char *)&src, sizeof(src));
1056	bzero((char *)&dst, sizeof(dst));
1057
1058	if (oip->ip_p == IPPROTO_ICMP) {
1059		icmp = (icmphdr_t *)((char *)oip + (oip->ip_hl << 2));
1060
1061		/*
1062		 * a ICMP error can only be generated as a result of an
1063		 * ICMP query, not as the response on an ICMP error
1064		 *
1065		 * XXX theoretically ICMP_ECHOREP and the other reply's are
1066		 * ICMP query's as well, but adding them here seems strange XXX
1067		 */
1068		 if ((icmp->icmp_type != ICMP_ECHO) &&
1069		     (icmp->icmp_type != ICMP_TSTAMP) &&
1070		     (icmp->icmp_type != ICMP_IREQ) &&
1071		     (icmp->icmp_type != ICMP_MASKREQ))
1072		    	return NULL;
1073
1074		/*
1075		 * perform a lookup of the ICMP packet in the state table
1076		 */
1077		hv = (pr = oip->ip_p);
1078		src.in4 = oip->ip_src;
1079		hv += src.in4.s_addr;
1080		dst.in4 = oip->ip_dst;
1081		hv += dst.in4.s_addr;
1082		hv += icmp->icmp_id;
1083		hv += icmp->icmp_seq;
1084		hv %= fr_statesize;
1085
1086		savelen = oip->ip_len;
1087		oip->ip_len = len;
1088		ofin.fin_v = 4;
1089		fr_makefrip(oip->ip_hl << 2, oip, &ofin);
1090		oip->ip_len = savelen;
1091		ofin.fin_ifp = fin->fin_ifp;
1092		ofin.fin_out = !fin->fin_out;
1093		ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1094
1095		READ_ENTER(&ipf_state);
1096		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1097			if ((is->is_p == pr) && (is->is_v == 4) &&
1098			    fr_matchsrcdst(is, src, dst, &ofin, NULL) &&
1099			    fr_matchicmpqueryreply(is->is_v, is, icmp)) {
1100				ips_stats.iss_hits++;
1101				is->is_pkts++;
1102				is->is_bytes += ip->ip_len;
1103				fr = is->is_rule;
1104				RWLOCK_EXIT(&ipf_state);
1105				return fr;
1106			}
1107		RWLOCK_EXIT(&ipf_state);
1108		return NULL;
1109	};
1110
1111	if ((oip->ip_p != IPPROTO_TCP) && (oip->ip_p != IPPROTO_UDP))
1112		return NULL;
1113
1114	tcp = (tcphdr_t *)((char *)oip + (oip->ip_hl << 2));
1115	dport = tcp->th_dport;
1116	sport = tcp->th_sport;
1117
1118	hv = (pr = oip->ip_p);
1119	src.in4 = oip->ip_src;
1120	hv += src.in4.s_addr;
1121	dst.in4 = oip->ip_dst;
1122	hv += dst.in4.s_addr;
1123	hv += dport;
1124	hv += sport;
1125	hv %= fr_statesize;
1126	/*
1127	 * we make an fin entry to be able to feed it to
1128	 * matchsrcdst note that not all fields are encessary
1129	 * but this is the cleanest way. Note further we fill
1130	 * in fin_mp such that if someone uses it we'll get
1131	 * a kernel panic. fr_matchsrcdst does not use this.
1132	 *
1133	 * watch out here, as ip is in host order and oip in network
1134	 * order. Any change we make must be undone afterwards.
1135	 */
1136	savelen = oip->ip_len;
1137	oip->ip_len = len;
1138	ofin.fin_v = 4;
1139	fr_makefrip(oip->ip_hl << 2, oip, &ofin);
1140	oip->ip_len = savelen;
1141	ofin.fin_ifp = fin->fin_ifp;
1142	ofin.fin_out = !fin->fin_out;
1143	ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1144	READ_ENTER(&ipf_state);
1145	for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1146		/*
1147		 * Only allow this icmp though if the
1148		 * encapsulated packet was allowed through the
1149		 * other way around. Note that the minimal amount
1150		 * of info present does not allow for checking against
1151		 * tcp internals such as seq and ack numbers.
1152		 */
1153		if ((is->is_p == pr) && (is->is_v == 4) &&
1154		    fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1155			fr = is->is_rule;
1156			ips_stats.iss_hits++;
1157			is->is_pkts++;
1158			is->is_bytes += fin->fin_plen;
1159			/*
1160			 * we deliberately do not touch the timeouts
1161			 * for the accompanying state table entry.
1162			 * It remains to be seen if that is correct. XXX
1163			 */
1164			RWLOCK_EXIT(&ipf_state);
1165			return fr;
1166		}
1167	}
1168	RWLOCK_EXIT(&ipf_state);
1169	return NULL;
1170}
1171
1172
1173static void fr_ipsmove(isp, is, hv)
1174ipstate_t **isp, *is;
1175u_int hv;
1176{
1177	u_int hvm;
1178
1179	hvm = is->is_hv;
1180	/*
1181	 * Remove the hash from the old location...
1182	 */
1183	if (is->is_hnext)
1184		is->is_hnext->is_phnext = isp;
1185	*isp = is->is_hnext;
1186	if (ips_table[hvm] == NULL)
1187		ips_stats.iss_inuse--;
1188
1189	/*
1190	 * ...and put the hash in the new one.
1191	 */
1192	hvm = hv % fr_statesize;
1193	is->is_hv = hvm;
1194	isp = &ips_table[hvm];
1195	if (*isp)
1196		(*isp)->is_phnext = &is->is_hnext;
1197	else
1198		ips_stats.iss_inuse++;
1199	is->is_phnext = isp;
1200	is->is_hnext = *isp;
1201	*isp = is;
1202}
1203
1204
1205/*
1206 * Check if a packet has a registered state.
1207 */
1208frentry_t *fr_checkstate(ip, fin)
1209ip_t *ip;
1210fr_info_t *fin;
1211{
1212	union i6addr dst, src;
1213	register ipstate_t *is, **isp;
1214	register u_char pr;
1215	u_int hv, hvm, hlen, tryagain, pass, v;
1216	struct icmp *ic;
1217	frentry_t *fr;
1218	tcphdr_t *tcp;
1219
1220	if (fr_state_lock || (fin->fin_off != 0) || (fin->fin_fl & FI_SHORT))
1221		return NULL;
1222
1223	is = NULL;
1224	hlen = fin->fin_hlen;
1225	tcp = (tcphdr_t *)((char *)ip + hlen);
1226	ic = (struct icmp *)tcp;
1227	hv = (pr = fin->fin_fi.fi_p);
1228	src = fin->fin_fi.fi_src;
1229	dst = fin->fin_fi.fi_dst;
1230	hv += src.in4.s_addr;
1231	hv += dst.in4.s_addr;
1232
1233	/*
1234	 * Search the hash table for matching packet header info.
1235	 */
1236	v = fin->fin_fi.fi_v;
1237	switch (fin->fin_fi.fi_p)
1238	{
1239#ifdef	USE_INET6
1240	case IPPROTO_ICMPV6 :
1241		if (v == 6) {
1242			if (fin->fin_out)
1243				hv -= dst.in4.s_addr;
1244			else
1245				hv -= src.in4.s_addr;
1246			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
1247			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
1248				hv += ic->icmp_id;
1249				hv += ic->icmp_seq;
1250			}
1251		}
1252#endif
1253	case IPPROTO_ICMP :
1254		if (v == 4) {
1255			hv += ic->icmp_id;
1256			hv += ic->icmp_seq;
1257		}
1258		hv %= fr_statesize;
1259		READ_ENTER(&ipf_state);
1260		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1261			if ((is->is_p == pr) && (is->is_v == v) &&
1262			    fr_matchsrcdst(is, src, dst, fin, NULL) &&
1263			    fr_matchicmpqueryreply(v, is, ic)) {
1264				if (fin->fin_rev)
1265					is->is_age = fr_icmpacktimeout;
1266				else
1267					is->is_age = fr_icmptimeout;
1268				break;
1269			}
1270		}
1271		if (is != NULL)
1272			break;
1273		RWLOCK_EXIT(&ipf_state);
1274		/*
1275		 * No matching icmp state entry. Perhaps this is a
1276		 * response to another state entry.
1277		 */
1278#ifdef	USE_INET6
1279		if (v == 6)
1280			fr = fr_checkicmp6matchingstate((ip6_t *)ip, fin);
1281		else
1282#endif
1283			fr = fr_checkicmpmatchingstate(ip, fin);
1284		if (fr)
1285			return fr;
1286		break;
1287	case IPPROTO_TCP :
1288	    {
1289		register u_short dport, sport;
1290		register int i;
1291
1292		i = tcp->th_flags;
1293		/*
1294		 * Just plain ignore RST flag set with either FIN or SYN.
1295		 */
1296		if ((i & TH_RST) &&
1297		    ((i & (TH_FIN|TH_SYN|TH_RST)) != TH_RST))
1298			break;
1299	case IPPROTO_UDP :
1300		dport = tcp->th_dport;
1301		sport = tcp->th_sport;
1302		tryagain = 0;
1303		hv += dport;
1304		hv += sport;
1305		READ_ENTER(&ipf_state);
1306retry_tcpudp:
1307		hvm = hv % fr_statesize;
1308		for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1309			if ((is->is_p == pr) && (is->is_v == v) &&
1310			    fr_matchsrcdst(is, src, dst, fin, tcp)) {
1311				if ((pr == IPPROTO_TCP)) {
1312					if (!fr_tcpstate(is, fin, ip, tcp)) {
1313						continue;
1314					}
1315				} else if ((pr == IPPROTO_UDP)) {
1316					if (fin->fin_rev)
1317						is->is_age = fr_udpacktimeout;
1318					else
1319						is->is_age = fr_udptimeout;
1320				}
1321				break;
1322			}
1323		if (is != NULL) {
1324			if (tryagain &&
1325			    !(is->is_flags & (FI_WILDP|FI_WILDA))) {
1326				hv += dport;
1327				hv += sport;
1328				fr_ipsmove(isp, is, hv);
1329				MUTEX_DOWNGRADE(&ipf_state);
1330			}
1331			break;
1332		}
1333		RWLOCK_EXIT(&ipf_state);
1334		if (!tryagain && ips_wild) {
1335			hv -= dport;
1336			hv -= sport;
1337			tryagain = 1;
1338			WRITE_ENTER(&ipf_state);
1339			goto retry_tcpudp;
1340		}
1341		break;
1342	    }
1343	default :
1344		break;
1345	}
1346	if (is == NULL) {
1347		ATOMIC_INCL(ips_stats.iss_miss);
1348		return NULL;
1349	}
1350	MUTEX_ENTER(&is->is_lock);
1351	is->is_bytes += fin->fin_plen;
1352	ips_stats.iss_hits++;
1353	is->is_pkts++;
1354	MUTEX_EXIT(&is->is_lock);
1355	fr = is->is_rule;
1356	fin->fin_fr = fr;
1357	pass = is->is_pass;
1358#ifndef	_KERNEL
1359	if (tcp->th_flags & TCP_CLOSE)
1360		fr_delstate(is);
1361#endif
1362	RWLOCK_EXIT(&ipf_state);
1363	if ((fin->fin_fi.fi_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
1364		ipfr_newfrag(ip, fin, pass ^ FR_KEEPSTATE);
1365	return fr;
1366}
1367
1368
1369void ip_statesync(ifp)
1370void *ifp;
1371{
1372	register ipstate_t *is;
1373
1374	WRITE_ENTER(&ipf_state);
1375	for (is = ips_list; is; is = is->is_next) {
1376		if (is->is_ifpin == ifp) {
1377			is->is_ifpin = GETUNIT(is->is_ifname[0], is->is_v);
1378			if (!is->is_ifpin)
1379				is->is_ifpin = (void *)-1;
1380		}
1381		if (is->is_ifpout == ifp) {
1382			is->is_ifpout = GETUNIT(is->is_ifname[1], is->is_v);
1383			if (!is->is_ifpout)
1384				is->is_ifpout = (void *)-1;
1385		}
1386	}
1387	RWLOCK_EXIT(&ipf_state);
1388}
1389
1390
1391/*
1392 * Must always be called with fr_ipfstate held as a write lock.
1393 */
1394static void fr_delstate(is)
1395ipstate_t *is;
1396{
1397	frentry_t *fr;
1398
1399	if (is->is_flags & (FI_WILDP|FI_WILDA))
1400		ips_wild--;
1401	if (is->is_next)
1402		is->is_next->is_pnext = is->is_pnext;
1403	*is->is_pnext = is->is_next;
1404	if (is->is_hnext)
1405		is->is_hnext->is_phnext = is->is_phnext;
1406	*is->is_phnext = is->is_hnext;
1407	if (ips_table[is->is_hv] == NULL)
1408		ips_stats.iss_inuse--;
1409
1410	fr = is->is_rule;
1411	if (fr != NULL) {
1412		fr->fr_ref--;
1413		if (fr->fr_ref == 0) {
1414			KFREE(fr);
1415		}
1416	}
1417#ifdef	_KERNEL
1418	MUTEX_DESTROY(&is->is_lock);
1419#endif
1420	KFREE(is);
1421	ips_num--;
1422}
1423
1424
1425/*
1426 * Free memory in use by all state info. kept.
1427 */
1428void fr_stateunload()
1429{
1430	register ipstate_t *is;
1431
1432	WRITE_ENTER(&ipf_state);
1433	while ((is = ips_list))
1434		fr_delstate(is);
1435	ips_stats.iss_inuse = 0;
1436	ips_num = 0;
1437	RWLOCK_EXIT(&ipf_state);
1438	if (ips_table)
1439		KFREES(ips_table, fr_statesize * sizeof(ipstate_t *));
1440	ips_table = NULL;
1441}
1442
1443
1444/*
1445 * Slowly expire held state for thingslike UDP and ICMP.  Timeouts are set
1446 * in expectation of this being called twice per second.
1447 */
1448void fr_timeoutstate()
1449{
1450	register ipstate_t *is, **isp;
1451#if defined(_KERNEL) && !SOLARIS
1452	int s;
1453#endif
1454
1455	SPL_NET(s);
1456	WRITE_ENTER(&ipf_state);
1457	for (isp = &ips_list; (is = *isp); )
1458		if (is->is_age && !--is->is_age) {
1459			if (is->is_p == IPPROTO_TCP)
1460				ips_stats.iss_fin++;
1461			else
1462				ips_stats.iss_expire++;
1463#ifdef	IPFILTER_LOG
1464			ipstate_log(is, ISL_EXPIRE);
1465#endif
1466			fr_delstate(is);
1467		} else
1468			isp = &is->is_next;
1469	if (fr_state_doflush) {
1470		(void) fr_state_flush(1);
1471		fr_state_doflush = 0;
1472	}
1473	RWLOCK_EXIT(&ipf_state);
1474	SPL_X(s);
1475}
1476
1477
1478/*
1479 * Original idea freom Pradeep Krishnan for use primarily with NAT code.
1480 * (pkrishna@netcom.com)
1481 *
1482 * Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:
1483 *
1484 * - (try to) base state transitions on real evidence only,
1485 *   i.e. packets that are sent and have been received by ipfilter;
1486 *   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.
1487 *
1488 * - deal with half-closed connections correctly;
1489 *
1490 * - store the state of the source in state[0] such that ipfstat
1491 *   displays the state as source/dest instead of dest/source; the calls
1492 *   to fr_tcp_age have been changed accordingly.
1493 *
1494 * Parameters:
1495 *
1496 *    state[0] = state of source (host that initiated connection)
1497 *    state[1] = state of dest   (host that accepted the connection)
1498 *
1499 *    dir == 0 : a packet from source to dest
1500 *    dir == 1 : a packet from dest to source
1501 *
1502 */
1503void fr_tcp_age(age, state, fin, dir)
1504u_long *age;
1505u_char *state;
1506fr_info_t *fin;
1507int dir;
1508{
1509	tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
1510	u_char flags = tcp->th_flags;
1511	int dlen, ostate;
1512
1513	ostate = state[1 - dir];
1514
1515	dlen = fin->fin_plen - fin->fin_hlen - (tcp->th_off << 2);
1516
1517	if (flags & TH_RST) {
1518		if (!(tcp->th_flags & TH_PUSH) && !dlen) {
1519			*age = fr_tcpclosed;
1520			state[dir] = TCPS_CLOSED;
1521		} else {
1522			*age = fr_tcpclosewait;
1523			state[dir] = TCPS_CLOSE_WAIT;
1524		}
1525		return;
1526	}
1527
1528	*age = fr_tcptimeout; /* default 4 mins */
1529
1530	switch(state[dir])
1531	{
1532	case TCPS_CLOSED: /* 0 */
1533		if ((flags & TH_OPENING) == TH_OPENING) {
1534			/*
1535			 * 'dir' received an S and sends SA in response,
1536			 * CLOSED -> SYN_RECEIVED
1537			 */
1538			state[dir] = TCPS_SYN_RECEIVED;
1539			*age = fr_tcptimeout;
1540		} else if ((flags & (TH_SYN|TH_ACK)) == TH_SYN) {
1541			/* 'dir' sent S, CLOSED -> SYN_SENT */
1542			state[dir] = TCPS_SYN_SENT;
1543			*age = fr_tcptimeout;
1544		}
1545		/*
1546		 * The next piece of code makes it possible to get
1547		 * already established connections into the state table
1548		 * after a restart or reload of the filter rules; this
1549		 * does not work when a strict 'flags S keep state' is
1550		 * used for tcp connections of course
1551		 */
1552		if ((flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK) {
1553			/* we saw an A, guess 'dir' is in ESTABLISHED mode */
1554			state[dir] = TCPS_ESTABLISHED;
1555			*age = fr_tcpidletimeout;
1556		}
1557		/*
1558		 * TODO: besides regular ACK packets we can have other
1559		 * packets as well; it is yet to be determined how we
1560		 * should initialize the states in those cases
1561		 */
1562		break;
1563
1564	case TCPS_LISTEN: /* 1 */
1565		/* NOT USED */
1566		break;
1567
1568	case TCPS_SYN_SENT: /* 2 */
1569		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1570			/*
1571			 * We see an A from 'dir' which is in SYN_SENT
1572			 * state: 'dir' sent an A in response to an SA
1573			 * which it received, SYN_SENT -> ESTABLISHED
1574			 */
1575			state[dir] = TCPS_ESTABLISHED;
1576			*age = fr_tcpidletimeout;
1577		} else if (flags & TH_FIN) {
1578			/*
1579			 * We see an F from 'dir' which is in SYN_SENT
1580			 * state and wants to close its side of the
1581			 * connection; SYN_SENT -> FIN_WAIT_1
1582			 */
1583			state[dir] = TCPS_FIN_WAIT_1;
1584			*age = fr_tcpidletimeout; /* or fr_tcptimeout? */
1585		} else if ((flags & TH_OPENING) == TH_OPENING) {
1586			/*
1587			 * We see an SA from 'dir' which is already in
1588			 * SYN_SENT state, this means we have a
1589			 * simultaneous open; SYN_SENT -> SYN_RECEIVED
1590			 */
1591			state[dir] = TCPS_SYN_RECEIVED;
1592			*age = fr_tcptimeout;
1593		}
1594		break;
1595
1596	case TCPS_SYN_RECEIVED: /* 3 */
1597		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1598			/*
1599			 * We see an A from 'dir' which was in SYN_RECEIVED
1600			 * state so it must now be in established state,
1601			 * SYN_RECEIVED -> ESTABLISHED
1602			 */
1603			state[dir] = TCPS_ESTABLISHED;
1604			*age = fr_tcpidletimeout;
1605		} else if (flags & TH_FIN) {
1606			/*
1607			 * We see an F from 'dir' which is in SYN_RECEIVED
1608			 * state and wants to close its side of the connection;
1609			 * SYN_RECEIVED -> FIN_WAIT_1
1610			 */
1611			state[dir] = TCPS_FIN_WAIT_1;
1612			*age = fr_tcpidletimeout;
1613		}
1614		break;
1615
1616	case TCPS_ESTABLISHED: /* 4 */
1617		if (flags & TH_FIN) {
1618			/*
1619			 * 'dir' closed its side of the connection; this
1620			 * gives us a half-closed connection;
1621			 * ESTABLISHED -> FIN_WAIT_1
1622			 */
1623			state[dir] = TCPS_FIN_WAIT_1;
1624			*age = fr_tcphalfclosed;
1625		} else if (flags & TH_ACK) {
1626			/* an ACK, should we exclude other flags here? */
1627			if (ostate == TCPS_FIN_WAIT_1) {
1628				/*
1629				 * We know the other side did an active close,
1630				 * so we are ACKing the recvd FIN packet (does
1631				 * the window matching code guarantee this?)
1632				 * and go into CLOSE_WAIT state; this gives us
1633				 * a half-closed connection
1634				 */
1635				state[dir] = TCPS_CLOSE_WAIT;
1636				*age = fr_tcphalfclosed;
1637			} else if (ostate < TCPS_CLOSE_WAIT)
1638				/*
1639				 * Still a fully established connection,
1640				 * reset timeout
1641				 */
1642				*age = fr_tcpidletimeout;
1643		}
1644		break;
1645
1646	case TCPS_CLOSE_WAIT: /* 5 */
1647		if (flags & TH_FIN) {
1648			/*
1649			 * Application closed and 'dir' sent a FIN, we're now
1650			 * going into LAST_ACK state
1651			 */
1652			*age  = fr_tcplastack;
1653			state[dir] = TCPS_LAST_ACK;
1654		} else {
1655			/*
1656			 * We remain in CLOSE_WAIT because the other side has
1657			 * closed already and we did not close our side yet;
1658			 * reset timeout
1659			 */
1660			*age  = fr_tcphalfclosed;
1661		}
1662		break;
1663
1664	case TCPS_FIN_WAIT_1: /* 6 */
1665		if ((flags & TH_ACK) && ostate > TCPS_CLOSE_WAIT) {
1666			/*
1667			 * If the other side is not active anymore it has sent
1668			 * us a FIN packet that we are ack'ing now with an ACK;
1669			 * this means both sides have now closed the connection
1670			 * and we go into TIME_WAIT
1671			 */
1672			/*
1673			 * XXX: how do we know we really are ACKing the FIN
1674			 * packet here? does the window code guarantee that?
1675			 */
1676			state[dir] = TCPS_TIME_WAIT;
1677			*age = fr_tcptimeout;
1678		} else
1679			/*
1680			 * We closed our side of the connection already but the
1681			 * other side is still active (ESTABLISHED/CLOSE_WAIT);
1682			 * continue with this half-closed connection
1683			 */
1684			*age = fr_tcphalfclosed;
1685		break;
1686
1687	case TCPS_CLOSING: /* 7 */
1688		/* NOT USED */
1689		break;
1690
1691	case TCPS_LAST_ACK: /* 8 */
1692		if (flags & TH_ACK) {
1693			if ((flags & TH_PUSH) || dlen)
1694				/*
1695				 * There is still data to be delivered, reset
1696				 * timeout
1697				 */
1698				*age  = fr_tcplastack;
1699		}
1700		/*
1701		 * We cannot detect when we go out of LAST_ACK state to CLOSED
1702		 * because that is based on the reception of ACK packets;
1703		 * ipfilter can only detect that a packet has been sent by a
1704		 * host
1705		 */
1706		break;
1707
1708	case TCPS_FIN_WAIT_2: /* 9 */
1709		/* NOT USED */
1710		break;
1711
1712	case TCPS_TIME_WAIT: /* 10 */
1713		/* we're in 2MSL timeout now */
1714		break;
1715	}
1716}
1717
1718
1719#ifdef	IPFILTER_LOG
1720void ipstate_log(is, type)
1721struct ipstate *is;
1722u_int type;
1723{
1724	struct	ipslog	ipsl;
1725	void *items[1];
1726	size_t sizes[1];
1727	int types[1];
1728
1729	ipsl.isl_type = type;
1730	ipsl.isl_pkts = is->is_pkts;
1731	ipsl.isl_bytes = is->is_bytes;
1732	ipsl.isl_src = is->is_src;
1733	ipsl.isl_dst = is->is_dst;
1734	ipsl.isl_p = is->is_p;
1735	ipsl.isl_v = is->is_v;
1736	ipsl.isl_flags = is->is_flags;
1737	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
1738		ipsl.isl_sport = is->is_sport;
1739		ipsl.isl_dport = is->is_dport;
1740		if (ipsl.isl_p == IPPROTO_TCP) {
1741			ipsl.isl_state[0] = is->is_state[0];
1742			ipsl.isl_state[1] = is->is_state[1];
1743		}
1744	} else if (ipsl.isl_p == IPPROTO_ICMP)
1745		ipsl.isl_itype = is->is_icmp.ics_type;
1746	else {
1747		ipsl.isl_ps.isl_filler[0] = 0;
1748		ipsl.isl_ps.isl_filler[1] = 0;
1749	}
1750	items[0] = &ipsl;
1751	sizes[0] = sizeof(ipsl);
1752	types[0] = 0;
1753
1754	(void) ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1);
1755}
1756#endif
1757
1758
1759#ifdef	USE_INET6
1760frentry_t *fr_checkicmp6matchingstate(ip, fin)
1761ip6_t *ip;
1762fr_info_t *fin;
1763{
1764	register ipstate_t *is, **isp;
1765	register u_short sport, dport;
1766	register u_char	pr;
1767	struct icmp6_hdr *ic, *oic;
1768	union i6addr dst, src;
1769	u_short savelen;
1770	fr_info_t ofin;
1771	tcphdr_t *tcp;
1772	frentry_t *fr;
1773	ip6_t *oip;
1774	int type;
1775	u_int hv;
1776
1777	/*
1778	 * Does it at least have the return (basic) IP header ?
1779	 * Only a basic IP header (no options) should be with
1780	 * an ICMP error header.
1781	 */
1782	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN))
1783		return NULL;
1784	ic = (struct icmp6_hdr *)fin->fin_dp;
1785	type = ic->icmp6_type;
1786	/*
1787	 * If it's not an error type, then return
1788	 */
1789	if ((type != ICMP6_DST_UNREACH) && (type != ICMP6_PACKET_TOO_BIG) &&
1790	    (type != ICMP6_TIME_EXCEEDED) && (type != ICMP6_PARAM_PROB))
1791		return NULL;
1792
1793	oip = (ip6_t *)((char *)ic + ICMPERR_ICMPHLEN);
1794	if (fin->fin_plen < sizeof(*oip))
1795		return NULL;
1796
1797	if (oip->ip6_nxt == IPPROTO_ICMPV6) {
1798		oic = (struct icmp6_hdr *)(oip + 1);
1799		/*
1800		 * a ICMP error can only be generated as a result of an
1801		 * ICMP query, not as the response on an ICMP error
1802		 *
1803		 * XXX theoretically ICMP_ECHOREP and the other reply's are
1804		 * ICMP query's as well, but adding them here seems strange XXX
1805		 */
1806		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
1807		    	return NULL;
1808
1809		/*
1810		 * perform a lookup of the ICMP packet in the state table
1811		 */
1812		hv = (pr = oip->ip6_nxt);
1813		src.in6 = oip->ip6_src;
1814		hv += src.in4.s_addr;
1815		dst.in6 = oip->ip6_dst;
1816		hv += dst.in4.s_addr;
1817		hv += oic->icmp6_id;
1818		hv += oic->icmp6_seq;
1819		hv %= fr_statesize;
1820
1821		oip->ip6_plen = ntohs(oip->ip6_plen);
1822		ofin.fin_v = 6;
1823		fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1824		oip->ip6_plen = htons(oip->ip6_plen);
1825		ofin.fin_ifp = fin->fin_ifp;
1826		ofin.fin_out = !fin->fin_out;
1827		ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1828
1829		READ_ENTER(&ipf_state);
1830		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1831			if ((is->is_p == pr) &&
1832			    (oic->icmp6_id == is->is_icmp.ics_id) &&
1833			    (oic->icmp6_seq == is->is_icmp.ics_seq) &&
1834			    fr_matchsrcdst(is, src, dst, &ofin, NULL)) {
1835			    	/*
1836			    	 * in the state table ICMP query's are stored
1837			    	 * with the type of the corresponding ICMP
1838			    	 * response. Correct here
1839			    	 */
1840				if (((is->is_type == ICMP6_ECHO_REPLY) &&
1841				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
1842				     (is->is_type - 1 == oic->icmp6_type )) {
1843				    	ips_stats.iss_hits++;
1844    					is->is_pkts++;
1845					is->is_bytes += fin->fin_plen;
1846					return is->is_rule;
1847				}
1848			}
1849		RWLOCK_EXIT(&ipf_state);
1850
1851		return NULL;
1852	};
1853
1854	if ((oip->ip6_nxt != IPPROTO_TCP) && (oip->ip6_nxt != IPPROTO_UDP))
1855		return NULL;
1856	tcp = (tcphdr_t *)(oip + 1);
1857	dport = tcp->th_dport;
1858	sport = tcp->th_sport;
1859
1860	hv = (pr = oip->ip6_nxt);
1861	src.in6 = oip->ip6_src;
1862	hv += src.in4.s_addr;
1863	dst.in6 = oip->ip6_dst;
1864	hv += dst.in4.s_addr;
1865	hv += dport;
1866	hv += sport;
1867	hv %= fr_statesize;
1868	/*
1869	 * we make an fin entry to be able to feed it to
1870	 * matchsrcdst note that not all fields are encessary
1871	 * but this is the cleanest way. Note further we fill
1872	 * in fin_mp such that if someone uses it we'll get
1873	 * a kernel panic. fr_matchsrcdst does not use this.
1874	 *
1875	 * watch out here, as ip is in host order and oip in network
1876	 * order. Any change we make must be undone afterwards.
1877	 */
1878	savelen = oip->ip6_plen;
1879	oip->ip6_plen = ip->ip6_plen - sizeof(*ip) - ICMPERR_ICMPHLEN;
1880	ofin.fin_v = 6;
1881	fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1882	oip->ip6_plen = savelen;
1883	ofin.fin_ifp = fin->fin_ifp;
1884	ofin.fin_out = !fin->fin_out;
1885	ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1886	READ_ENTER(&ipf_state);
1887	for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1888		/*
1889		 * Only allow this icmp though if the
1890		 * encapsulated packet was allowed through the
1891		 * other way around. Note that the minimal amount
1892		 * of info present does not allow for checking against
1893		 * tcp internals such as seq and ack numbers.
1894		 */
1895		if ((is->is_p == pr) && (is->is_v == 6) &&
1896		    fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1897			fr = is->is_rule;
1898			ips_stats.iss_hits++;
1899			/*
1900			 * we must swap src and dst here because the icmp
1901			 * comes the other way around
1902			 */
1903			is->is_pkts++;
1904			is->is_bytes += fin->fin_plen;
1905			/*
1906			 * we deliberately do not touch the timeouts
1907			 * for the accompanying state table entry.
1908			 * It remains to be seen if that is correct. XXX
1909			 */
1910			RWLOCK_EXIT(&ipf_state);
1911			return fr;
1912		}
1913	}
1914	RWLOCK_EXIT(&ipf_state);
1915	return NULL;
1916}
1917#endif
1918