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