ip_state.c revision 67853
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 67853 2000-10-29 07:53:05Z 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	is->is_hv = hvm;
1192	isp = &ips_table[hvm];
1193	if (*isp)
1194		(*isp)->is_phnext = &is->is_hnext;
1195	else
1196		ips_stats.iss_inuse++;
1197	is->is_phnext = isp;
1198	is->is_hnext = *isp;
1199	*isp = is;
1200}
1201
1202
1203/*
1204 * Check if a packet has a registered state.
1205 */
1206frentry_t *fr_checkstate(ip, fin)
1207ip_t *ip;
1208fr_info_t *fin;
1209{
1210	union i6addr dst, src;
1211	register ipstate_t *is, **isp;
1212	register u_char pr;
1213	u_int hv, hvm, hlen, tryagain, pass, v;
1214	struct icmp *ic;
1215	frentry_t *fr;
1216	tcphdr_t *tcp;
1217
1218	if (fr_state_lock || (fin->fin_off & IP_OFFMASK) ||
1219	    (fin->fin_fi.fi_fl & FI_SHORT))
1220		return NULL;
1221
1222	is = NULL;
1223	hlen = fin->fin_hlen;
1224	tcp = (tcphdr_t *)((char *)ip + hlen);
1225	ic = (struct icmp *)tcp;
1226	hv = (pr = fin->fin_fi.fi_p);
1227	src = fin->fin_fi.fi_src;
1228	dst = fin->fin_fi.fi_dst;
1229	hv += src.in4.s_addr;
1230	hv += dst.in4.s_addr;
1231
1232	/*
1233	 * Search the hash table for matching packet header info.
1234	 */
1235	v = fin->fin_fi.fi_v;
1236	switch (fin->fin_fi.fi_p)
1237	{
1238#ifdef	USE_INET6
1239	case IPPROTO_ICMPV6 :
1240		if (v == 6) {
1241			if (fin->fin_out)
1242				hv -= dst.in4.s_addr;
1243			else
1244				hv -= src.in4.s_addr;
1245			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
1246			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
1247				hv += ic->icmp_id;
1248				hv += ic->icmp_seq;
1249			}
1250		}
1251#endif
1252	case IPPROTO_ICMP :
1253		if (v == 4) {
1254			hv += ic->icmp_id;
1255			hv += ic->icmp_seq;
1256		}
1257		hv %= fr_statesize;
1258		READ_ENTER(&ipf_state);
1259		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1260			if ((is->is_p == pr) && (is->is_v == v) &&
1261			    fr_matchsrcdst(is, src, dst, fin, NULL) &&
1262			    fr_matchicmpqueryreply(v, is, ic)) {
1263				is->is_age = fr_icmptimeout;
1264				break;
1265			}
1266		}
1267		if (is != NULL)
1268			break;
1269		RWLOCK_EXIT(&ipf_state);
1270		/*
1271		 * No matching icmp state entry. Perhaps this is a
1272		 * response to another state entry.
1273		 */
1274#ifdef	USE_INET6
1275		if (v == 6)
1276			fr = fr_checkicmp6matchingstate((ip6_t *)ip, fin);
1277		else
1278#endif
1279			fr = fr_checkicmpmatchingstate(ip, fin);
1280		if (fr)
1281			return fr;
1282		break;
1283	case IPPROTO_TCP :
1284	    {
1285		register u_short dport, sport;
1286		register int i;
1287
1288		i = tcp->th_flags;
1289		/*
1290		 * Just plain ignore RST flag set with either FIN or SYN.
1291		 */
1292		if ((i & TH_RST) &&
1293		    ((i & (TH_FIN|TH_SYN|TH_RST)) != TH_RST))
1294			break;
1295	case IPPROTO_UDP :
1296		dport = tcp->th_dport;
1297		sport = tcp->th_sport;
1298		tryagain = 0;
1299		hv += dport;
1300		hv += sport;
1301		READ_ENTER(&ipf_state);
1302retry_tcpudp:
1303		hvm = hv % fr_statesize;
1304		for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1305			if ((is->is_p == pr) && (is->is_v == v) &&
1306			    fr_matchsrcdst(is, src, dst, fin, tcp)) {
1307				if ((pr == IPPROTO_TCP)) {
1308					if (!fr_tcpstate(is, fin, ip, tcp)) {
1309						continue;
1310					}
1311				}
1312				break;
1313			}
1314		if (is != NULL) {
1315			if (tryagain &&
1316			    !(is->is_flags & (FI_WILDP|FI_WILDA))) {
1317				hv += dport;
1318				hv += sport;
1319				fr_ipsmove(isp, is, hv);
1320				MUTEX_DOWNGRADE(&ipf_state);
1321			}
1322			break;
1323		}
1324		RWLOCK_EXIT(&ipf_state);
1325		if (!tryagain && ips_wild) {
1326			hv -= dport;
1327			hv -= sport;
1328			tryagain = 1;
1329			WRITE_ENTER(&ipf_state);
1330			goto retry_tcpudp;
1331		}
1332		break;
1333	    }
1334	default :
1335		break;
1336	}
1337	if (is == NULL) {
1338		ATOMIC_INCL(ips_stats.iss_miss);
1339		return NULL;
1340	}
1341	MUTEX_ENTER(&is->is_lock);
1342	is->is_bytes += fin->fin_plen;
1343	ips_stats.iss_hits++;
1344	is->is_pkts++;
1345	MUTEX_EXIT(&is->is_lock);
1346	fr = is->is_rule;
1347	fin->fin_fr = fr;
1348	pass = is->is_pass;
1349#ifndef	_KERNEL
1350	if (tcp->th_flags & TCP_CLOSE)
1351		fr_delstate(is);
1352#endif
1353	RWLOCK_EXIT(&ipf_state);
1354	if (fin->fin_fi.fi_fl & FI_FRAG)
1355		ipfr_newfrag(ip, fin, pass ^ FR_KEEPSTATE);
1356	return fr;
1357}
1358
1359
1360void ip_statesync(ifp)
1361void *ifp;
1362{
1363	register ipstate_t *is;
1364
1365	WRITE_ENTER(&ipf_state);
1366	for (is = ips_list; is; is = is->is_next) {
1367		if (is->is_ifpin == ifp) {
1368			is->is_ifpin = GETUNIT(is->is_ifname[0], is->is_v);
1369			if (!is->is_ifpin)
1370				is->is_ifpin = (void *)-1;
1371		}
1372		if (is->is_ifpout == ifp) {
1373			is->is_ifpout = GETUNIT(is->is_ifname[1], is->is_v);
1374			if (!is->is_ifpout)
1375				is->is_ifpout = (void *)-1;
1376		}
1377	}
1378	RWLOCK_EXIT(&ipf_state);
1379}
1380
1381
1382static void fr_delstate(is)
1383ipstate_t *is;
1384{
1385	frentry_t *fr;
1386
1387	if (is->is_flags & (FI_WILDP|FI_WILDA))
1388		ips_wild--;
1389	if (is->is_next)
1390		is->is_next->is_pnext = is->is_pnext;
1391	*is->is_pnext = is->is_next;
1392	if (is->is_hnext)
1393		is->is_hnext->is_phnext = is->is_phnext;
1394	*is->is_phnext = is->is_hnext;
1395	if (ips_table[is->is_hv] == NULL)
1396		ips_stats.iss_inuse--;
1397
1398	fr = is->is_rule;
1399	if (fr != NULL) {
1400		ATOMIC_DEC32(fr->fr_ref);
1401		if (fr->fr_ref == 0)
1402			KFREE(fr);
1403	}
1404#ifdef	_KERNEL
1405	MUTEX_DESTROY(&is->is_lock);
1406#endif
1407	KFREE(is);
1408	ips_num--;
1409}
1410
1411
1412/*
1413 * Free memory in use by all state info. kept.
1414 */
1415void fr_stateunload()
1416{
1417	register ipstate_t *is;
1418
1419	WRITE_ENTER(&ipf_state);
1420	while ((is = ips_list))
1421		fr_delstate(is);
1422	ips_stats.iss_inuse = 0;
1423	ips_num = 0;
1424	RWLOCK_EXIT(&ipf_state);
1425	KFREES(ips_table, fr_statesize * sizeof(ipstate_t *));
1426	ips_table = NULL;
1427}
1428
1429
1430/*
1431 * Slowly expire held state for thingslike UDP and ICMP.  Timeouts are set
1432 * in expectation of this being called twice per second.
1433 */
1434void fr_timeoutstate()
1435{
1436	register ipstate_t *is, **isp;
1437#if defined(_KERNEL) && !SOLARIS
1438	int s;
1439#endif
1440
1441	SPL_NET(s);
1442	WRITE_ENTER(&ipf_state);
1443	for (isp = &ips_list; (is = *isp); )
1444		if (is->is_age && !--is->is_age) {
1445			if (is->is_p == IPPROTO_TCP)
1446				ips_stats.iss_fin++;
1447			else
1448				ips_stats.iss_expire++;
1449#ifdef	IPFILTER_LOG
1450			ipstate_log(is, ISL_EXPIRE);
1451#endif
1452			fr_delstate(is);
1453		} else
1454			isp = &is->is_next;
1455	RWLOCK_EXIT(&ipf_state);
1456	SPL_X(s);
1457	if (fr_state_doflush) {
1458		(void) fr_state_flush(1);
1459		fr_state_doflush = 0;
1460	}
1461}
1462
1463
1464/*
1465 * Original idea freom Pradeep Krishnan for use primarily with NAT code.
1466 * (pkrishna@netcom.com)
1467 *
1468 * Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:
1469 *
1470 * - (try to) base state transitions on real evidence only,
1471 *   i.e. packets that are sent and have been received by ipfilter;
1472 *   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.
1473 *
1474 * - deal with half-closed connections correctly;
1475 *
1476 * - store the state of the source in state[0] such that ipfstat
1477 *   displays the state as source/dest instead of dest/source; the calls
1478 *   to fr_tcp_age have been changed accordingly.
1479 *
1480 * Parameters:
1481 *
1482 *    state[0] = state of source (host that initiated connection)
1483 *    state[1] = state of dest   (host that accepted the connection)
1484 *
1485 *    dir == 0 : a packet from source to dest
1486 *    dir == 1 : a packet from dest to source
1487 *
1488 */
1489void fr_tcp_age(age, state, fin, dir)
1490u_long *age;
1491u_char *state;
1492fr_info_t *fin;
1493int dir;
1494{
1495	tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
1496	u_char flags = tcp->th_flags;
1497	int dlen, ostate;
1498
1499	ostate = state[1 - dir];
1500
1501	dlen = fin->fin_plen - fin->fin_hlen - (tcp->th_off << 2);
1502
1503	if (flags & TH_RST) {
1504		if (!(tcp->th_flags & TH_PUSH) && !dlen) {
1505			*age = fr_tcpclosed;
1506			state[dir] = TCPS_CLOSED;
1507		} else {
1508			*age = fr_tcpclosewait;
1509			state[dir] = TCPS_CLOSE_WAIT;
1510		}
1511		return;
1512	}
1513
1514	*age = fr_tcptimeout; /* default 4 mins */
1515
1516	switch(state[dir])
1517	{
1518	case TCPS_CLOSED: /* 0 */
1519		if ((flags & TH_OPENING) == TH_OPENING) {
1520			/*
1521			 * 'dir' received an S and sends SA in response,
1522			 * CLOSED -> SYN_RECEIVED
1523			 */
1524			state[dir] = TCPS_SYN_RECEIVED;
1525			*age = fr_tcptimeout;
1526		} else if ((flags & (TH_SYN|TH_ACK)) == TH_SYN) {
1527			/* 'dir' sent S, CLOSED -> SYN_SENT */
1528			state[dir] = TCPS_SYN_SENT;
1529			*age = fr_tcptimeout;
1530		}
1531		/*
1532		 * The next piece of code makes it possible to get
1533		 * already established connections into the state table
1534		 * after a restart or reload of the filter rules; this
1535		 * does not work when a strict 'flags S keep state' is
1536		 * used for tcp connections of course
1537		 */
1538		if ((flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK) {
1539			/* we saw an A, guess 'dir' is in ESTABLISHED mode */
1540			state[dir] = TCPS_ESTABLISHED;
1541			*age = fr_tcpidletimeout;
1542		}
1543		/*
1544		 * TODO: besides regular ACK packets we can have other
1545		 * packets as well; it is yet to be determined how we
1546		 * should initialize the states in those cases
1547		 */
1548		break;
1549
1550	case TCPS_LISTEN: /* 1 */
1551		/* NOT USED */
1552		break;
1553
1554	case TCPS_SYN_SENT: /* 2 */
1555		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1556			/*
1557			 * We see an A from 'dir' which is in SYN_SENT
1558			 * state: 'dir' sent an A in response to an SA
1559			 * which it received, SYN_SENT -> ESTABLISHED
1560			 */
1561			state[dir] = TCPS_ESTABLISHED;
1562			*age = fr_tcpidletimeout;
1563		} else if (flags & TH_FIN) {
1564			/*
1565			 * We see an F from 'dir' which is in SYN_SENT
1566			 * state and wants to close its side of the
1567			 * connection; SYN_SENT -> FIN_WAIT_1
1568			 */
1569			state[dir] = TCPS_FIN_WAIT_1;
1570			*age = fr_tcpidletimeout; /* or fr_tcptimeout? */
1571		} else if ((flags & TH_OPENING) == TH_OPENING) {
1572			/*
1573			 * We see an SA from 'dir' which is already in
1574			 * SYN_SENT state, this means we have a
1575			 * simultaneous open; SYN_SENT -> SYN_RECEIVED
1576			 */
1577			state[dir] = TCPS_SYN_RECEIVED;
1578			*age = fr_tcptimeout;
1579		}
1580		break;
1581
1582	case TCPS_SYN_RECEIVED: /* 3 */
1583		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1584			/*
1585			 * We see an A from 'dir' which was in SYN_RECEIVED
1586			 * state so it must now be in established state,
1587			 * SYN_RECEIVED -> ESTABLISHED
1588			 */
1589			state[dir] = TCPS_ESTABLISHED;
1590			*age = fr_tcpidletimeout;
1591		} else if (flags & TH_FIN) {
1592			/*
1593			 * We see an F from 'dir' which is in SYN_RECEIVED
1594			 * state and wants to close its side of the connection;
1595			 * SYN_RECEIVED -> FIN_WAIT_1
1596			 */
1597			state[dir] = TCPS_FIN_WAIT_1;
1598			*age = fr_tcpidletimeout;
1599		}
1600		break;
1601
1602	case TCPS_ESTABLISHED: /* 4 */
1603		if (flags & TH_FIN) {
1604			/*
1605			 * 'dir' closed its side of the connection; this
1606			 * gives us a half-closed connection;
1607			 * ESTABLISHED -> FIN_WAIT_1
1608			 */
1609			state[dir] = TCPS_FIN_WAIT_1;
1610			*age = fr_tcphalfclosed;
1611		} else if (flags & TH_ACK) {
1612			/* an ACK, should we exclude other flags here? */
1613			if (ostate == TCPS_FIN_WAIT_1) {
1614				/*
1615				 * We know the other side did an active close,
1616				 * so we are ACKing the recvd FIN packet (does
1617				 * the window matching code guarantee this?)
1618				 * and go into CLOSE_WAIT state; this gives us
1619				 * a half-closed connection
1620				 */
1621				state[dir] = TCPS_CLOSE_WAIT;
1622				*age = fr_tcphalfclosed;
1623			} else if (ostate < TCPS_CLOSE_WAIT)
1624				/*
1625				 * Still a fully established connection,
1626				 * reset timeout
1627				 */
1628				*age = fr_tcpidletimeout;
1629		}
1630		break;
1631
1632	case TCPS_CLOSE_WAIT: /* 5 */
1633		if (flags & TH_FIN) {
1634			/*
1635			 * Application closed and 'dir' sent a FIN, we're now
1636			 * going into LAST_ACK state
1637			 */
1638			*age  = fr_tcplastack;
1639			state[dir] = TCPS_LAST_ACK;
1640		} else {
1641			/*
1642			 * We remain in CLOSE_WAIT because the other side has
1643			 * closed already and we did not close our side yet;
1644			 * reset timeout
1645			 */
1646			*age  = fr_tcphalfclosed;
1647		}
1648		break;
1649
1650	case TCPS_FIN_WAIT_1: /* 6 */
1651		if ((flags & TH_ACK) && ostate > TCPS_CLOSE_WAIT) {
1652			/*
1653			 * If the other side is not active anymore it has sent
1654			 * us a FIN packet that we are ack'ing now with an ACK;
1655			 * this means both sides have now closed the connection
1656			 * and we go into TIME_WAIT
1657			 */
1658			/*
1659			 * XXX: how do we know we really are ACKing the FIN
1660			 * packet here? does the window code guarantee that?
1661			 */
1662			state[dir] = TCPS_TIME_WAIT;
1663			*age = fr_tcptimeout;
1664		} else
1665			/*
1666			 * We closed our side of the connection already but the
1667			 * other side is still active (ESTABLISHED/CLOSE_WAIT);
1668			 * continue with this half-closed connection
1669			 */
1670			*age = fr_tcphalfclosed;
1671		break;
1672
1673	case TCPS_CLOSING: /* 7 */
1674		/* NOT USED */
1675		break;
1676
1677	case TCPS_LAST_ACK: /* 8 */
1678		if (flags & TH_ACK) {
1679			if ((flags & TH_PUSH) || dlen)
1680				/*
1681				 * There is still data to be delivered, reset
1682				 * timeout
1683				 */
1684				*age  = fr_tcplastack;
1685		}
1686		/*
1687		 * We cannot detect when we go out of LAST_ACK state to CLOSED
1688		 * because that is based on the reception of ACK packets;
1689		 * ipfilter can only detect that a packet has been sent by a
1690		 * host
1691		 */
1692		break;
1693
1694	case TCPS_FIN_WAIT_2: /* 9 */
1695		/* NOT USED */
1696		break;
1697
1698	case TCPS_TIME_WAIT: /* 10 */
1699		/* we're in 2MSL timeout now */
1700		break;
1701	}
1702}
1703
1704
1705#ifdef	IPFILTER_LOG
1706void ipstate_log(is, type)
1707struct ipstate *is;
1708u_int type;
1709{
1710	struct	ipslog	ipsl;
1711	void *items[1];
1712	size_t sizes[1];
1713	int types[1];
1714
1715	ipsl.isl_type = type;
1716	ipsl.isl_pkts = is->is_pkts;
1717	ipsl.isl_bytes = is->is_bytes;
1718	ipsl.isl_src = is->is_src;
1719	ipsl.isl_dst = is->is_dst;
1720	ipsl.isl_p = is->is_p;
1721	ipsl.isl_v = is->is_v;
1722	ipsl.isl_flags = is->is_flags;
1723	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
1724		ipsl.isl_sport = is->is_sport;
1725		ipsl.isl_dport = is->is_dport;
1726		if (ipsl.isl_p == IPPROTO_TCP) {
1727			ipsl.isl_state[0] = is->is_state[0];
1728			ipsl.isl_state[1] = is->is_state[1];
1729		}
1730	} else if (ipsl.isl_p == IPPROTO_ICMP)
1731		ipsl.isl_itype = is->is_icmp.ics_type;
1732	else {
1733		ipsl.isl_ps.isl_filler[0] = 0;
1734		ipsl.isl_ps.isl_filler[1] = 0;
1735	}
1736	items[0] = &ipsl;
1737	sizes[0] = sizeof(ipsl);
1738	types[0] = 0;
1739
1740	(void) ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1);
1741}
1742#endif
1743
1744
1745#ifdef	USE_INET6
1746frentry_t *fr_checkicmp6matchingstate(ip, fin)
1747ip6_t *ip;
1748fr_info_t *fin;
1749{
1750	register ipstate_t *is, **isp;
1751	register u_short sport, dport;
1752	register u_char	pr;
1753	struct icmp6_hdr *ic, *oic;
1754	union i6addr dst, src;
1755	u_short savelen;
1756	fr_info_t ofin;
1757	tcphdr_t *tcp;
1758	frentry_t *fr;
1759	ip6_t *oip;
1760	int type;
1761	u_int hv;
1762
1763	/*
1764	 * Does it at least have the return (basic) IP header ?
1765	 * Only a basic IP header (no options) should be with
1766	 * an ICMP error header.
1767	 */
1768	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN))
1769		return NULL;
1770	ic = (struct icmp6_hdr *)fin->fin_dp;
1771	type = ic->icmp6_type;
1772	/*
1773	 * If it's not an error type, then return
1774	 */
1775	if ((type != ICMP6_DST_UNREACH) && (type != ICMP6_PACKET_TOO_BIG) &&
1776	    (type != ICMP6_TIME_EXCEEDED) && (type != ICMP6_PARAM_PROB))
1777		return NULL;
1778
1779	oip = (ip6_t *)((char *)ic + ICMPERR_ICMPHLEN);
1780	if (fin->fin_plen < sizeof(*oip))
1781		return NULL;
1782
1783	if (oip->ip6_nxt == IPPROTO_ICMPV6) {
1784		oic = (struct icmp6_hdr *)(oip + 1);
1785		/*
1786		 * a ICMP error can only be generated as a result of an
1787		 * ICMP query, not as the response on an ICMP error
1788		 *
1789		 * XXX theoretically ICMP_ECHOREP and the other reply's are
1790		 * ICMP query's as well, but adding them here seems strange XXX
1791		 */
1792		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
1793		    	return NULL;
1794
1795		/*
1796		 * perform a lookup of the ICMP packet in the state table
1797		 */
1798		hv = (pr = oip->ip6_nxt);
1799		src.in6 = oip->ip6_src;
1800		hv += src.in4.s_addr;
1801		dst.in6 = oip->ip6_dst;
1802		hv += dst.in4.s_addr;
1803		hv += oic->icmp6_id;
1804		hv += oic->icmp6_seq;
1805		hv %= fr_statesize;
1806
1807		oip->ip6_plen = ntohs(oip->ip6_plen);
1808		ofin.fin_v = 6;
1809		fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1810		oip->ip6_plen = htons(oip->ip6_plen);
1811		ofin.fin_ifp = fin->fin_ifp;
1812		ofin.fin_out = !fin->fin_out;
1813		ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1814
1815		READ_ENTER(&ipf_state);
1816		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1817			if ((is->is_p == pr) &&
1818			    (oic->icmp6_id == is->is_icmp.ics_id) &&
1819			    (oic->icmp6_seq == is->is_icmp.ics_seq) &&
1820			    fr_matchsrcdst(is, src, dst, &ofin, NULL)) {
1821			    	/*
1822			    	 * in the state table ICMP query's are stored
1823			    	 * with the type of the corresponding ICMP
1824			    	 * response. Correct here
1825			    	 */
1826				if (((is->is_type == ICMP6_ECHO_REPLY) &&
1827				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
1828				     (is->is_type - 1 == oic->icmp6_type )) {
1829				    	ips_stats.iss_hits++;
1830    					is->is_pkts++;
1831					is->is_bytes += fin->fin_plen;
1832					return is->is_rule;
1833				}
1834			}
1835		RWLOCK_EXIT(&ipf_state);
1836
1837		return NULL;
1838	};
1839
1840	if ((oip->ip6_nxt != IPPROTO_TCP) && (oip->ip6_nxt != IPPROTO_UDP))
1841		return NULL;
1842	tcp = (tcphdr_t *)(oip + 1);
1843	dport = tcp->th_dport;
1844	sport = tcp->th_sport;
1845
1846	hv = (pr = oip->ip6_nxt);
1847	src.in6 = oip->ip6_src;
1848	hv += src.in4.s_addr;
1849	dst.in6 = oip->ip6_dst;
1850	hv += dst.in4.s_addr;
1851	hv += dport;
1852	hv += sport;
1853	hv %= fr_statesize;
1854	/*
1855	 * we make an fin entry to be able to feed it to
1856	 * matchsrcdst note that not all fields are encessary
1857	 * but this is the cleanest way. Note further we fill
1858	 * in fin_mp such that if someone uses it we'll get
1859	 * a kernel panic. fr_matchsrcdst does not use this.
1860	 *
1861	 * watch out here, as ip is in host order and oip in network
1862	 * order. Any change we make must be undone afterwards.
1863	 */
1864	savelen = oip->ip6_plen;
1865	oip->ip6_plen = ip->ip6_plen - sizeof(*ip) - ICMPERR_ICMPHLEN;
1866	ofin.fin_v = 6;
1867	fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1868	oip->ip6_plen = savelen;
1869	ofin.fin_ifp = fin->fin_ifp;
1870	ofin.fin_out = !fin->fin_out;
1871	ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1872	READ_ENTER(&ipf_state);
1873	for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1874		/*
1875		 * Only allow this icmp though if the
1876		 * encapsulated packet was allowed through the
1877		 * other way around. Note that the minimal amount
1878		 * of info present does not allow for checking against
1879		 * tcp internals such as seq and ack numbers.
1880		 */
1881		if ((is->is_p == pr) && (is->is_v == 6) &&
1882		    fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1883			fr = is->is_rule;
1884			ips_stats.iss_hits++;
1885			/*
1886			 * we must swap src and dst here because the icmp
1887			 * comes the other way around
1888			 */
1889			is->is_pkts++;
1890			is->is_bytes += fin->fin_plen;
1891			/*
1892			 * we deliberately do not touch the timeouts
1893			 * for the accompanying state table entry.
1894			 * It remains to be seen if that is correct. XXX
1895			 */
1896			RWLOCK_EXIT(&ipf_state);
1897			return fr;
1898		}
1899	}
1900	RWLOCK_EXIT(&ipf_state);
1901	return NULL;
1902}
1903#endif
1904