ip_state.c revision 75262
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 75262 2001-04-06 15:52:28Z 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		arg = (int)iplused[IPL_LOGSTATE];
311		error = IWCOPY((caddr_t)&arg, (caddr_t)data, sizeof(arg));
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) && (pass & FR_KEEPFRAG))
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		/*
791		 * Nearing end of connection, start timeout.
792		 */
793		/* source ? 0 : 1 -> !source */
794		fr_tcp_age(&is->is_age, is->is_state, fin, !source);
795		ret = 1;
796	}
797	MUTEX_EXIT(&is->is_lock);
798	return ret;
799}
800
801
802static int fr_matchsrcdst(is, src, dst, fin, tcp)
803ipstate_t *is;
804union i6addr src, dst;
805fr_info_t *fin;
806tcphdr_t *tcp;
807{
808	int ret = 0, rev, out, flags;
809	u_short sp, dp;
810	void *ifp;
811
812	rev = fin->fin_rev = IP6NEQ(is->is_dst, dst);
813	ifp = fin->fin_ifp;
814	out = fin->fin_out;
815
816	if (tcp != NULL) {
817		flags = is->is_flags;
818		sp = tcp->th_sport;
819		dp = tcp->th_dport;
820	} else {
821		flags = is->is_flags & FI_WILDA;
822		sp = 0;
823		dp = 0;
824	}
825
826	if (rev == 0) {
827		if (!out) {
828			if (is->is_ifpin == NULL || is->is_ifpin == ifp)
829				ret = 1;
830		} else {
831			if (is->is_ifpout == NULL || is->is_ifpout == ifp)
832				ret = 1;
833		}
834	} else {
835		if (out) {
836			if (is->is_ifpin == NULL || is->is_ifpin == ifp)
837				ret = 1;
838		} else {
839			if (is->is_ifpout == NULL || is->is_ifpout == ifp)
840				ret = 1;
841		}
842	}
843	if (ret == 0)
844		return 0;
845	ret = 0;
846
847	if (rev == 0) {
848		if (
849		    (IP6EQ(is->is_dst, dst) || (flags & FI_W_DADDR)) &&
850		    (IP6EQ(is->is_src, src) || (flags & FI_W_SADDR)) &&
851		    (!tcp || ((sp == is->is_sport || flags & FI_W_SPORT) &&
852		     (dp == is->is_dport || flags & FI_W_DPORT)))) {
853			ret = 1;
854		}
855	} else {
856		if (
857		    (IP6EQ(is->is_dst, src) || (flags & FI_W_DADDR)) &&
858		    (IP6EQ(is->is_src, dst) || (flags & FI_W_SADDR)) &&
859		    (!tcp || ((sp == is->is_dport || flags & FI_W_DPORT) &&
860		     (dp == is->is_sport || flags & FI_W_SPORT)))) {
861			ret = 1;
862		}
863	}
864	if (ret == 0)
865		return 0;
866
867	/*
868	 * Whether or not this should be here, is questionable, but the aim
869	 * is to get this out of the main line.
870	 */
871	if (tcp == NULL)
872		flags = is->is_flags & (FI_CMP|(FI_CMP<<4));
873
874	if (((fin->fin_fi.fi_fl & (flags >> 4)) != (flags & FI_CMP)) ||
875	    ((fin->fin_fi.fi_optmsk & is->is_optmsk) != is->is_opt) ||
876	    ((fin->fin_fi.fi_secmsk & is->is_secmsk) != is->is_sec) ||
877	    ((fin->fin_fi.fi_auth & is->is_authmsk) != is->is_auth))
878		return 0;
879
880	if ((flags & (FI_W_SPORT|FI_W_DPORT))) {
881		if ((flags & FI_W_SPORT) != 0) {
882			if (rev == 0) {
883				is->is_sport = sp;
884				is->is_send = htonl(tcp->th_seq);
885			} else {
886				is->is_sport = dp;
887				is->is_send = htonl(tcp->th_ack);
888			}
889			is->is_maxsend = is->is_send + 1;
890		} else if ((flags & FI_W_DPORT) != 0) {
891			if (rev == 0) {
892				is->is_dport = dp;
893				is->is_dend = htonl(tcp->th_ack);
894			} else {
895				is->is_dport = sp;
896				is->is_dend = htonl(tcp->th_seq);
897			}
898			is->is_maxdend = is->is_dend + 1;
899		}
900		is->is_flags &= ~(FI_W_SPORT|FI_W_DPORT);
901		ips_wild--;
902	}
903
904	ret = -1;
905
906	if (!rev) {
907		if (out) {
908			if (!is->is_ifpout)
909				ret = 1;
910		} else {
911			if (!is->is_ifpin)
912				ret = 0;
913		}
914	} else {
915		if (out) {
916			if (!is->is_ifpin)
917				ret = 0;
918		} else {
919			if (!is->is_ifpout)
920				ret = 1;
921		}
922	}
923
924	if (ret >= 0) {
925		is->is_ifp[ret] = ifp;
926#ifdef	_KERNEL
927		strncpy(is->is_ifname[out], IFNAME(fin->fin_ifp),
928			sizeof(is->is_ifname[1]));
929#endif
930	}
931#ifdef  _KERNEL
932	if (ret >= 0) {
933		strncpy(is->is_ifname[out], IFNAME(fin->fin_ifp),
934			sizeof(is->is_ifname[1]));
935	}
936#endif
937	return 1;
938}
939
940static int fr_matchicmpqueryreply(v, is, icmp)
941int v;
942ipstate_t *is;
943icmphdr_t *icmp;
944{
945	if (v == 4) {
946		/*
947		 * If we matched its type on the way in, then when going out
948		 * it will still be the same type.
949		 */
950		if (((icmp->icmp_type == is->is_type) ||
951		     (icmpreplytype4[is->is_type] == icmp->icmp_type)) &&
952		    (icmp->icmp_id == is->is_icmp.ics_id) &&
953		    (icmp->icmp_seq == is->is_icmp.ics_seq)) {
954			return 1;
955		};
956	}
957#ifdef	USE_INET6
958	else if (is->is_v == 6) {
959		if ((is->is_type == ICMP6_ECHO_REPLY) &&
960		    (icmp->icmp_type == ICMP6_ECHO_REQUEST) &&
961		    (icmp->icmp_id == is->is_icmp.ics_id) &&
962		    (icmp->icmp_seq == is->is_icmp.ics_seq)) {
963			return 1;
964		};
965	}
966#endif
967	return 0;
968}
969
970static frentry_t *fr_checkicmpmatchingstate(ip, fin)
971ip_t *ip;
972fr_info_t *fin;
973{
974	register ipstate_t *is, **isp;
975	register u_short sport, dport;
976	register u_char	pr;
977	union i6addr dst, src;
978	struct icmp *ic;
979	u_short savelen;
980	icmphdr_t *icmp;
981	fr_info_t ofin;
982	int type, len;
983	tcphdr_t *tcp;
984	frentry_t *fr;
985	ip_t *oip;
986	u_int hv;
987
988	/*
989	 * Does it at least have the return (basic) IP header ?
990	 * Only a basic IP header (no options) should be with
991	 * an ICMP error header.
992	 */
993	if (((ip->ip_v != 4) || (ip->ip_hl != 5)) ||
994	    (fin->fin_plen < ICMPERR_MINPKTLEN))
995		return NULL;
996	ic = (struct icmp *)fin->fin_dp;
997	type = ic->icmp_type;
998	/*
999	 * If it's not an error type, then return
1000	 */
1001	if ((type != ICMP_UNREACH) && (type != ICMP_SOURCEQUENCH) &&
1002    	    (type != ICMP_REDIRECT) && (type != ICMP_TIMXCEED) &&
1003    	    (type != ICMP_PARAMPROB))
1004		return NULL;
1005
1006	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
1007	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((oip->ip_hl - 5) << 2))
1008		return NULL;
1009
1010	/*
1011	 * Sanity checks.
1012	 */
1013	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
1014	if ((len <= 0) || ((oip->ip_hl << 2) > len))
1015		return NULL;
1016
1017	/*
1018	 * Is the buffer big enough for all of it ?  It's the size of the IP
1019	 * header claimed in the encapsulated part which is of concern.  It
1020	 * may be too big to be in this buffer but not so big that it's
1021	 * outside the ICMP packet, leading to TCP deref's causing problems.
1022	 * This is possible because we don't know how big oip_hl is when we
1023	 * do the pullup early in fr_check() and thus can't gaurantee it is
1024	 * all here now.
1025	 */
1026#ifdef  _KERNEL
1027	{
1028	mb_t *m;
1029
1030# if SOLARIS
1031	m = fin->fin_qfm;
1032	if ((char *)oip + len > (char *)m->b_wptr)
1033		return NULL;
1034# else
1035	m = *(mb_t **)fin->fin_mp;
1036	if ((char *)oip + len > (char *)ip + m->m_len)
1037		return NULL;
1038# endif
1039	}
1040#endif
1041
1042	/*
1043	 * in the IPv4 case we must zero the i6addr union otherwise
1044	 * the IP6EQ and IP6NEQ macros produce the wrong results because
1045	 * of the 'junk' in the unused part of the union
1046	 */
1047	bzero((char *)&src, sizeof(src));
1048	bzero((char *)&dst, sizeof(dst));
1049
1050	if (oip->ip_p == IPPROTO_ICMP) {
1051		icmp = (icmphdr_t *)((char *)oip + (oip->ip_hl << 2));
1052
1053		/*
1054		 * a ICMP error can only be generated as a result of an
1055		 * ICMP query, not as the response on an ICMP error
1056		 *
1057		 * XXX theoretically ICMP_ECHOREP and the other reply's are
1058		 * ICMP query's as well, but adding them here seems strange XXX
1059		 */
1060		 if ((icmp->icmp_type != ICMP_ECHO) &&
1061		     (icmp->icmp_type != ICMP_TSTAMP) &&
1062		     (icmp->icmp_type != ICMP_IREQ) &&
1063		     (icmp->icmp_type != ICMP_MASKREQ))
1064		    	return NULL;
1065
1066		/*
1067		 * perform a lookup of the ICMP packet in the state table
1068		 */
1069		hv = (pr = oip->ip_p);
1070		src.in4 = oip->ip_src;
1071		hv += src.in4.s_addr;
1072		dst.in4 = oip->ip_dst;
1073		hv += dst.in4.s_addr;
1074		hv += icmp->icmp_id;
1075		hv += icmp->icmp_seq;
1076		hv %= fr_statesize;
1077
1078		savelen = oip->ip_len;
1079		oip->ip_len = len;
1080		ofin.fin_v = 4;
1081		fr_makefrip(oip->ip_hl << 2, oip, &ofin);
1082		oip->ip_len = savelen;
1083		ofin.fin_ifp = fin->fin_ifp;
1084		ofin.fin_out = !fin->fin_out;
1085		ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1086
1087		READ_ENTER(&ipf_state);
1088		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1089			if ((is->is_p == pr) && (is->is_v == 4) &&
1090			    fr_matchsrcdst(is, src, dst, &ofin, NULL) &&
1091			    fr_matchicmpqueryreply(is->is_v, is, icmp)) {
1092				ips_stats.iss_hits++;
1093				is->is_pkts++;
1094				is->is_bytes += ip->ip_len;
1095				fr = is->is_rule;
1096				RWLOCK_EXIT(&ipf_state);
1097				return fr;
1098			}
1099		RWLOCK_EXIT(&ipf_state);
1100		return NULL;
1101	};
1102
1103	if ((oip->ip_p != IPPROTO_TCP) && (oip->ip_p != IPPROTO_UDP))
1104		return NULL;
1105
1106	tcp = (tcphdr_t *)((char *)oip + (oip->ip_hl << 2));
1107	dport = tcp->th_dport;
1108	sport = tcp->th_sport;
1109
1110	hv = (pr = oip->ip_p);
1111	src.in4 = oip->ip_src;
1112	hv += src.in4.s_addr;
1113	dst.in4 = oip->ip_dst;
1114	hv += dst.in4.s_addr;
1115	hv += dport;
1116	hv += sport;
1117	hv %= fr_statesize;
1118	/*
1119	 * we make an fin entry to be able to feed it to
1120	 * matchsrcdst note that not all fields are encessary
1121	 * but this is the cleanest way. Note further we fill
1122	 * in fin_mp such that if someone uses it we'll get
1123	 * a kernel panic. fr_matchsrcdst does not use this.
1124	 *
1125	 * watch out here, as ip is in host order and oip in network
1126	 * order. Any change we make must be undone afterwards.
1127	 */
1128	savelen = oip->ip_len;
1129	oip->ip_len = len;
1130	ofin.fin_v = 4;
1131	fr_makefrip(oip->ip_hl << 2, oip, &ofin);
1132	oip->ip_len = savelen;
1133	ofin.fin_ifp = fin->fin_ifp;
1134	ofin.fin_out = !fin->fin_out;
1135	ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1136	READ_ENTER(&ipf_state);
1137	for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1138		/*
1139		 * Only allow this icmp though if the
1140		 * encapsulated packet was allowed through the
1141		 * other way around. Note that the minimal amount
1142		 * of info present does not allow for checking against
1143		 * tcp internals such as seq and ack numbers.
1144		 */
1145		if ((is->is_p == pr) && (is->is_v == 4) &&
1146		    fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1147			fr = is->is_rule;
1148			ips_stats.iss_hits++;
1149			is->is_pkts++;
1150			is->is_bytes += fin->fin_plen;
1151			/*
1152			 * we deliberately do not touch the timeouts
1153			 * for the accompanying state table entry.
1154			 * It remains to be seen if that is correct. XXX
1155			 */
1156			RWLOCK_EXIT(&ipf_state);
1157			return fr;
1158		}
1159	}
1160	RWLOCK_EXIT(&ipf_state);
1161	return NULL;
1162}
1163
1164
1165static void fr_ipsmove(isp, is, hv)
1166ipstate_t **isp, *is;
1167u_int hv;
1168{
1169	u_int hvm;
1170
1171	hvm = is->is_hv;
1172	/*
1173	 * Remove the hash from the old location...
1174	 */
1175	if (is->is_hnext)
1176		is->is_hnext->is_phnext = isp;
1177	*isp = is->is_hnext;
1178	if (ips_table[hvm] == NULL)
1179		ips_stats.iss_inuse--;
1180
1181	/*
1182	 * ...and put the hash in the new one.
1183	 */
1184	hvm = hv % fr_statesize;
1185	is->is_hv = hvm;
1186	isp = &ips_table[hvm];
1187	if (*isp)
1188		(*isp)->is_phnext = &is->is_hnext;
1189	else
1190		ips_stats.iss_inuse++;
1191	is->is_phnext = isp;
1192	is->is_hnext = *isp;
1193	*isp = is;
1194}
1195
1196
1197/*
1198 * Check if a packet has a registered state.
1199 */
1200frentry_t *fr_checkstate(ip, fin)
1201ip_t *ip;
1202fr_info_t *fin;
1203{
1204	union i6addr dst, src;
1205	register ipstate_t *is, **isp;
1206	register u_char pr;
1207	u_int hv, hvm, hlen, tryagain, pass, v;
1208	struct icmp *ic;
1209	frentry_t *fr;
1210	tcphdr_t *tcp;
1211
1212	if (fr_state_lock || (fin->fin_off & IP_OFFMASK) ||
1213	    (fin->fin_fi.fi_fl & FI_SHORT))
1214		return NULL;
1215
1216	is = NULL;
1217	hlen = fin->fin_hlen;
1218	tcp = (tcphdr_t *)((char *)ip + hlen);
1219	ic = (struct icmp *)tcp;
1220	hv = (pr = fin->fin_fi.fi_p);
1221	src = fin->fin_fi.fi_src;
1222	dst = fin->fin_fi.fi_dst;
1223	hv += src.in4.s_addr;
1224	hv += dst.in4.s_addr;
1225
1226	/*
1227	 * Search the hash table for matching packet header info.
1228	 */
1229	v = fin->fin_fi.fi_v;
1230	switch (fin->fin_fi.fi_p)
1231	{
1232#ifdef	USE_INET6
1233	case IPPROTO_ICMPV6 :
1234		if (v == 6) {
1235			if (fin->fin_out)
1236				hv -= dst.in4.s_addr;
1237			else
1238				hv -= src.in4.s_addr;
1239			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
1240			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
1241				hv += ic->icmp_id;
1242				hv += ic->icmp_seq;
1243			}
1244		}
1245#endif
1246	case IPPROTO_ICMP :
1247		if (v == 4) {
1248			hv += ic->icmp_id;
1249			hv += ic->icmp_seq;
1250		}
1251		hv %= fr_statesize;
1252		READ_ENTER(&ipf_state);
1253		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1254			if ((is->is_p == pr) && (is->is_v == v) &&
1255			    fr_matchsrcdst(is, src, dst, fin, NULL) &&
1256			    fr_matchicmpqueryreply(v, is, ic)) {
1257				is->is_age = fr_icmptimeout;
1258				break;
1259			}
1260		}
1261		if (is != NULL)
1262			break;
1263		RWLOCK_EXIT(&ipf_state);
1264		/*
1265		 * No matching icmp state entry. Perhaps this is a
1266		 * response to another state entry.
1267		 */
1268#ifdef	USE_INET6
1269		if (v == 6)
1270			fr = fr_checkicmp6matchingstate((ip6_t *)ip, fin);
1271		else
1272#endif
1273			fr = fr_checkicmpmatchingstate(ip, fin);
1274		if (fr)
1275			return fr;
1276		break;
1277	case IPPROTO_TCP :
1278	    {
1279		register u_short dport, sport;
1280		register int i;
1281
1282		i = tcp->th_flags;
1283		/*
1284		 * Just plain ignore RST flag set with either FIN or SYN.
1285		 */
1286		if ((i & TH_RST) &&
1287		    ((i & (TH_FIN|TH_SYN|TH_RST)) != TH_RST))
1288			break;
1289	case IPPROTO_UDP :
1290		dport = tcp->th_dport;
1291		sport = tcp->th_sport;
1292		tryagain = 0;
1293		hv += dport;
1294		hv += sport;
1295		READ_ENTER(&ipf_state);
1296retry_tcpudp:
1297		hvm = hv % fr_statesize;
1298		for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1299			if ((is->is_p == pr) && (is->is_v == v) &&
1300			    fr_matchsrcdst(is, src, dst, fin, tcp)) {
1301				if ((pr == IPPROTO_TCP)) {
1302					if (!fr_tcpstate(is, fin, ip, tcp)) {
1303						continue;
1304					}
1305				}
1306				break;
1307			}
1308		if (is != NULL) {
1309			if (tryagain &&
1310			    !(is->is_flags & (FI_WILDP|FI_WILDA))) {
1311				hv += dport;
1312				hv += sport;
1313				fr_ipsmove(isp, is, hv);
1314				MUTEX_DOWNGRADE(&ipf_state);
1315			}
1316			break;
1317		}
1318		RWLOCK_EXIT(&ipf_state);
1319		if (!tryagain && ips_wild) {
1320			hv -= dport;
1321			hv -= sport;
1322			tryagain = 1;
1323			WRITE_ENTER(&ipf_state);
1324			goto retry_tcpudp;
1325		}
1326		break;
1327	    }
1328	default :
1329		break;
1330	}
1331	if (is == NULL) {
1332		ATOMIC_INCL(ips_stats.iss_miss);
1333		return NULL;
1334	}
1335	MUTEX_ENTER(&is->is_lock);
1336	is->is_bytes += fin->fin_plen;
1337	ips_stats.iss_hits++;
1338	is->is_pkts++;
1339	MUTEX_EXIT(&is->is_lock);
1340	fr = is->is_rule;
1341	fin->fin_fr = fr;
1342	pass = is->is_pass;
1343#ifndef	_KERNEL
1344	if (tcp->th_flags & TCP_CLOSE)
1345		fr_delstate(is);
1346#endif
1347	RWLOCK_EXIT(&ipf_state);
1348	if ((fin->fin_fi.fi_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
1349		ipfr_newfrag(ip, fin, pass ^ FR_KEEPSTATE);
1350	return fr;
1351}
1352
1353
1354void ip_statesync(ifp)
1355void *ifp;
1356{
1357	register ipstate_t *is;
1358
1359	WRITE_ENTER(&ipf_state);
1360	for (is = ips_list; is; is = is->is_next) {
1361		if (is->is_ifpin == ifp) {
1362			is->is_ifpin = GETUNIT(is->is_ifname[0], is->is_v);
1363			if (!is->is_ifpin)
1364				is->is_ifpin = (void *)-1;
1365		}
1366		if (is->is_ifpout == ifp) {
1367			is->is_ifpout = GETUNIT(is->is_ifname[1], is->is_v);
1368			if (!is->is_ifpout)
1369				is->is_ifpout = (void *)-1;
1370		}
1371	}
1372	RWLOCK_EXIT(&ipf_state);
1373}
1374
1375
1376/*
1377 * Must always be called with fr_ipfstate held as a write lock.
1378 */
1379static void fr_delstate(is)
1380ipstate_t *is;
1381{
1382	frentry_t *fr;
1383
1384	if (is->is_flags & (FI_WILDP|FI_WILDA))
1385		ips_wild--;
1386	if (is->is_next)
1387		is->is_next->is_pnext = is->is_pnext;
1388	*is->is_pnext = is->is_next;
1389	if (is->is_hnext)
1390		is->is_hnext->is_phnext = is->is_phnext;
1391	*is->is_phnext = is->is_hnext;
1392	if (ips_table[is->is_hv] == NULL)
1393		ips_stats.iss_inuse--;
1394
1395	fr = is->is_rule;
1396	if (fr != NULL) {
1397		fr->fr_ref--;
1398		if (fr->fr_ref == 0) {
1399			KFREE(fr);
1400		}
1401	}
1402#ifdef	_KERNEL
1403	MUTEX_DESTROY(&is->is_lock);
1404#endif
1405	KFREE(is);
1406	ips_num--;
1407}
1408
1409
1410/*
1411 * Free memory in use by all state info. kept.
1412 */
1413void fr_stateunload()
1414{
1415	register ipstate_t *is;
1416
1417	WRITE_ENTER(&ipf_state);
1418	while ((is = ips_list))
1419		fr_delstate(is);
1420	ips_stats.iss_inuse = 0;
1421	ips_num = 0;
1422	RWLOCK_EXIT(&ipf_state);
1423	KFREES(ips_table, fr_statesize * sizeof(ipstate_t *));
1424	ips_table = NULL;
1425}
1426
1427
1428/*
1429 * Slowly expire held state for thingslike UDP and ICMP.  Timeouts are set
1430 * in expectation of this being called twice per second.
1431 */
1432void fr_timeoutstate()
1433{
1434	register ipstate_t *is, **isp;
1435#if defined(_KERNEL) && !SOLARIS
1436	int s;
1437#endif
1438
1439	SPL_NET(s);
1440	WRITE_ENTER(&ipf_state);
1441	for (isp = &ips_list; (is = *isp); )
1442		if (is->is_age && !--is->is_age) {
1443			if (is->is_p == IPPROTO_TCP)
1444				ips_stats.iss_fin++;
1445			else
1446				ips_stats.iss_expire++;
1447#ifdef	IPFILTER_LOG
1448			ipstate_log(is, ISL_EXPIRE);
1449#endif
1450			fr_delstate(is);
1451		} else
1452			isp = &is->is_next;
1453	if (fr_state_doflush) {
1454		(void) fr_state_flush(1);
1455		fr_state_doflush = 0;
1456	}
1457	RWLOCK_EXIT(&ipf_state);
1458	SPL_X(s);
1459}
1460
1461
1462/*
1463 * Original idea freom Pradeep Krishnan for use primarily with NAT code.
1464 * (pkrishna@netcom.com)
1465 *
1466 * Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:
1467 *
1468 * - (try to) base state transitions on real evidence only,
1469 *   i.e. packets that are sent and have been received by ipfilter;
1470 *   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.
1471 *
1472 * - deal with half-closed connections correctly;
1473 *
1474 * - store the state of the source in state[0] such that ipfstat
1475 *   displays the state as source/dest instead of dest/source; the calls
1476 *   to fr_tcp_age have been changed accordingly.
1477 *
1478 * Parameters:
1479 *
1480 *    state[0] = state of source (host that initiated connection)
1481 *    state[1] = state of dest   (host that accepted the connection)
1482 *
1483 *    dir == 0 : a packet from source to dest
1484 *    dir == 1 : a packet from dest to source
1485 *
1486 */
1487void fr_tcp_age(age, state, fin, dir)
1488u_long *age;
1489u_char *state;
1490fr_info_t *fin;
1491int dir;
1492{
1493	tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
1494	u_char flags = tcp->th_flags;
1495	int dlen, ostate;
1496
1497	ostate = state[1 - dir];
1498
1499	dlen = fin->fin_plen - fin->fin_hlen - (tcp->th_off << 2);
1500
1501	if (flags & TH_RST) {
1502		if (!(tcp->th_flags & TH_PUSH) && !dlen) {
1503			*age = fr_tcpclosed;
1504			state[dir] = TCPS_CLOSED;
1505		} else {
1506			*age = fr_tcpclosewait;
1507			state[dir] = TCPS_CLOSE_WAIT;
1508		}
1509		return;
1510	}
1511
1512	*age = fr_tcptimeout; /* default 4 mins */
1513
1514	switch(state[dir])
1515	{
1516	case TCPS_CLOSED: /* 0 */
1517		if ((flags & TH_OPENING) == TH_OPENING) {
1518			/*
1519			 * 'dir' received an S and sends SA in response,
1520			 * CLOSED -> SYN_RECEIVED
1521			 */
1522			state[dir] = TCPS_SYN_RECEIVED;
1523			*age = fr_tcptimeout;
1524		} else if ((flags & (TH_SYN|TH_ACK)) == TH_SYN) {
1525			/* 'dir' sent S, CLOSED -> SYN_SENT */
1526			state[dir] = TCPS_SYN_SENT;
1527			*age = fr_tcptimeout;
1528		}
1529		/*
1530		 * The next piece of code makes it possible to get
1531		 * already established connections into the state table
1532		 * after a restart or reload of the filter rules; this
1533		 * does not work when a strict 'flags S keep state' is
1534		 * used for tcp connections of course
1535		 */
1536		if ((flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK) {
1537			/* we saw an A, guess 'dir' is in ESTABLISHED mode */
1538			state[dir] = TCPS_ESTABLISHED;
1539			*age = fr_tcpidletimeout;
1540		}
1541		/*
1542		 * TODO: besides regular ACK packets we can have other
1543		 * packets as well; it is yet to be determined how we
1544		 * should initialize the states in those cases
1545		 */
1546		break;
1547
1548	case TCPS_LISTEN: /* 1 */
1549		/* NOT USED */
1550		break;
1551
1552	case TCPS_SYN_SENT: /* 2 */
1553		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1554			/*
1555			 * We see an A from 'dir' which is in SYN_SENT
1556			 * state: 'dir' sent an A in response to an SA
1557			 * which it received, SYN_SENT -> ESTABLISHED
1558			 */
1559			state[dir] = TCPS_ESTABLISHED;
1560			*age = fr_tcpidletimeout;
1561		} else if (flags & TH_FIN) {
1562			/*
1563			 * We see an F from 'dir' which is in SYN_SENT
1564			 * state and wants to close its side of the
1565			 * connection; SYN_SENT -> FIN_WAIT_1
1566			 */
1567			state[dir] = TCPS_FIN_WAIT_1;
1568			*age = fr_tcpidletimeout; /* or fr_tcptimeout? */
1569		} else if ((flags & TH_OPENING) == TH_OPENING) {
1570			/*
1571			 * We see an SA from 'dir' which is already in
1572			 * SYN_SENT state, this means we have a
1573			 * simultaneous open; SYN_SENT -> SYN_RECEIVED
1574			 */
1575			state[dir] = TCPS_SYN_RECEIVED;
1576			*age = fr_tcptimeout;
1577		}
1578		break;
1579
1580	case TCPS_SYN_RECEIVED: /* 3 */
1581		if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1582			/*
1583			 * We see an A from 'dir' which was in SYN_RECEIVED
1584			 * state so it must now be in established state,
1585			 * SYN_RECEIVED -> ESTABLISHED
1586			 */
1587			state[dir] = TCPS_ESTABLISHED;
1588			*age = fr_tcpidletimeout;
1589		} else if (flags & TH_FIN) {
1590			/*
1591			 * We see an F from 'dir' which is in SYN_RECEIVED
1592			 * state and wants to close its side of the connection;
1593			 * SYN_RECEIVED -> FIN_WAIT_1
1594			 */
1595			state[dir] = TCPS_FIN_WAIT_1;
1596			*age = fr_tcpidletimeout;
1597		}
1598		break;
1599
1600	case TCPS_ESTABLISHED: /* 4 */
1601		if (flags & TH_FIN) {
1602			/*
1603			 * 'dir' closed its side of the connection; this
1604			 * gives us a half-closed connection;
1605			 * ESTABLISHED -> FIN_WAIT_1
1606			 */
1607			state[dir] = TCPS_FIN_WAIT_1;
1608			*age = fr_tcphalfclosed;
1609		} else if (flags & TH_ACK) {
1610			/* an ACK, should we exclude other flags here? */
1611			if (ostate == TCPS_FIN_WAIT_1) {
1612				/*
1613				 * We know the other side did an active close,
1614				 * so we are ACKing the recvd FIN packet (does
1615				 * the window matching code guarantee this?)
1616				 * and go into CLOSE_WAIT state; this gives us
1617				 * a half-closed connection
1618				 */
1619				state[dir] = TCPS_CLOSE_WAIT;
1620				*age = fr_tcphalfclosed;
1621			} else if (ostate < TCPS_CLOSE_WAIT)
1622				/*
1623				 * Still a fully established connection,
1624				 * reset timeout
1625				 */
1626				*age = fr_tcpidletimeout;
1627		}
1628		break;
1629
1630	case TCPS_CLOSE_WAIT: /* 5 */
1631		if (flags & TH_FIN) {
1632			/*
1633			 * Application closed and 'dir' sent a FIN, we're now
1634			 * going into LAST_ACK state
1635			 */
1636			*age  = fr_tcplastack;
1637			state[dir] = TCPS_LAST_ACK;
1638		} else {
1639			/*
1640			 * We remain in CLOSE_WAIT because the other side has
1641			 * closed already and we did not close our side yet;
1642			 * reset timeout
1643			 */
1644			*age  = fr_tcphalfclosed;
1645		}
1646		break;
1647
1648	case TCPS_FIN_WAIT_1: /* 6 */
1649		if ((flags & TH_ACK) && ostate > TCPS_CLOSE_WAIT) {
1650			/*
1651			 * If the other side is not active anymore it has sent
1652			 * us a FIN packet that we are ack'ing now with an ACK;
1653			 * this means both sides have now closed the connection
1654			 * and we go into TIME_WAIT
1655			 */
1656			/*
1657			 * XXX: how do we know we really are ACKing the FIN
1658			 * packet here? does the window code guarantee that?
1659			 */
1660			state[dir] = TCPS_TIME_WAIT;
1661			*age = fr_tcptimeout;
1662		} else
1663			/*
1664			 * We closed our side of the connection already but the
1665			 * other side is still active (ESTABLISHED/CLOSE_WAIT);
1666			 * continue with this half-closed connection
1667			 */
1668			*age = fr_tcphalfclosed;
1669		break;
1670
1671	case TCPS_CLOSING: /* 7 */
1672		/* NOT USED */
1673		break;
1674
1675	case TCPS_LAST_ACK: /* 8 */
1676		if (flags & TH_ACK) {
1677			if ((flags & TH_PUSH) || dlen)
1678				/*
1679				 * There is still data to be delivered, reset
1680				 * timeout
1681				 */
1682				*age  = fr_tcplastack;
1683		}
1684		/*
1685		 * We cannot detect when we go out of LAST_ACK state to CLOSED
1686		 * because that is based on the reception of ACK packets;
1687		 * ipfilter can only detect that a packet has been sent by a
1688		 * host
1689		 */
1690		break;
1691
1692	case TCPS_FIN_WAIT_2: /* 9 */
1693		/* NOT USED */
1694		break;
1695
1696	case TCPS_TIME_WAIT: /* 10 */
1697		/* we're in 2MSL timeout now */
1698		break;
1699	}
1700}
1701
1702
1703#ifdef	IPFILTER_LOG
1704void ipstate_log(is, type)
1705struct ipstate *is;
1706u_int type;
1707{
1708	struct	ipslog	ipsl;
1709	void *items[1];
1710	size_t sizes[1];
1711	int types[1];
1712
1713	ipsl.isl_type = type;
1714	ipsl.isl_pkts = is->is_pkts;
1715	ipsl.isl_bytes = is->is_bytes;
1716	ipsl.isl_src = is->is_src;
1717	ipsl.isl_dst = is->is_dst;
1718	ipsl.isl_p = is->is_p;
1719	ipsl.isl_v = is->is_v;
1720	ipsl.isl_flags = is->is_flags;
1721	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
1722		ipsl.isl_sport = is->is_sport;
1723		ipsl.isl_dport = is->is_dport;
1724		if (ipsl.isl_p == IPPROTO_TCP) {
1725			ipsl.isl_state[0] = is->is_state[0];
1726			ipsl.isl_state[1] = is->is_state[1];
1727		}
1728	} else if (ipsl.isl_p == IPPROTO_ICMP)
1729		ipsl.isl_itype = is->is_icmp.ics_type;
1730	else {
1731		ipsl.isl_ps.isl_filler[0] = 0;
1732		ipsl.isl_ps.isl_filler[1] = 0;
1733	}
1734	items[0] = &ipsl;
1735	sizes[0] = sizeof(ipsl);
1736	types[0] = 0;
1737
1738	(void) ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1);
1739}
1740#endif
1741
1742
1743#ifdef	USE_INET6
1744frentry_t *fr_checkicmp6matchingstate(ip, fin)
1745ip6_t *ip;
1746fr_info_t *fin;
1747{
1748	register ipstate_t *is, **isp;
1749	register u_short sport, dport;
1750	register u_char	pr;
1751	struct icmp6_hdr *ic, *oic;
1752	union i6addr dst, src;
1753	u_short savelen;
1754	fr_info_t ofin;
1755	tcphdr_t *tcp;
1756	frentry_t *fr;
1757	ip6_t *oip;
1758	int type;
1759	u_int hv;
1760
1761	/*
1762	 * Does it at least have the return (basic) IP header ?
1763	 * Only a basic IP header (no options) should be with
1764	 * an ICMP error header.
1765	 */
1766	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN))
1767		return NULL;
1768	ic = (struct icmp6_hdr *)fin->fin_dp;
1769	type = ic->icmp6_type;
1770	/*
1771	 * If it's not an error type, then return
1772	 */
1773	if ((type != ICMP6_DST_UNREACH) && (type != ICMP6_PACKET_TOO_BIG) &&
1774	    (type != ICMP6_TIME_EXCEEDED) && (type != ICMP6_PARAM_PROB))
1775		return NULL;
1776
1777	oip = (ip6_t *)((char *)ic + ICMPERR_ICMPHLEN);
1778	if (fin->fin_plen < sizeof(*oip))
1779		return NULL;
1780
1781	if (oip->ip6_nxt == IPPROTO_ICMPV6) {
1782		oic = (struct icmp6_hdr *)(oip + 1);
1783		/*
1784		 * a ICMP error can only be generated as a result of an
1785		 * ICMP query, not as the response on an ICMP error
1786		 *
1787		 * XXX theoretically ICMP_ECHOREP and the other reply's are
1788		 * ICMP query's as well, but adding them here seems strange XXX
1789		 */
1790		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
1791		    	return NULL;
1792
1793		/*
1794		 * perform a lookup of the ICMP packet in the state table
1795		 */
1796		hv = (pr = oip->ip6_nxt);
1797		src.in6 = oip->ip6_src;
1798		hv += src.in4.s_addr;
1799		dst.in6 = oip->ip6_dst;
1800		hv += dst.in4.s_addr;
1801		hv += oic->icmp6_id;
1802		hv += oic->icmp6_seq;
1803		hv %= fr_statesize;
1804
1805		oip->ip6_plen = ntohs(oip->ip6_plen);
1806		ofin.fin_v = 6;
1807		fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1808		oip->ip6_plen = htons(oip->ip6_plen);
1809		ofin.fin_ifp = fin->fin_ifp;
1810		ofin.fin_out = !fin->fin_out;
1811		ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1812
1813		READ_ENTER(&ipf_state);
1814		for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1815			if ((is->is_p == pr) &&
1816			    (oic->icmp6_id == is->is_icmp.ics_id) &&
1817			    (oic->icmp6_seq == is->is_icmp.ics_seq) &&
1818			    fr_matchsrcdst(is, src, dst, &ofin, NULL)) {
1819			    	/*
1820			    	 * in the state table ICMP query's are stored
1821			    	 * with the type of the corresponding ICMP
1822			    	 * response. Correct here
1823			    	 */
1824				if (((is->is_type == ICMP6_ECHO_REPLY) &&
1825				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
1826				     (is->is_type - 1 == oic->icmp6_type )) {
1827				    	ips_stats.iss_hits++;
1828    					is->is_pkts++;
1829					is->is_bytes += fin->fin_plen;
1830					return is->is_rule;
1831				}
1832			}
1833		RWLOCK_EXIT(&ipf_state);
1834
1835		return NULL;
1836	};
1837
1838	if ((oip->ip6_nxt != IPPROTO_TCP) && (oip->ip6_nxt != IPPROTO_UDP))
1839		return NULL;
1840	tcp = (tcphdr_t *)(oip + 1);
1841	dport = tcp->th_dport;
1842	sport = tcp->th_sport;
1843
1844	hv = (pr = oip->ip6_nxt);
1845	src.in6 = oip->ip6_src;
1846	hv += src.in4.s_addr;
1847	dst.in6 = oip->ip6_dst;
1848	hv += dst.in4.s_addr;
1849	hv += dport;
1850	hv += sport;
1851	hv %= fr_statesize;
1852	/*
1853	 * we make an fin entry to be able to feed it to
1854	 * matchsrcdst note that not all fields are encessary
1855	 * but this is the cleanest way. Note further we fill
1856	 * in fin_mp such that if someone uses it we'll get
1857	 * a kernel panic. fr_matchsrcdst does not use this.
1858	 *
1859	 * watch out here, as ip is in host order and oip in network
1860	 * order. Any change we make must be undone afterwards.
1861	 */
1862	savelen = oip->ip6_plen;
1863	oip->ip6_plen = ip->ip6_plen - sizeof(*ip) - ICMPERR_ICMPHLEN;
1864	ofin.fin_v = 6;
1865	fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
1866	oip->ip6_plen = savelen;
1867	ofin.fin_ifp = fin->fin_ifp;
1868	ofin.fin_out = !fin->fin_out;
1869	ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
1870	READ_ENTER(&ipf_state);
1871	for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1872		/*
1873		 * Only allow this icmp though if the
1874		 * encapsulated packet was allowed through the
1875		 * other way around. Note that the minimal amount
1876		 * of info present does not allow for checking against
1877		 * tcp internals such as seq and ack numbers.
1878		 */
1879		if ((is->is_p == pr) && (is->is_v == 6) &&
1880		    fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1881			fr = is->is_rule;
1882			ips_stats.iss_hits++;
1883			/*
1884			 * we must swap src and dst here because the icmp
1885			 * comes the other way around
1886			 */
1887			is->is_pkts++;
1888			is->is_bytes += fin->fin_plen;
1889			/*
1890			 * we deliberately do not touch the timeouts
1891			 * for the accompanying state table entry.
1892			 * It remains to be seen if that is correct. XXX
1893			 */
1894			RWLOCK_EXIT(&ipf_state);
1895			return fr;
1896		}
1897	}
1898	RWLOCK_EXIT(&ipf_state);
1899	return NULL;
1900}
1901#endif
1902