ip_state.c revision 153876
1/*	$FreeBSD: head/sys/contrib/ipfilter/netinet/ip_state.c 153876 2005-12-30 11:32:23Z guido $	*/
2
3/*
4 * Copyright (C) 1995-2003 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 */
8#if defined(KERNEL) || defined(_KERNEL)
9# undef KERNEL
10# undef _KERNEL
11# define        KERNEL	1
12# define        _KERNEL	1
13#endif
14#include <sys/errno.h>
15#include <sys/types.h>
16#include <sys/param.h>
17#include <sys/file.h>
18#if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
19    defined(_KERNEL)
20# include "opt_ipfilter_log.h"
21#endif
22#if defined(_KERNEL) && defined(__FreeBSD_version) && \
23    (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
24#include "opt_inet6.h"
25#endif
26#if !defined(_KERNEL) && !defined(__KERNEL__)
27# include <stdio.h>
28# include <stdlib.h>
29# include <string.h>
30# define _KERNEL
31# ifdef __OpenBSD__
32struct file;
33# endif
34# include <sys/uio.h>
35# undef _KERNEL
36#endif
37#if defined(_KERNEL) && (__FreeBSD_version >= 220000)
38# include <sys/filio.h>
39# include <sys/fcntl.h>
40# if (__FreeBSD_version >= 300000) && !defined(IPFILTER_LKM)
41#  include "opt_ipfilter.h"
42# endif
43#else
44# include <sys/ioctl.h>
45#endif
46#include <sys/time.h>
47#if !defined(linux)
48# include <sys/protosw.h>
49#endif
50#include <sys/socket.h>
51#if defined(_KERNEL)
52# include <sys/systm.h>
53# if !defined(__SVR4) && !defined(__svr4__)
54#  include <sys/mbuf.h>
55# endif
56#endif
57#if defined(__SVR4) || defined(__svr4__)
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#if !defined(linux)
77# include <netinet/ip_var.h>
78#endif
79#if !defined(__hpux) && !defined(linux)
80# include <netinet/tcp_fsm.h>
81#endif
82#include <netinet/udp.h>
83#include <netinet/ip_icmp.h>
84#include "netinet/ip_compat.h"
85#include <netinet/tcpip.h>
86#include "netinet/ip_fil.h"
87#include "netinet/ip_nat.h"
88#include "netinet/ip_frag.h"
89#include "netinet/ip_state.h"
90#include "netinet/ip_proxy.h"
91#ifdef	IPFILTER_SYNC
92#include "netinet/ip_sync.h"
93#endif
94#ifdef	IPFILTER_SCAN
95#include "netinet/ip_scan.h"
96#endif
97#ifdef	USE_INET6
98#include <netinet/icmp6.h>
99#endif
100#if (__FreeBSD_version >= 300000)
101# include <sys/malloc.h>
102# if defined(_KERNEL) && !defined(IPFILTER_LKM)
103#  include <sys/libkern.h>
104#  include <sys/systm.h>
105# endif
106#endif
107/* END OF INCLUDES */
108
109
110#if !defined(lint)
111static const char sccsid[] = "@(#)ip_state.c	1.8 6/5/96 (C) 1993-2000 Darren Reed";
112static const char rcsid[] = "@(#)$Id: ip_state.c,v 2.186.2.36 2005/12/04 22:25:36 darrenr Exp $";
113#endif
114
115static	ipstate_t **ips_table = NULL;
116static	u_long	*ips_seed = NULL;
117static	int	ips_num = 0;
118static	u_long ips_last_force_flush = 0;
119ips_stat_t ips_stats;
120
121#ifdef	USE_INET6
122static ipstate_t *fr_checkicmp6matchingstate __P((fr_info_t *));
123#endif
124static ipstate_t *fr_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
125				      i6addr_t *, tcphdr_t *, u_32_t));
126static ipstate_t *fr_checkicmpmatchingstate __P((fr_info_t *));
127static int fr_state_flush __P((int, int));
128static ips_stat_t *fr_statetstats __P((void));
129static void fr_delstate __P((ipstate_t *, int));
130static int fr_state_remove __P((caddr_t));
131static void fr_ipsmove __P((ipstate_t *, u_int));
132static int fr_tcpstate __P((fr_info_t *, tcphdr_t *, ipstate_t *));
133static int fr_tcpoptions __P((fr_info_t *, tcphdr_t *, tcpdata_t *));
134static ipstate_t *fr_stclone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
135static void fr_fixinisn __P((fr_info_t *, ipstate_t *));
136static void fr_fixoutisn __P((fr_info_t *, ipstate_t *));
137static void fr_checknewisn __P((fr_info_t *, ipstate_t *));
138
139int fr_stputent __P((caddr_t));
140int fr_stgetent __P((caddr_t));
141
142#define	ONE_DAY		IPF_TTLVAL(1 * 86400)	/* 1 day */
143#define	FIVE_DAYS	(5 * ONE_DAY)
144#define	DOUBLE_HASH(x)	(((x) + ips_seed[(x) % fr_statesize]) % fr_statesize)
145
146u_long	fr_tcpidletimeout = FIVE_DAYS,
147	fr_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL),
148	fr_tcplastack = IPF_TTLVAL(2 * TCP_MSL),
149	fr_tcptimeout = IPF_TTLVAL(2 * TCP_MSL),
150	fr_tcpclosed = IPF_TTLVAL(60),
151	fr_tcphalfclosed = IPF_TTLVAL(2 * 3600),	/* 2 hours */
152	fr_udptimeout = IPF_TTLVAL(120),
153	fr_udpacktimeout = IPF_TTLVAL(12),
154	fr_icmptimeout = IPF_TTLVAL(60),
155	fr_icmpacktimeout = IPF_TTLVAL(6),
156	fr_iptimeout = IPF_TTLVAL(60);
157int	fr_statemax = IPSTATE_MAX,
158	fr_statesize = IPSTATE_SIZE;
159int	fr_state_doflush = 0,
160	fr_state_lock = 0,
161	fr_state_maxbucket = 0,
162	fr_state_maxbucket_reset = 1,
163	fr_state_init = 0;
164ipftq_t	ips_tqtqb[IPF_TCP_NSTATES],
165	ips_udptq,
166	ips_udpacktq,
167	ips_iptq,
168	ips_icmptq,
169	ips_icmpacktq,
170	*ips_utqe = NULL;
171#ifdef	IPFILTER_LOG
172int	ipstate_logging = 1;
173#else
174int	ipstate_logging = 0;
175#endif
176ipstate_t *ips_list = NULL;
177
178
179/* ------------------------------------------------------------------------ */
180/* Function:    fr_stateinit                                                */
181/* Returns:     int - 0 == success, -1 == failure                           */
182/* Parameters:  Nil                                                         */
183/*                                                                          */
184/* Initialise all the global variables used within the state code.          */
185/* This action also includes initiailising locks.                           */
186/* ------------------------------------------------------------------------ */
187int fr_stateinit()
188{
189	int i;
190
191	KMALLOCS(ips_table, ipstate_t **, fr_statesize * sizeof(ipstate_t *));
192	if (ips_table == NULL)
193		return -1;
194	bzero((char *)ips_table, fr_statesize * sizeof(ipstate_t *));
195
196	KMALLOCS(ips_seed, u_long *, fr_statesize * sizeof(*ips_seed));
197	if (ips_seed == NULL)
198		return -2;
199	for (i = 0; i < fr_statesize; i++) {
200		/*
201		 * XXX - ips_seed[X] should be a random number of sorts.
202		 */
203#if  (__FreeBSD_version >= 400000)
204		ips_seed[i] = arc4random();
205#else
206		ips_seed[i] = ((u_long)ips_seed + i) * fr_statesize;
207		ips_seed[i] ^= 0xa5a55a5a;
208		ips_seed[i] *= (u_long)ips_seed;
209		ips_seed[i] ^= 0x5a5aa5a5;
210		ips_seed[i] *= fr_statemax;
211#endif
212	}
213
214	/* fill icmp reply type table */
215	for (i = 0; i <= ICMP_MAXTYPE; i++)
216		icmpreplytype4[i] = -1;
217	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
218	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
219	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
220	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
221#ifdef	USE_INET6
222	/* fill icmp reply type table */
223	for (i = 0; i <= ICMP6_MAXTYPE; i++)
224		icmpreplytype6[i] = -1;
225	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
226	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
227	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
228	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
229	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
230#endif
231
232	KMALLOCS(ips_stats.iss_bucketlen, u_long *,
233		 fr_statesize * sizeof(u_long));
234	if (ips_stats.iss_bucketlen == NULL)
235		return -1;
236	bzero((char *)ips_stats.iss_bucketlen, fr_statesize * sizeof(u_long));
237
238	if (fr_state_maxbucket == 0) {
239		for (i = fr_statesize; i > 0; i >>= 1)
240			fr_state_maxbucket++;
241		fr_state_maxbucket *= 2;
242	}
243
244	fr_sttab_init(ips_tqtqb);
245	ips_tqtqb[IPF_TCP_NSTATES - 1].ifq_next = &ips_udptq;
246	ips_udptq.ifq_ttl = (u_long)fr_udptimeout;
247	ips_udptq.ifq_ref = 1;
248	ips_udptq.ifq_head = NULL;
249	ips_udptq.ifq_tail = &ips_udptq.ifq_head;
250	MUTEX_INIT(&ips_udptq.ifq_lock, "ipftq udp tab");
251	ips_udptq.ifq_next = &ips_udpacktq;
252	ips_udpacktq.ifq_ttl = (u_long)fr_udpacktimeout;
253	ips_udpacktq.ifq_ref = 1;
254	ips_udpacktq.ifq_head = NULL;
255	ips_udpacktq.ifq_tail = &ips_udpacktq.ifq_head;
256	MUTEX_INIT(&ips_udpacktq.ifq_lock, "ipftq udpack tab");
257	ips_udpacktq.ifq_next = &ips_icmptq;
258	ips_icmptq.ifq_ttl = (u_long)fr_icmptimeout;
259	ips_icmptq.ifq_ref = 1;
260	ips_icmptq.ifq_head = NULL;
261	ips_icmptq.ifq_tail = &ips_icmptq.ifq_head;
262	MUTEX_INIT(&ips_icmptq.ifq_lock, "ipftq icmp tab");
263	ips_icmptq.ifq_next = &ips_icmpacktq;
264	ips_icmpacktq.ifq_ttl = (u_long)fr_icmpacktimeout;
265	ips_icmpacktq.ifq_ref = 1;
266	ips_icmpacktq.ifq_head = NULL;
267	ips_icmpacktq.ifq_tail = &ips_icmpacktq.ifq_head;
268	MUTEX_INIT(&ips_icmpacktq.ifq_lock, "ipftq icmpack tab");
269	ips_icmpacktq.ifq_next = &ips_iptq;
270	ips_iptq.ifq_ttl = (u_long)fr_iptimeout;
271	ips_iptq.ifq_ref = 1;
272	ips_iptq.ifq_head = NULL;
273	ips_iptq.ifq_tail = &ips_iptq.ifq_head;
274	MUTEX_INIT(&ips_iptq.ifq_lock, "ipftq ip tab");
275	ips_iptq.ifq_next = NULL;
276
277	RWLOCK_INIT(&ipf_state, "ipf IP state rwlock");
278	MUTEX_INIT(&ipf_stinsert, "ipf state insert mutex");
279	fr_state_init = 1;
280
281	ips_last_force_flush = fr_ticks;
282	return 0;
283}
284
285
286/* ------------------------------------------------------------------------ */
287/* Function:    fr_stateunload                                              */
288/* Returns:     Nil                                                         */
289/* Parameters:  Nil                                                         */
290/*                                                                          */
291/* Release and destroy any resources acquired or initialised so that        */
292/* IPFilter can be unloaded or re-initialised.                              */
293/* ------------------------------------------------------------------------ */
294void fr_stateunload()
295{
296	ipftq_t *ifq, *ifqnext;
297	ipstate_t *is;
298
299	while ((is = ips_list) != NULL)
300		fr_delstate(is, 0);
301
302	/*
303	 * Proxy timeout queues are not cleaned here because although they
304	 * exist on the state list, appr_unload is called after fr_stateunload
305	 * and the proxies actually are responsible for them being created.
306	 * Should the proxy timeouts have their own list?  There's no real
307	 * justification as this is the only complicationA
308	 */
309	for (ifq = ips_utqe; ifq != NULL; ifq = ifqnext) {
310		ifqnext = ifq->ifq_next;
311		if (((ifq->ifq_flags & IFQF_PROXY) == 0) &&
312		    (fr_deletetimeoutqueue(ifq) == 0))
313			fr_freetimeoutqueue(ifq);
314	}
315
316	ips_stats.iss_inuse = 0;
317	ips_num = 0;
318
319	if (fr_state_init == 1) {
320		fr_sttab_destroy(ips_tqtqb);
321		MUTEX_DESTROY(&ips_udptq.ifq_lock);
322		MUTEX_DESTROY(&ips_icmptq.ifq_lock);
323		MUTEX_DESTROY(&ips_udpacktq.ifq_lock);
324		MUTEX_DESTROY(&ips_icmpacktq.ifq_lock);
325		MUTEX_DESTROY(&ips_iptq.ifq_lock);
326	}
327
328	if (ips_table != NULL) {
329		KFREES(ips_table, fr_statesize * sizeof(*ips_table));
330		ips_table = NULL;
331	}
332
333	if (ips_seed != NULL) {
334		KFREES(ips_seed, fr_statesize * sizeof(*ips_seed));
335		ips_seed = NULL;
336	}
337
338	if (ips_stats.iss_bucketlen != NULL) {
339		KFREES(ips_stats.iss_bucketlen, fr_statesize * sizeof(u_long));
340		ips_stats.iss_bucketlen = NULL;
341	}
342
343	if (fr_state_maxbucket_reset == 1)
344		fr_state_maxbucket = 0;
345
346	if (fr_state_init == 1) {
347		fr_state_init = 0;
348		RW_DESTROY(&ipf_state);
349		MUTEX_DESTROY(&ipf_stinsert);
350	}
351}
352
353
354/* ------------------------------------------------------------------------ */
355/* Function:    fr_statetstats                                              */
356/* Returns:     ips_state_t* - pointer to state stats structure             */
357/* Parameters:  Nil                                                         */
358/*                                                                          */
359/* Put all the current numbers and pointers into a single struct and return */
360/* a pointer to it.                                                         */
361/* ------------------------------------------------------------------------ */
362static ips_stat_t *fr_statetstats()
363{
364	ips_stats.iss_active = ips_num;
365	ips_stats.iss_statesize = fr_statesize;
366	ips_stats.iss_statemax = fr_statemax;
367	ips_stats.iss_table = ips_table;
368	ips_stats.iss_list = ips_list;
369	ips_stats.iss_ticks = fr_ticks;
370	return &ips_stats;
371}
372
373/* ------------------------------------------------------------------------ */
374/* Function:    fr_state_remove                                             */
375/* Returns:     int - 0 == success, != 0 == failure                         */
376/* Parameters:  data(I) - pointer to state structure to delete from table   */
377/*                                                                          */
378/* Search for a state structure that matches the one passed, according to   */
379/* the IP addresses and other protocol specific information.                */
380/* ------------------------------------------------------------------------ */
381static int fr_state_remove(data)
382caddr_t data;
383{
384	ipstate_t *sp, st;
385	int error;
386
387	sp = &st;
388	error = fr_inobj(data, &st, IPFOBJ_IPSTATE);
389	if (error)
390		return EFAULT;
391
392	WRITE_ENTER(&ipf_state);
393	for (sp = ips_list; sp; sp = sp->is_next)
394		if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
395		    !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
396			  sizeof(st.is_src)) &&
397		    !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_src,
398			  sizeof(st.is_dst)) &&
399		    !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
400			  sizeof(st.is_ps))) {
401			fr_delstate(sp, ISL_REMOVE);
402			RWLOCK_EXIT(&ipf_state);
403			return 0;
404		}
405	RWLOCK_EXIT(&ipf_state);
406	return ESRCH;
407}
408
409
410/* ------------------------------------------------------------------------ */
411/* Function:    fr_state_ioctl                                              */
412/* Returns:     int - 0 == success, != 0 == failure                         */
413/* Parameters:  data(I) - pointer to ioctl data                             */
414/*              cmd(I)  - ioctl command integer                             */
415/*              mode(I) - file mode bits used with open                     */
416/*                                                                          */
417/* Processes an ioctl call made to operate on the IP Filter state device.   */
418/* ------------------------------------------------------------------------ */
419int fr_state_ioctl(data, cmd, mode)
420caddr_t data;
421ioctlcmd_t cmd;
422int mode;
423{
424	int arg, ret, error = 0;
425
426	switch (cmd)
427	{
428	/*
429	 * Delete an entry from the state table.
430	 */
431	case SIOCDELST :
432		error = fr_state_remove(data);
433		break;
434	/*
435	 * Flush the state table
436	 */
437	case SIOCIPFFL :
438		BCOPYIN(data, (char *)&arg, sizeof(arg));
439		if (arg == 0 || arg == 1) {
440			WRITE_ENTER(&ipf_state);
441			ret = fr_state_flush(arg, 4);
442			RWLOCK_EXIT(&ipf_state);
443			BCOPYOUT((char *)&ret, data, sizeof(ret));
444		} else
445			error = EINVAL;
446		break;
447#ifdef	USE_INET6
448	case SIOCIPFL6 :
449		BCOPYIN(data, (char *)&arg, sizeof(arg));
450		if (arg == 0 || arg == 1) {
451			WRITE_ENTER(&ipf_state);
452			ret = fr_state_flush(arg, 6);
453			RWLOCK_EXIT(&ipf_state);
454			BCOPYOUT((char *)&ret, data, sizeof(ret));
455		} else
456			error = EINVAL;
457		break;
458#endif
459#ifdef	IPFILTER_LOG
460	/*
461	 * Flush the state log.
462	 */
463	case SIOCIPFFB :
464		if (!(mode & FWRITE))
465			error = EPERM;
466		else {
467			int tmp;
468
469			tmp = ipflog_clear(IPL_LOGSTATE);
470			BCOPYOUT((char *)&tmp, data, sizeof(tmp));
471		}
472		break;
473	/*
474	 * Turn logging of state information on/off.
475	 */
476	case SIOCSETLG :
477		if (!(mode & FWRITE))
478			error = EPERM;
479		else {
480			BCOPYIN((char *)data, (char *)&ipstate_logging,
481				sizeof(ipstate_logging));
482		}
483		break;
484	/*
485	 * Return the current state of logging.
486	 */
487	case SIOCGETLG :
488		BCOPYOUT((char *)&ipstate_logging, (char *)data,
489			 sizeof(ipstate_logging));
490		break;
491	/*
492	 * Return the number of bytes currently waiting to be read.
493	 */
494	case FIONREAD :
495		arg = iplused[IPL_LOGSTATE];	/* returned in an int */
496		BCOPYOUT((char *)&arg, data, sizeof(arg));
497		break;
498#endif
499	/*
500	 * Get the current state statistics.
501	 */
502	case SIOCGETFS :
503		error = fr_outobj(data, fr_statetstats(), IPFOBJ_STATESTAT);
504		break;
505	/*
506	 * Lock/Unlock the state table.  (Locking prevents any changes, which
507	 * means no packets match).
508	 */
509	case SIOCSTLCK :
510		if (!(mode & FWRITE)) {
511			error = EPERM;
512		} else {
513			fr_lock(data, &fr_state_lock);
514		}
515		break;
516	/*
517	 * Add an entry to the current state table.
518	 */
519	case SIOCSTPUT :
520		if (!fr_state_lock || !(mode &FWRITE)) {
521			error = EACCES;
522			break;
523		}
524		error = fr_stputent(data);
525		break;
526	/*
527	 * Get a state table entry.
528	 */
529	case SIOCSTGET :
530		if (!fr_state_lock) {
531			error = EACCES;
532			break;
533		}
534		error = fr_stgetent(data);
535		break;
536	default :
537		error = EINVAL;
538		break;
539	}
540	return error;
541}
542
543
544/* ------------------------------------------------------------------------ */
545/* Function:    fr_stgetent                                                 */
546/* Returns:     int - 0 == success, != 0 == failure                         */
547/* Parameters:  data(I) - pointer to state structure to retrieve from table */
548/*                                                                          */
549/* Copy out state information from the kernel to a user space process.  If  */
550/* there is a filter rule associated with the state entry, copy that out    */
551/* as well.  The entry to copy out is taken from the value of "ips_next" in */
552/* the struct passed in and if not null and not found in the list of current*/
553/* state entries, the retrieval fails.                                      */
554/* ------------------------------------------------------------------------ */
555int fr_stgetent(data)
556caddr_t data;
557{
558	ipstate_t *is, *isn;
559	ipstate_save_t ips;
560	int error;
561
562	error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
563	if (error)
564		return EFAULT;
565
566	isn = ips.ips_next;
567	if (isn == NULL) {
568		isn = ips_list;
569		if (isn == NULL) {
570			if (ips.ips_next == NULL)
571				return ENOENT;
572			return 0;
573		}
574	} else {
575		/*
576		 * Make sure the pointer we're copying from exists in the
577		 * current list of entries.  Security precaution to prevent
578		 * copying of random kernel data.
579		 */
580		for (is = ips_list; is; is = is->is_next)
581			if (is == isn)
582				break;
583		if (!is)
584			return ESRCH;
585	}
586	ips.ips_next = isn->is_next;
587	bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
588	ips.ips_rule = isn->is_rule;
589	if (isn->is_rule != NULL)
590		bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
591		      sizeof(ips.ips_fr));
592	error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
593	if (error)
594		return EFAULT;
595	return 0;
596}
597
598
599/* ------------------------------------------------------------------------ */
600/* Function:    fr_stputent                                                 */
601/* Returns:     int - 0 == success, != 0 == failure                         */
602/* Parameters:  data(I) - pointer to state information struct               */
603/*                                                                          */
604/* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
605/* the state table.  If the state info. includes a pointer to a filter rule */
606/* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
607/* output.                                                                  */
608/* ------------------------------------------------------------------------ */
609int fr_stputent(data)
610caddr_t data;
611{
612	ipstate_t *is, *isn;
613	ipstate_save_t ips;
614	int error, out, i;
615	frentry_t *fr;
616	char *name;
617
618	error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
619	if (error)
620		return EFAULT;
621
622	KMALLOC(isn, ipstate_t *);
623	if (isn == NULL)
624		return ENOMEM;
625
626	bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
627	bzero((char *)isn, offsetof(struct ipstate, is_pkts));
628	isn->is_sti.tqe_pnext = NULL;
629	isn->is_sti.tqe_next = NULL;
630	isn->is_sti.tqe_ifq = NULL;
631	isn->is_sti.tqe_parent = isn;
632	isn->is_ifp[0] = NULL;
633	isn->is_ifp[1] = NULL;
634	isn->is_ifp[2] = NULL;
635	isn->is_ifp[3] = NULL;
636	isn->is_sync = NULL;
637	fr = ips.ips_rule;
638
639	if (fr == NULL) {
640		READ_ENTER(&ipf_state);
641		fr_stinsert(isn, 0);
642		MUTEX_EXIT(&isn->is_lock);
643		RWLOCK_EXIT(&ipf_state);
644		return 0;
645	}
646
647	if (isn->is_flags & SI_NEWFR) {
648		KMALLOC(fr, frentry_t *);
649		if (fr == NULL) {
650			KFREE(isn);
651			return ENOMEM;
652		}
653		bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
654		out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
655		isn->is_rule = fr;
656		ips.ips_is.is_rule = fr;
657		MUTEX_NUKE(&fr->fr_lock);
658		MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
659
660		/*
661		 * Look up all the interface names in the rule.
662		 */
663		for (i = 0; i < 4; i++) {
664			name = fr->fr_ifnames[i];
665			fr->fr_ifas[i] = fr_resolvenic(name, fr->fr_v);
666			name = isn->is_ifname[i];
667			isn->is_ifp[i] = fr_resolvenic(name, isn->is_v);
668		}
669
670		fr->fr_ref = 0;
671		fr->fr_dsize = 0;
672		fr->fr_data = NULL;
673
674		fr_resolvedest(&fr->fr_tif, fr->fr_v);
675		fr_resolvedest(&fr->fr_dif, fr->fr_v);
676
677		/*
678		 * send a copy back to userland of what we ended up
679		 * to allow for verification.
680		 */
681		error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
682		if (error) {
683			KFREE(isn);
684			MUTEX_DESTROY(&fr->fr_lock);
685			KFREE(fr);
686			return EFAULT;
687		}
688		READ_ENTER(&ipf_state);
689		fr_stinsert(isn, 0);
690		MUTEX_EXIT(&isn->is_lock);
691		RWLOCK_EXIT(&ipf_state);
692
693	} else {
694		READ_ENTER(&ipf_state);
695		for (is = ips_list; is; is = is->is_next)
696			if (is->is_rule == fr) {
697				fr_stinsert(isn, 0);
698				MUTEX_EXIT(&isn->is_lock);
699				break;
700			}
701
702		if (is == NULL) {
703			KFREE(isn);
704			isn = NULL;
705		}
706		RWLOCK_EXIT(&ipf_state);
707
708		return (isn == NULL) ? ESRCH : 0;
709	}
710
711	return 0;
712}
713
714
715/* ------------------------------------------------------------------------ */
716/* Function:   fr_stinsert                                                  */
717/* Returns:    Nil                                                          */
718/* Parameters: is(I)  - pointer to state structure                          */
719/*             rev(I) - flag indicating forward/reverse direction of packet */
720/*                                                                          */
721/* Inserts a state structure into the hash table (for lookups) and the list */
722/* of state entries (for enumeration).  Resolves all of the interface names */
723/* to pointers and adjusts running stats for the hash table as appropriate. */
724/*                                                                          */
725/* Locking: it is assumed that some kind of lock on ipf_state is held.      */
726/*          Exits with is_lock initialised and held.                        */
727/* ------------------------------------------------------------------------ */
728void fr_stinsert(is, rev)
729ipstate_t *is;
730int rev;
731{
732	frentry_t *fr;
733	u_int hv;
734	int i;
735
736	MUTEX_INIT(&is->is_lock, "ipf state entry");
737
738	fr = is->is_rule;
739	if (fr != NULL) {
740		MUTEX_ENTER(&fr->fr_lock);
741		fr->fr_ref++;
742		fr->fr_statecnt++;
743		MUTEX_EXIT(&fr->fr_lock);
744	}
745
746	/*
747	 * Look up all the interface names in the state entry.
748	 */
749	for (i = 0; i < 4; i++) {
750		if (is->is_ifp[i] != NULL)
751			continue;
752		is->is_ifp[i] = fr_resolvenic(is->is_ifname[i], is->is_v);
753	}
754
755	/*
756	 * If we could trust is_hv, then the modulous would not be needed, but
757	 * when running with IPFILTER_SYNC, this stops bad values.
758	 */
759	hv = is->is_hv % fr_statesize;
760	is->is_hv = hv;
761
762	/*
763	 * We need to get both of these locks...the first because it is
764	 * possible that once the insert is complete another packet might
765	 * come along, match the entry and want to update it.
766	 */
767	MUTEX_ENTER(&is->is_lock);
768	MUTEX_ENTER(&ipf_stinsert);
769
770	/*
771	 * add into list table.
772	 */
773	if (ips_list != NULL)
774		ips_list->is_pnext = &is->is_next;
775	is->is_pnext = &ips_list;
776	is->is_next = ips_list;
777	ips_list = is;
778
779	if (ips_table[hv] != NULL)
780		ips_table[hv]->is_phnext = &is->is_hnext;
781	else
782		ips_stats.iss_inuse++;
783	is->is_phnext = ips_table + hv;
784	is->is_hnext = ips_table[hv];
785	ips_table[hv] = is;
786	ips_stats.iss_bucketlen[hv]++;
787	ips_num++;
788	MUTEX_EXIT(&ipf_stinsert);
789
790	fr_setstatequeue(is, rev);
791}
792
793
794/* ------------------------------------------------------------------------ */
795/* Function:    fr_addstate                                                 */
796/* Returns:     ipstate_t* - NULL == failure, else pointer to new state     */
797/* Parameters:  fin(I)    - pointer to packet information                   */
798/*              stsave(O) - pointer to place to save pointer to created     */
799/*                          state structure.                                */
800/*              flags(I)  - flags to use when creating the structure        */
801/*                                                                          */
802/* Creates a new IP state structure from the packet information collected.  */
803/* Inserts it into the state table and appends to the bottom of the active  */
804/* list.  If the capacity of the table has reached the maximum allowed then */
805/* the call will fail and a flush is scheduled for the next timeout call.   */
806/* ------------------------------------------------------------------------ */
807ipstate_t *fr_addstate(fin, stsave, flags)
808fr_info_t *fin;
809ipstate_t **stsave;
810u_int flags;
811{
812	ipstate_t *is, ips;
813	struct icmp *ic;
814	u_int pass, hv;
815	frentry_t *fr;
816	tcphdr_t *tcp;
817	grehdr_t *gre;
818	void *ifp;
819	int out;
820
821	if (fr_state_lock ||
822	    (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
823		return NULL;
824
825	if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN))
826		return NULL;
827
828	fr = fin->fin_fr;
829	if ((fr->fr_statemax == 0) && (ips_num == fr_statemax)) {
830		ATOMIC_INCL(ips_stats.iss_max);
831		fr_state_doflush = 1;
832		return NULL;
833	}
834
835	/*
836	 * If a "keep state" rule has reached the maximum number of references
837	 * to it, then schedule an automatic flush in case we can clear out
838	 * some "dead old wood".
839	 */
840	MUTEX_ENTER(&fr->fr_lock);
841	if ((fr != NULL) && (fr->fr_statemax != 0) &&
842	    (fr->fr_statecnt >= fr->fr_statemax)) {
843		MUTEX_EXIT(&fr->fr_lock);
844		ATOMIC_INCL(ips_stats.iss_maxref);
845		fr_state_doflush = 1;
846		return NULL;
847	}
848	fr->fr_statecnt++;
849	MUTEX_EXIT(&fr->fr_lock);
850
851	pass = (fr == NULL) ? 0 : fr->fr_flags;
852
853	ic = NULL;
854	tcp = NULL;
855	out = fin->fin_out;
856	is = &ips;
857	bzero((char *)is, sizeof(*is));
858	is->is_die = 1 + fr_ticks;
859
860	/*
861	 * Copy and calculate...
862	 */
863	hv = (is->is_p = fin->fin_fi.fi_p);
864	is->is_src = fin->fin_fi.fi_src;
865	hv += is->is_saddr;
866	is->is_dst = fin->fin_fi.fi_dst;
867	hv += is->is_daddr;
868#ifdef	USE_INET6
869	if (fin->fin_v == 6) {
870		/*
871		 * For ICMPv6, we check to see if the destination address is
872		 * a multicast address.  If it is, do not include it in the
873		 * calculation of the hash because the correct reply will come
874		 * back from a real address, not a multicast address.
875		 */
876		if ((is->is_p == IPPROTO_ICMPV6) &&
877		    IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
878			/*
879			 * So you can do keep state with neighbour discovery.
880			 *
881			 * Here we could use the address from the neighbour
882			 * solicit message to put in the state structure and
883			 * we could use that without a wildcard flag too...
884			 */
885			flags |= SI_W_DADDR;
886			hv -= is->is_daddr;
887		} else {
888			hv += is->is_dst.i6[1];
889			hv += is->is_dst.i6[2];
890			hv += is->is_dst.i6[3];
891		}
892		hv += is->is_src.i6[1];
893		hv += is->is_src.i6[2];
894		hv += is->is_src.i6[3];
895	}
896#endif
897
898	switch (is->is_p)
899	{
900#ifdef	USE_INET6
901	case IPPROTO_ICMPV6 :
902		ic = fin->fin_dp;
903
904		switch (ic->icmp_type)
905		{
906		case ICMP6_ECHO_REQUEST :
907			is->is_icmp.ici_type = ic->icmp_type;
908			hv += (is->is_icmp.ici_id = ic->icmp_id);
909			break;
910		case ICMP6_MEMBERSHIP_QUERY :
911		case ND_ROUTER_SOLICIT :
912		case ND_NEIGHBOR_SOLICIT :
913		case ICMP6_NI_QUERY :
914			is->is_icmp.ici_type = ic->icmp_type;
915			break;
916		default :
917			return NULL;
918		}
919		ATOMIC_INCL(ips_stats.iss_icmp);
920		break;
921#endif
922	case IPPROTO_ICMP :
923		ic = fin->fin_dp;
924
925		switch (ic->icmp_type)
926		{
927		case ICMP_ECHO :
928		case ICMP_TSTAMP :
929		case ICMP_IREQ :
930		case ICMP_MASKREQ :
931			is->is_icmp.ici_type = ic->icmp_type;
932			hv += (is->is_icmp.ici_id = ic->icmp_id);
933			break;
934		default :
935			return NULL;
936		}
937		ATOMIC_INCL(ips_stats.iss_icmp);
938		break;
939
940	case IPPROTO_GRE :
941		gre = fin->fin_dp;
942
943		is->is_gre.gs_flags = gre->gr_flags;
944		is->is_gre.gs_ptype = gre->gr_ptype;
945		if (GRE_REV(is->is_gre.gs_flags) == 1) {
946			is->is_call[0] = fin->fin_data[0];
947			is->is_call[1] = fin->fin_data[1];
948		}
949		break;
950
951	case IPPROTO_TCP :
952		tcp = fin->fin_dp;
953
954		if (tcp->th_flags & TH_RST)
955			return NULL;
956		/*
957		 * The endian of the ports doesn't matter, but the ack and
958		 * sequence numbers do as we do mathematics on them later.
959		 */
960		is->is_sport = htons(fin->fin_data[0]);
961		is->is_dport = htons(fin->fin_data[1]);
962		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
963			hv += is->is_sport;
964			hv += is->is_dport;
965		}
966
967		/*
968		 * If this is a real packet then initialise fields in the
969		 * state information structure from the TCP header information.
970		 */
971
972		is->is_maxdwin = 1;
973		is->is_maxswin = ntohs(tcp->th_win);
974		if (is->is_maxswin == 0)
975			is->is_maxswin = 1;
976
977		if ((fin->fin_flx & FI_IGNORE) == 0) {
978			is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
979				      (TCP_OFF(tcp) << 2) +
980				      ((tcp->th_flags & TH_SYN) ? 1 : 0) +
981				      ((tcp->th_flags & TH_FIN) ? 1 : 0);
982			is->is_maxsend = is->is_send;
983
984			/*
985			 * Window scale option is only present in
986			 * SYN/SYN-ACK packet.
987			 */
988			if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
989			    TH_SYN &&
990			    (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
991				if (fr_tcpoptions(fin, tcp,
992					      &is->is_tcp.ts_data[0]) == -1) {
993					fin->fin_flx |= FI_BAD;
994				}
995			}
996
997			if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
998				fr_checknewisn(fin, is);
999				fr_fixoutisn(fin, is);
1000			}
1001
1002			if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1003				flags |= IS_TCPFSM;
1004			else {
1005				is->is_maxdwin = is->is_maxswin * 2;
1006				is->is_dend = ntohl(tcp->th_ack);
1007				is->is_maxdend = ntohl(tcp->th_ack);
1008				is->is_maxdwin *= 2;
1009			}
1010		}
1011
1012		/*
1013		 * If we're creating state for a starting connection, start the
1014		 * timer on it as we'll never see an error if it fails to
1015		 * connect.
1016		 */
1017		ATOMIC_INCL(ips_stats.iss_tcp);
1018		break;
1019
1020	case IPPROTO_UDP :
1021		tcp = fin->fin_dp;
1022
1023		is->is_sport = htons(fin->fin_data[0]);
1024		is->is_dport = htons(fin->fin_data[1]);
1025		if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1026			hv += tcp->th_dport;
1027			hv += tcp->th_sport;
1028		}
1029		ATOMIC_INCL(ips_stats.iss_udp);
1030		break;
1031
1032	default :
1033		break;
1034	}
1035	hv = DOUBLE_HASH(hv);
1036	is->is_hv = hv;
1037	is->is_rule = fr;
1038	is->is_flags = flags & IS_INHERITED;
1039
1040	/*
1041	 * Look for identical state.
1042	 */
1043	for (is = ips_table[is->is_hv % fr_statesize]; is != NULL;
1044	     is = is->is_hnext) {
1045		if (bcmp(&ips.is_src, &is->is_src,
1046			 offsetof(struct ipstate, is_ps) -
1047			 offsetof(struct ipstate, is_src)) == 0)
1048			break;
1049	}
1050	if (is != NULL)
1051		goto cantaddstate;
1052
1053	if (ips_stats.iss_bucketlen[hv] >= fr_state_maxbucket) {
1054		ATOMIC_INCL(ips_stats.iss_bucketfull);
1055		goto cantaddstate;
1056	}
1057	KMALLOC(is, ipstate_t *);
1058	if (is == NULL) {
1059		ATOMIC_INCL(ips_stats.iss_nomem);
1060		goto cantaddstate;
1061	}
1062	bcopy((char *)&ips, (char *)is, sizeof(*is));
1063	/*
1064	 * Do not do the modulous here, it is done in fr_stinsert().
1065	 */
1066	if (fr != NULL) {
1067		(void) strncpy(is->is_group, fr->fr_group, FR_GROUPLEN);
1068		if (fr->fr_age[0] != 0) {
1069			is->is_tqehead[0] = fr_addtimeoutqueue(&ips_utqe,
1070							       fr->fr_age[0]);
1071			is->is_sti.tqe_flags |= TQE_RULEBASED;
1072		}
1073		if (fr->fr_age[1] != 0) {
1074			is->is_tqehead[1] = fr_addtimeoutqueue(&ips_utqe,
1075							       fr->fr_age[1]);
1076			is->is_sti.tqe_flags |= TQE_RULEBASED;
1077		}
1078
1079		is->is_tag = fr->fr_logtag;
1080
1081		is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1082		is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1083		is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1084
1085		if (((ifp = fr->fr_ifas[1]) != NULL) &&
1086		    (ifp != (void *)-1)) {
1087			COPYIFNAME(ifp, is->is_ifname[(out << 1) + 1]);
1088		}
1089		if (((ifp = fr->fr_ifas[2]) != NULL) &&
1090		    (ifp != (void *)-1)) {
1091			COPYIFNAME(ifp, is->is_ifname[(1 - out) << 1]);
1092		}
1093		if (((ifp = fr->fr_ifas[3]) != NULL) &&
1094		    (ifp != (void *)-1)) {
1095			COPYIFNAME(ifp, is->is_ifname[((1 - out) << 1) + 1]);
1096		}
1097	} else {
1098		pass = fr_flags;
1099		is->is_tag = FR_NOLOGTAG;
1100	}
1101
1102	is->is_ifp[out << 1] = fin->fin_ifp;
1103	if (fin->fin_ifp != NULL) {
1104		COPYIFNAME(fin->fin_ifp, is->is_ifname[out << 1]);
1105	}
1106
1107	/*
1108	 * It may seem strange to set is_ref to 2, but fr_check() will call
1109	 * fr_statederef() after calling fr_addstate() and the idea is to
1110	 * have it exist at the end of fr_check() with is_ref == 1.
1111	 */
1112	is->is_ref = 2;
1113	is->is_pass = pass;
1114	is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1115	is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1116	is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1117	is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1118	if ((fin->fin_flx & FI_IGNORE) == 0) {
1119		is->is_pkts[out] = 1;
1120		is->is_bytes[out] = fin->fin_plen;
1121		is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1122		is->is_flx[out][0] &= ~FI_OOW;
1123	}
1124
1125	if (pass & FR_STSTRICT)
1126		is->is_flags |= IS_STRICT;
1127
1128	if (pass & FR_STATESYNC)
1129		is->is_flags |= IS_STATESYNC;
1130
1131	/*
1132	 * We want to check everything that is a property of this packet,
1133	 * but we don't (automatically) care about it's fragment status as
1134	 * this may change.
1135	 */
1136	is->is_v = fin->fin_v;
1137	is->is_opt[0] = fin->fin_optmsk;
1138	is->is_optmsk[0] = 0xffffffff;
1139	is->is_optmsk[1] = 0xffffffff;
1140	if (is->is_v == 6) {
1141		is->is_opt[0] &= ~0x8;
1142		is->is_optmsk[0] &= ~0x8;
1143		is->is_optmsk[1] &= ~0x8;
1144	}
1145	is->is_sec = fin->fin_secmsk;
1146	is->is_secmsk = 0xffff;
1147	is->is_auth = fin->fin_auth;
1148	is->is_authmsk = 0xffff;
1149	if (flags & (SI_WILDP|SI_WILDA)) {
1150		ATOMIC_INCL(ips_stats.iss_wild);
1151	}
1152	is->is_rulen = fin->fin_rule;
1153
1154
1155	if (pass & FR_LOGFIRST)
1156		is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1157
1158	READ_ENTER(&ipf_state);
1159	is->is_me = stsave;
1160
1161	fr_stinsert(is, fin->fin_rev);
1162
1163	if (fin->fin_p == IPPROTO_TCP) {
1164		/*
1165		* If we're creating state for a starting connection, start the
1166		* timer on it as we'll never see an error if it fails to
1167		* connect.
1168		*/
1169		(void) fr_tcp_age(&is->is_sti, fin, ips_tqtqb, is->is_flags);
1170		MUTEX_EXIT(&is->is_lock);
1171#ifdef	IPFILTER_SCAN
1172		if ((is->is_flags & SI_CLONE) == 0)
1173			(void) ipsc_attachis(is);
1174#endif
1175	} else {
1176		MUTEX_EXIT(&is->is_lock);
1177	}
1178#ifdef	IPFILTER_SYNC
1179	if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1180		is->is_sync = ipfsync_new(SMC_STATE, fin, is);
1181#endif
1182	if (ipstate_logging)
1183		ipstate_log(is, ISL_NEW);
1184
1185	RWLOCK_EXIT(&ipf_state);
1186	fin->fin_state = is;
1187	fin->fin_rev = IP6_NEQ(&is->is_dst, &fin->fin_daddr);
1188	fin->fin_flx |= FI_STATE;
1189	if (fin->fin_flx & FI_FRAG)
1190		(void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
1191
1192	return is;
1193
1194cantaddstate:
1195	if (fr != NULL) {
1196		MUTEX_ENTER(&fr->fr_lock);
1197		fr->fr_statecnt--;
1198		MUTEX_EXIT(&fr->fr_lock);
1199	}
1200	return NULL;
1201}
1202
1203
1204/* ------------------------------------------------------------------------ */
1205/* Function:    fr_tcpoptions                                               */
1206/* Returns:     int - 1 == packet matches state entry, 0 == it does not,    */
1207/*                   -1 == packet has bad TCP options data                  */
1208/* Parameters:  fin(I) - pointer to packet information                      */
1209/*              tcp(I) - pointer to TCP packet header                       */
1210/*              td(I)  - pointer to TCP data held as part of the state      */
1211/*                                                                          */
1212/* Look after the TCP header for any options and deal with those that are   */
1213/* present.  Record details about those that we recogise.                   */
1214/* ------------------------------------------------------------------------ */
1215static int fr_tcpoptions(fin, tcp, td)
1216fr_info_t *fin;
1217tcphdr_t *tcp;
1218tcpdata_t *td;
1219{
1220	int off, mlen, ol, i, len, retval;
1221	char buf[64], *s, opt;
1222	mb_t *m = NULL;
1223
1224	len = (TCP_OFF(tcp) << 2);
1225	if (fin->fin_dlen < len)
1226		return 0;
1227	len -= sizeof(*tcp);
1228
1229	off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1230
1231	m = fin->fin_m;
1232	mlen = MSGDSIZE(m) - off;
1233	if (len > mlen) {
1234		len = mlen;
1235		retval = 0;
1236	} else {
1237		retval = 1;
1238	}
1239
1240	COPYDATA(m, off, len, buf);
1241
1242	for (s = buf; len > 0; ) {
1243		opt = *s;
1244		if (opt == TCPOPT_EOL)
1245			break;
1246		else if (opt == TCPOPT_NOP)
1247			ol = 1;
1248		else {
1249			if (len < 2)
1250				break;
1251			ol = (int)*(s + 1);
1252			if (ol < 2 || ol > len)
1253				break;
1254
1255			/*
1256			 * Extract the TCP options we are interested in out of
1257			 * the header and store them in the the tcpdata struct.
1258			 */
1259			switch (opt)
1260			{
1261			case TCPOPT_WINDOW :
1262				if (ol == TCPOLEN_WINDOW) {
1263					i = (int)*(s + 2);
1264					if (i > TCP_WSCALE_MAX)
1265						i = TCP_WSCALE_MAX;
1266					else if (i < 0)
1267						i = 0;
1268					td->td_winscale = i;
1269					td->td_winflags |= TCP_WSCALE_SEEN|
1270							   TCP_WSCALE_FIRST;
1271				} else
1272					retval = -1;
1273				break;
1274			case TCPOPT_MAXSEG :
1275				/*
1276				 * So, if we wanted to set the TCP MAXSEG,
1277				 * it should be done here...
1278				 */
1279				if (ol == TCPOLEN_MAXSEG) {
1280					i = (int)*(s + 2);
1281					i <<= 8;
1282					i += (int)*(s + 3);
1283					td->td_maxseg = i;
1284				} else
1285					retval = -1;
1286				break;
1287			case TCPOPT_SACK_PERMITTED :
1288				if (ol == TCPOLEN_SACK_PERMITTED)
1289					td->td_winflags |= TCP_SACK_PERMIT;
1290				else
1291					retval = -1;
1292				break;
1293			}
1294		}
1295		len -= ol;
1296		s += ol;
1297	}
1298	return retval;
1299}
1300
1301
1302/* ------------------------------------------------------------------------ */
1303/* Function:    fr_tcpstate                                                 */
1304/* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1305/* Parameters:  fin(I)   - pointer to packet information                    */
1306/*              tcp(I)   - pointer to TCP packet header                     */
1307/*              is(I)  - pointer to master state structure                  */
1308/*                                                                          */
1309/* Check to see if a packet with TCP headers fits within the TCP window.    */
1310/* Change timeout depending on whether new packet is a SYN-ACK returning    */
1311/* for a SYN or a RST or FIN which indicate time to close up shop.          */
1312/* ------------------------------------------------------------------------ */
1313static int fr_tcpstate(fin, tcp, is)
1314fr_info_t *fin;
1315tcphdr_t *tcp;
1316ipstate_t *is;
1317{
1318	int source, ret = 0, flags;
1319	tcpdata_t  *fdata, *tdata;
1320
1321	source = !fin->fin_rev;
1322	if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
1323	    (ntohs(is->is_sport) != fin->fin_data[0]))
1324		source = 0;
1325	fdata = &is->is_tcp.ts_data[!source];
1326	tdata = &is->is_tcp.ts_data[source];
1327
1328	MUTEX_ENTER(&is->is_lock);
1329	if (fr_tcpinwindow(fin, fdata, tdata, tcp, is->is_flags)) {
1330#ifdef	IPFILTER_SCAN
1331		if (is->is_flags & (IS_SC_CLIENT|IS_SC_SERVER)) {
1332			ipsc_packet(fin, is);
1333			if (FR_ISBLOCK(is->is_pass)) {
1334				MUTEX_EXIT(&is->is_lock);
1335				return 1;
1336			}
1337		}
1338#endif
1339
1340		/*
1341		 * Nearing end of connection, start timeout.
1342		 */
1343		ret = fr_tcp_age(&is->is_sti, fin, ips_tqtqb, is->is_flags);
1344		if (ret == 0) {
1345			MUTEX_EXIT(&is->is_lock);
1346			return 0;
1347		}
1348
1349		/*
1350		 * set s0's as appropriate.  Use syn-ack packet as it
1351		 * contains both pieces of required information.
1352		 */
1353		/*
1354		 * Window scale option is only present in SYN/SYN-ACK packet.
1355		 * Compare with ~TH_FIN to mask out T/TCP setups.
1356		 */
1357		flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
1358		if (flags == (TH_SYN|TH_ACK)) {
1359			is->is_s0[source] = ntohl(tcp->th_ack);
1360			is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
1361			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2)) &&
1362			    (tdata->td_winflags & TCP_WSCALE_SEEN)) {
1363				if (fr_tcpoptions(fin, tcp, fdata) == -1)
1364					fin->fin_flx |= FI_BAD;
1365				if (!(fdata->td_winflags & TCP_WSCALE_SEEN)) {
1366					fdata->td_winscale = 0;
1367					tdata->td_winscale = 0;
1368				}
1369			}
1370			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1371				fr_checknewisn(fin, is);
1372		} else if (flags == TH_SYN) {
1373			is->is_s0[source] = ntohl(tcp->th_seq) + 1;
1374			if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1375				if (fr_tcpoptions(fin, tcp, tdata) == -1)
1376					fin->fin_flx |= FI_BAD;
1377			}
1378
1379			if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1380				fr_checknewisn(fin, is);
1381
1382		}
1383		ret = 1;
1384	} else
1385		fin->fin_flx |= FI_OOW;
1386	MUTEX_EXIT(&is->is_lock);
1387	return ret;
1388}
1389
1390
1391/* ------------------------------------------------------------------------ */
1392/* Function:    fr_checknewisn                                              */
1393/* Returns:     Nil                                                         */
1394/* Parameters:  fin(I)   - pointer to packet information                    */
1395/*              is(I)  - pointer to master state structure                  */
1396/*                                                                          */
1397/* Check to see if this TCP connection is expecting and needs a new         */
1398/* sequence number for a particular direction of the connection.            */
1399/*                                                                          */
1400/* NOTE: This does not actually change the sequence numbers, only gets new  */
1401/* one ready.                                                               */
1402/* ------------------------------------------------------------------------ */
1403static void fr_checknewisn(fin, is)
1404fr_info_t *fin;
1405ipstate_t *is;
1406{
1407	u_32_t sumd, old, new;
1408	tcphdr_t *tcp;
1409	int i;
1410
1411	i = fin->fin_rev;
1412	tcp = fin->fin_dp;
1413
1414	if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
1415	    ((i == 1) && !(is->is_flags & IS_ISNACK))) {
1416		old = ntohl(tcp->th_seq);
1417		new = fr_newisn(fin);
1418		is->is_isninc[i] = new - old;
1419		CALC_SUMD(old, new, sumd);
1420		is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
1421
1422		is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
1423	}
1424}
1425
1426
1427/* ------------------------------------------------------------------------ */
1428/* Function:    fr_tcpinwindow                                              */
1429/* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
1430/* Parameters:  fin(I)   - pointer to packet information                    */
1431/*              fdata(I) - pointer to tcp state informatio (forward)        */
1432/*              tdata(I) - pointer to tcp state informatio (reverse)        */
1433/*              tcp(I)   - pointer to TCP packet header                     */
1434/*                                                                          */
1435/* Given a packet has matched addresses and ports, check to see if it is    */
1436/* within the TCP data window.  In a show of generosity, allow packets that */
1437/* are within the window space behind the current sequence # as well.       */
1438/* ------------------------------------------------------------------------ */
1439int fr_tcpinwindow(fin, fdata, tdata, tcp, flags)
1440fr_info_t *fin;
1441tcpdata_t  *fdata, *tdata;
1442tcphdr_t *tcp;
1443int flags;
1444{
1445	tcp_seq seq, ack, end;
1446	int ackskew, tcpflags;
1447	u_32_t win, maxwin;
1448	int dsize, inseq;
1449
1450	/*
1451	 * Find difference between last checked packet and this packet.
1452	 */
1453	tcpflags = tcp->th_flags;
1454	seq = ntohl(tcp->th_seq);
1455	ack = ntohl(tcp->th_ack);
1456	if (tcpflags & TH_SYN)
1457		win = ntohs(tcp->th_win);
1458	else
1459		win = ntohs(tcp->th_win) << fdata->td_winscale;
1460#if 0
1461	/*
1462	 * XXX - This is a kludge is here because IPFilter doesn't track SACK
1463	 * options in TCP packets.  This is not a trivial to do if one is to
1464	 * consider the performance impact of it.  So instead, if the
1465	 * receiver has said SACK is ok, double the allowed window size.
1466	 * This is disabled for testing of another workaround for a problem
1467	 * with Microsoft Windows - see below.
1468	 */
1469	if ((tdata->td_winflags & TCP_SACK_PERMIT) != 0)
1470		win *= 2;
1471#endif
1472
1473	/*
1474	 * A window of 0 produces undesirable behaviour from this function.
1475	 */
1476	if (win == 0)
1477		win = 1;
1478
1479	dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
1480	        ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
1481
1482	/*
1483	 * if window scaling is present, the scaling is only allowed
1484	 * for windows not in the first SYN packet. In that packet the
1485	 * window is 65535 to specify the largest window possible
1486	 * for receivers not implementing the window scale option.
1487	 * Currently, we do not assume TTCP here. That means that
1488	 * if we see a second packet from a host (after the initial
1489	 * SYN), we can assume that the receiver of the SYN did
1490	 * already send back the SYN/ACK (and thus that we know if
1491	 * the receiver also does window scaling)
1492	 */
1493	if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
1494		if (tdata->td_winflags & TCP_WSCALE_SEEN) {
1495			fdata->td_winflags &= ~TCP_WSCALE_FIRST;
1496			fdata->td_maxwin = win;
1497		} else {
1498			fdata->td_winscale = 0;
1499			fdata->td_winflags &= ~(TCP_WSCALE_FIRST|
1500						TCP_WSCALE_SEEN);
1501			tdata->td_winscale = 0;
1502			tdata->td_winflags &= ~(TCP_WSCALE_FIRST|
1503						TCP_WSCALE_SEEN);
1504		  }
1505	}
1506
1507	end = seq + dsize;
1508
1509	if ((fdata->td_end == 0) &&
1510	    (!(flags & IS_TCPFSM) ||
1511	     ((tcpflags & TH_OPENING) == TH_OPENING))) {
1512		/*
1513		 * Must be a (outgoing) SYN-ACK in reply to a SYN.
1514		 */
1515		fdata->td_end = end - 1;
1516		fdata->td_maxwin = 1;
1517		fdata->td_maxend = end + win;
1518	}
1519
1520	if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
1521		ack = tdata->td_end;
1522	} else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
1523		   (ack == 0)) {
1524		/* gross hack to get around certain broken tcp stacks */
1525		ack = tdata->td_end;
1526	}
1527
1528	maxwin = tdata->td_maxwin;
1529	ackskew = tdata->td_end - ack;
1530
1531	/*
1532	 * Strict sequencing only allows in-order delivery.
1533	 */
1534	if ((flags & IS_STRICT) != 0) {
1535		if (seq != fdata->td_end) {
1536			return 0;
1537		}
1538	}
1539
1540#define	SEQ_GE(a,b)	((int)((a) - (b)) >= 0)
1541#define	SEQ_GT(a,b)	((int)((a) - (b)) > 0)
1542	inseq = 0;
1543	if ((SEQ_GE(fdata->td_maxend, end)) &&
1544	    (SEQ_GE(seq, fdata->td_end - maxwin)) &&
1545/* XXX what about big packets */
1546#define MAXACKWINDOW 66000
1547	    (-ackskew <= (MAXACKWINDOW << fdata->td_winscale)) &&
1548	    ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
1549		inseq = 1;
1550	/*
1551	 * Microsoft Windows will send the next packet to the right of the
1552	 * window if SACK is in use.
1553	 */
1554	} else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
1555	    (fdata->td_winflags & TCP_SACK_PERMIT) &&
1556	    (tdata->td_winflags & TCP_SACK_PERMIT)) {
1557		inseq = 1;
1558	}
1559
1560	if (inseq) {
1561		/* if ackskew < 0 then this should be due to fragmented
1562		 * packets. There is no way to know the length of the
1563		 * total packet in advance.
1564		 * We do know the total length from the fragment cache though.
1565		 * Note however that there might be more sessions with
1566		 * exactly the same source and destination parameters in the
1567		 * state cache (and source and destination is the only stuff
1568		 * that is saved in the fragment cache). Note further that
1569		 * some TCP connections in the state cache are hashed with
1570		 * sport and dport as well which makes it not worthwhile to
1571		 * look for them.
1572		 * Thus, when ackskew is negative but still seems to belong
1573		 * to this session, we bump up the destinations end value.
1574		 */
1575		if (ackskew < 0)
1576			tdata->td_end = ack;
1577
1578		/* update max window seen */
1579		if (fdata->td_maxwin < win)
1580			fdata->td_maxwin = win;
1581		if (SEQ_GT(end, fdata->td_end))
1582			fdata->td_end = end;
1583		if (SEQ_GE(ack + win, tdata->td_maxend))
1584			tdata->td_maxend = ack + win;
1585		return 1;
1586	}
1587	return 0;
1588}
1589
1590
1591/* ------------------------------------------------------------------------ */
1592/* Function:    fr_stclone                                                  */
1593/* Returns:     ipstate_t* - NULL == cloning failed,                        */
1594/*                           else pointer to new state structure            */
1595/* Parameters:  fin(I) - pointer to packet information                      */
1596/*              tcp(I) - pointer to TCP/UDP header                          */
1597/*              is(I)  - pointer to master state structure                  */
1598/*                                                                          */
1599/* Create a "duplcate" state table entry from the master.                   */
1600/* ------------------------------------------------------------------------ */
1601static ipstate_t *fr_stclone(fin, tcp, is)
1602fr_info_t *fin;
1603tcphdr_t *tcp;
1604ipstate_t *is;
1605{
1606	ipstate_t *clone;
1607	u_32_t send;
1608
1609	if (ips_num == fr_statemax) {
1610		ATOMIC_INCL(ips_stats.iss_max);
1611		fr_state_doflush = 1;
1612		return NULL;
1613	}
1614	KMALLOC(clone, ipstate_t *);
1615	if (clone == NULL)
1616		return NULL;
1617	bcopy((char *)is, (char *)clone, sizeof(*clone));
1618
1619	MUTEX_NUKE(&clone->is_lock);
1620
1621	clone->is_die = ONE_DAY + fr_ticks;
1622	clone->is_state[0] = 0;
1623	clone->is_state[1] = 0;
1624	send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
1625		((tcp->th_flags & TH_SYN) ? 1 : 0) +
1626		((tcp->th_flags & TH_FIN) ? 1 : 0);
1627
1628	if (fin->fin_rev == 1) {
1629		clone->is_dend = send;
1630		clone->is_maxdend = send;
1631		clone->is_send = 0;
1632		clone->is_maxswin = 1;
1633		clone->is_maxdwin = ntohs(tcp->th_win);
1634		if (clone->is_maxdwin == 0)
1635			clone->is_maxdwin = 1;
1636	} else {
1637		clone->is_send = send;
1638		clone->is_maxsend = send;
1639		clone->is_dend = 0;
1640		clone->is_maxdwin = 1;
1641		clone->is_maxswin = ntohs(tcp->th_win);
1642		if (clone->is_maxswin == 0)
1643			clone->is_maxswin = 1;
1644	}
1645
1646	clone->is_flags &= ~SI_CLONE;
1647	clone->is_flags |= SI_CLONED;
1648	fr_stinsert(clone, fin->fin_rev);
1649	clone->is_ref = 2;
1650	if (clone->is_p == IPPROTO_TCP) {
1651		(void) fr_tcp_age(&clone->is_sti, fin, ips_tqtqb,
1652				  clone->is_flags);
1653	}
1654	MUTEX_EXIT(&clone->is_lock);
1655#ifdef	IPFILTER_SCAN
1656	(void) ipsc_attachis(is);
1657#endif
1658#ifdef	IPFILTER_SYNC
1659	if (is->is_flags & IS_STATESYNC)
1660		clone->is_sync = ipfsync_new(SMC_STATE, fin, clone);
1661#endif
1662	return clone;
1663}
1664
1665
1666/* ------------------------------------------------------------------------ */
1667/* Function:    fr_matchsrcdst                                              */
1668/* Returns:     Nil                                                         */
1669/* Parameters:  fin(I) - pointer to packet information                      */
1670/*              is(I)  - pointer to state structure                         */
1671/*              src(I) - pointer to source address                          */
1672/*              dst(I) - pointer to destination address                     */
1673/*              tcp(I) - pointer to TCP/UDP header                          */
1674/*                                                                          */
1675/* Match a state table entry against an IP packet.  The logic below is that */
1676/* ret gets set to one if the match succeeds, else remains 0.  If it is     */
1677/* still 0 after the test. no match.                                        */
1678/* ------------------------------------------------------------------------ */
1679static ipstate_t *fr_matchsrcdst(fin, is, src, dst, tcp, cmask)
1680fr_info_t *fin;
1681ipstate_t *is;
1682i6addr_t *src, *dst;
1683tcphdr_t *tcp;
1684u_32_t cmask;
1685{
1686	int ret = 0, rev, out, flags, flx = 0, idx;
1687	u_short sp, dp;
1688	u_32_t cflx;
1689	void *ifp;
1690
1691	rev = IP6_NEQ(&is->is_dst, dst);
1692	ifp = fin->fin_ifp;
1693	out = fin->fin_out;
1694	flags = is->is_flags;
1695	sp = 0;
1696	dp = 0;
1697
1698	if (tcp != NULL) {
1699		sp = htons(fin->fin_sport);
1700		dp = ntohs(fin->fin_dport);
1701	}
1702	if (!rev) {
1703		if (tcp != NULL) {
1704			if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
1705				rev = 1;
1706			else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
1707				rev = 1;
1708		}
1709	}
1710
1711	idx = (out << 1) + rev;
1712
1713	/*
1714	 * If the interface for this 'direction' is set, make sure it matches.
1715	 * An interface name that is not set matches any, as does a name of *.
1716	 */
1717	if ((is->is_ifp[idx] == NULL &&
1718	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) ||
1719	    is->is_ifp[idx] == ifp)
1720		ret = 1;
1721
1722	if (ret == 0)
1723		return NULL;
1724	ret = 0;
1725
1726	/*
1727	 * Match addresses and ports.
1728	 */
1729	if (rev == 0) {
1730		if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
1731		    (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
1732			if (tcp) {
1733				if ((sp == is->is_sport || flags & SI_W_SPORT)&&
1734				    (dp == is->is_dport || flags & SI_W_DPORT))
1735					ret = 1;
1736			} else {
1737				ret = 1;
1738			}
1739		}
1740	} else {
1741		if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
1742		    (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
1743			if (tcp) {
1744				if ((dp == is->is_sport || flags & SI_W_SPORT)&&
1745				    (sp == is->is_dport || flags & SI_W_DPORT))
1746					ret = 1;
1747			} else {
1748				ret = 1;
1749			}
1750		}
1751	}
1752
1753	if (ret == 0)
1754		return NULL;
1755
1756	/*
1757	 * Whether or not this should be here, is questionable, but the aim
1758	 * is to get this out of the main line.
1759	 */
1760	if (tcp == NULL)
1761		flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
1762
1763	/*
1764	 * Only one of the source or destination address can be flaged as a
1765	 * wildcard.  Fill in the missing address, if set.
1766	 * For IPv6, if the address being copied in is multicast, then
1767	 * don't reset the wild flag - multicast causes it to be set in the
1768	 * first place!
1769	 */
1770	if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
1771		fr_ip_t *fi = &fin->fin_fi;
1772
1773		if ((flags & SI_W_SADDR) != 0) {
1774			if (rev == 0) {
1775#ifdef USE_INET6
1776				if (is->is_v == 6 &&
1777				    IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
1778					/*EMPTY*/;
1779				else
1780#endif
1781				{
1782					is->is_src = fi->fi_src;
1783					is->is_flags &= ~SI_W_SADDR;
1784				}
1785			} else {
1786#ifdef USE_INET6
1787				if (is->is_v == 6 &&
1788				    IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
1789					/*EMPTY*/;
1790				else
1791#endif
1792				{
1793					is->is_src = fi->fi_dst;
1794					is->is_flags &= ~SI_W_SADDR;
1795				}
1796			}
1797		} else if ((flags & SI_W_DADDR) != 0) {
1798			if (rev == 0) {
1799#ifdef USE_INET6
1800				if (is->is_v == 6 &&
1801				    IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
1802					/*EMPTY*/;
1803				else
1804#endif
1805				{
1806					is->is_dst = fi->fi_dst;
1807					is->is_flags &= ~SI_W_DADDR;
1808				}
1809			} else {
1810#ifdef USE_INET6
1811				if (is->is_v == 6 &&
1812				    IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
1813					/*EMPTY*/;
1814				else
1815#endif
1816				{
1817					is->is_dst = fi->fi_src;
1818					is->is_flags &= ~SI_W_DADDR;
1819				}
1820			}
1821		}
1822		if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
1823			ATOMIC_DECL(ips_stats.iss_wild);
1824		}
1825	}
1826
1827	flx = fin->fin_flx & cmask;
1828	cflx = is->is_flx[out][rev];
1829
1830	/*
1831	 * Match up any flags set from IP options.
1832	 */
1833	if ((cflx && (flx != (cflx & cmask))) ||
1834	    ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
1835	    ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
1836	    ((fin->fin_auth & is->is_authmsk) != is->is_auth))
1837		return NULL;
1838
1839	/*
1840	 * Only one of the source or destination port can be flagged as a
1841	 * wildcard.  When filling it in, fill in a copy of the matched entry
1842	 * if it has the cloning flag set.
1843	 */
1844	if ((fin->fin_flx & FI_IGNORE) != 0) {
1845		fin->fin_rev = rev;
1846		return is;
1847	}
1848
1849	if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
1850		if ((flags & SI_CLONE) != 0) {
1851			ipstate_t *clone;
1852
1853			clone = fr_stclone(fin, tcp, is);
1854			if (clone == NULL)
1855				return NULL;
1856			is = clone;
1857		} else {
1858			ATOMIC_DECL(ips_stats.iss_wild);
1859		}
1860
1861		if ((flags & SI_W_SPORT) != 0) {
1862			if (rev == 0) {
1863				is->is_sport = sp;
1864				is->is_send = ntohl(tcp->th_seq);
1865			} else {
1866				is->is_sport = dp;
1867				is->is_send = ntohl(tcp->th_ack);
1868			}
1869			is->is_maxsend = is->is_send + 1;
1870		} else if ((flags & SI_W_DPORT) != 0) {
1871			if (rev == 0) {
1872				is->is_dport = dp;
1873				is->is_dend = ntohl(tcp->th_ack);
1874			} else {
1875				is->is_dport = sp;
1876				is->is_dend = ntohl(tcp->th_seq);
1877			}
1878			is->is_maxdend = is->is_dend + 1;
1879		}
1880		is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
1881		if ((flags & SI_CLONED) && ipstate_logging)
1882			ipstate_log(is, ISL_CLONE);
1883	}
1884
1885	ret = -1;
1886
1887	if (is->is_flx[out][rev] == 0) {
1888		is->is_flx[out][rev] = flx;
1889		is->is_opt[rev] = fin->fin_optmsk;
1890		if (is->is_v == 6) {
1891			is->is_opt[rev] &= ~0x8;
1892			is->is_optmsk[rev] &= ~0x8;
1893		}
1894	}
1895
1896	/*
1897	 * Check if the interface name for this "direction" is set and if not,
1898	 * fill it in.
1899	 */
1900	if (is->is_ifp[idx] == NULL &&
1901	    (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
1902		is->is_ifp[idx] = ifp;
1903		COPYIFNAME(ifp, is->is_ifname[idx]);
1904	}
1905	fin->fin_rev = rev;
1906	return is;
1907}
1908
1909
1910/* ------------------------------------------------------------------------ */
1911/* Function:    fr_checkicmpmatchingstate                                   */
1912/* Returns:     Nil                                                         */
1913/* Parameters:  fin(I) - pointer to packet information                      */
1914/*                                                                          */
1915/* If we've got an ICMP error message, using the information stored in the  */
1916/* ICMP packet, look for a matching state table entry.                      */
1917/*                                                                          */
1918/* If we return NULL then no lock on ipf_state is held.                     */
1919/* If we return non-null then a read-lock on ipf_state is held.             */
1920/* ------------------------------------------------------------------------ */
1921static ipstate_t *fr_checkicmpmatchingstate(fin)
1922fr_info_t *fin;
1923{
1924	ipstate_t *is, **isp;
1925	u_short sport, dport;
1926	u_char	pr;
1927	int backward, i, oi;
1928	i6addr_t dst, src;
1929	struct icmp *ic;
1930	u_short savelen;
1931	icmphdr_t *icmp;
1932	fr_info_t ofin;
1933	tcphdr_t *tcp;
1934	int type, len;
1935	ip_t *oip;
1936	u_int hv;
1937
1938	/*
1939	 * Does it at least have the return (basic) IP header ?
1940	 * Is it an actual recognised ICMP error type?
1941	 * Only a basic IP header (no options) should be with
1942	 * an ICMP error header.
1943	 */
1944	if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
1945	    (fin->fin_plen < ICMPERR_MINPKTLEN) ||
1946	    !(fin->fin_flx & FI_ICMPERR))
1947		return NULL;
1948	ic = fin->fin_dp;
1949	type = ic->icmp_type;
1950
1951	oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
1952	/*
1953	 * Check if the at least the old IP header (with options) and
1954	 * 8 bytes of payload is present.
1955	 */
1956	if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2))
1957		return NULL;
1958
1959	/*
1960	 * Sanity Checks.
1961	 */
1962	len = fin->fin_dlen - ICMPERR_ICMPHLEN;
1963	if ((len <= 0) || ((IP_HL(oip) << 2) > len))
1964		return NULL;
1965
1966	/*
1967	 * Is the buffer big enough for all of it ?  It's the size of the IP
1968	 * header claimed in the encapsulated part which is of concern.  It
1969	 * may be too big to be in this buffer but not so big that it's
1970	 * outside the ICMP packet, leading to TCP deref's causing problems.
1971	 * This is possible because we don't know how big oip_hl is when we
1972	 * do the pullup early in fr_check() and thus can't guarantee it is
1973	 * all here now.
1974	 */
1975#ifdef  _KERNEL
1976	{
1977	mb_t *m;
1978
1979	m = fin->fin_m;
1980# if defined(MENTAT)
1981	if ((char *)oip + len > (char *)m->b_wptr)
1982		return NULL;
1983# else
1984	if ((char *)oip + len > (char *)fin->fin_ip + m->m_len)
1985		return NULL;
1986# endif
1987	}
1988#endif
1989	bcopy((char *)fin, (char *)&ofin, sizeof(fin));
1990
1991	/*
1992	 * in the IPv4 case we must zero the i6addr union otherwise
1993	 * the IP6_EQ and IP6_NEQ macros produce the wrong results because
1994	 * of the 'junk' in the unused part of the union
1995	 */
1996	bzero((char *)&src, sizeof(src));
1997	bzero((char *)&dst, sizeof(dst));
1998
1999	/*
2000	 * we make an fin entry to be able to feed it to
2001	 * matchsrcdst note that not all fields are encessary
2002	 * but this is the cleanest way. Note further we fill
2003	 * in fin_mp such that if someone uses it we'll get
2004	 * a kernel panic. fr_matchsrcdst does not use this.
2005	 *
2006	 * watch out here, as ip is in host order and oip in network
2007	 * order. Any change we make must be undone afterwards, like
2008	 * oip->ip_off - it is still in network byte order so fix it.
2009	 */
2010	savelen = oip->ip_len;
2011	oip->ip_len = len;
2012	oip->ip_off = ntohs(oip->ip_off);
2013
2014	ofin.fin_flx = FI_NOCKSUM;
2015	ofin.fin_v = 4;
2016	ofin.fin_ip = oip;
2017	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
2018	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
2019	ofin.fin_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
2020	(void) fr_makefrip(IP_HL(oip) << 2, oip, &ofin);
2021	ofin.fin_ifp = fin->fin_ifp;
2022	ofin.fin_out = !fin->fin_out;
2023	/*
2024	 * Reset the short and bad flag here because in fr_matchsrcdst()
2025	 * the flags for the current packet (fin_flx) are compared against
2026	 * those for the existing session.
2027	 */
2028	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2029
2030	/*
2031	 * Put old values of ip_len and ip_off back as we don't know
2032	 * if we have to forward the packet (or process it again.
2033	 */
2034	oip->ip_len = savelen;
2035	oip->ip_off = htons(oip->ip_off);
2036
2037	switch (oip->ip_p)
2038	{
2039	case IPPROTO_ICMP :
2040		/*
2041		 * an ICMP error can only be generated as a result of an
2042		 * ICMP query, not as the response on an ICMP error
2043		 *
2044		 * XXX theoretically ICMP_ECHOREP and the other reply's are
2045		 * ICMP query's as well, but adding them here seems strange XXX
2046		 */
2047		if ((ofin.fin_flx & FI_ICMPERR) != 0)
2048		    	return NULL;
2049
2050		/*
2051		 * perform a lookup of the ICMP packet in the state table
2052		 */
2053		icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2054		hv = (pr = oip->ip_p);
2055		src.in4 = oip->ip_src;
2056		hv += src.in4.s_addr;
2057		dst.in4 = oip->ip_dst;
2058		hv += dst.in4.s_addr;
2059		hv += icmp->icmp_id;
2060		hv = DOUBLE_HASH(hv);
2061
2062		READ_ENTER(&ipf_state);
2063		for (isp = &ips_table[hv]; ((is = *isp) != NULL); ) {
2064			isp = &is->is_hnext;
2065			if ((is->is_p != pr) || (is->is_v != 4))
2066				continue;
2067			if (is->is_pass & FR_NOICMPERR)
2068				continue;
2069			is = fr_matchsrcdst(&ofin, is, &src, &dst,
2070					    NULL, FI_ICMPCMP);
2071			if (is != NULL) {
2072				/*
2073				 * i  : the index of this packet (the icmp
2074				 *      unreachable)
2075				 * oi : the index of the original packet found
2076				 *      in the icmp header (i.e. the packet
2077				 *      causing this icmp)
2078				 * backward : original packet was backward
2079				 *      compared to the state
2080				 */
2081				backward = IP6_NEQ(&is->is_src, &src);
2082				fin->fin_rev = !backward;
2083				i = (!backward << 1) + fin->fin_out;
2084				oi = (backward << 1) + ofin.fin_out;
2085				if (is->is_icmppkts[i] > is->is_pkts[oi])
2086					continue;
2087				ips_stats.iss_hits++;
2088				is->is_icmppkts[i]++;
2089				return is;
2090			}
2091		}
2092		RWLOCK_EXIT(&ipf_state);
2093		return NULL;
2094	case IPPROTO_TCP :
2095	case IPPROTO_UDP :
2096		break;
2097	default :
2098		return NULL;
2099	}
2100
2101	tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2102	dport = tcp->th_dport;
2103	sport = tcp->th_sport;
2104
2105	hv = (pr = oip->ip_p);
2106	src.in4 = oip->ip_src;
2107	hv += src.in4.s_addr;
2108	dst.in4 = oip->ip_dst;
2109	hv += dst.in4.s_addr;
2110	hv += dport;
2111	hv += sport;
2112	hv = DOUBLE_HASH(hv);
2113
2114	READ_ENTER(&ipf_state);
2115	for (isp = &ips_table[hv]; ((is = *isp) != NULL); ) {
2116		isp = &is->is_hnext;
2117		/*
2118		 * Only allow this icmp though if the
2119		 * encapsulated packet was allowed through the
2120		 * other way around. Note that the minimal amount
2121		 * of info present does not allow for checking against
2122		 * tcp internals such as seq and ack numbers.   Only the
2123		 * ports are known to be present and can be even if the
2124		 * short flag is set.
2125		 */
2126		if ((is->is_p == pr) && (is->is_v == 4) &&
2127		    (is = fr_matchsrcdst(&ofin, is, &src, &dst,
2128					 tcp, FI_ICMPCMP))) {
2129			/*
2130			 * i  : the index of this packet (the icmp unreachable)
2131			 * oi : the index of the original packet found in the
2132			 *      icmp header (i.e. the packet causing this icmp)
2133			 * backward : original packet was backward compared to
2134			 *            the state
2135			 */
2136			backward = IP6_NEQ(&is->is_src, &src);
2137			fin->fin_rev = !backward;
2138			i = (!backward << 1) + fin->fin_out;
2139			oi = (backward << 1) + ofin.fin_out;
2140
2141			if (((is->is_pass & FR_NOICMPERR) != 0) ||
2142			    (is->is_icmppkts[i] > is->is_pkts[oi]))
2143				break;
2144			ips_stats.iss_hits++;
2145			is->is_icmppkts[i]++;
2146			/*
2147			 * we deliberately do not touch the timeouts
2148			 * for the accompanying state table entry.
2149			 * It remains to be seen if that is correct. XXX
2150			 */
2151			return is;
2152		}
2153	}
2154	RWLOCK_EXIT(&ipf_state);
2155	return NULL;
2156}
2157
2158
2159/* ------------------------------------------------------------------------ */
2160/* Function:    fr_ipsmove                                                  */
2161/* Returns:     Nil                                                         */
2162/* Parameters:  is(I) - pointer to state table entry                        */
2163/*              hv(I) - new hash value for state table entry                */
2164/* Write Locks: ipf_state                                                   */
2165/*                                                                          */
2166/* Move a state entry from one position in the hash table to another.       */
2167/* ------------------------------------------------------------------------ */
2168static void fr_ipsmove(is, hv)
2169ipstate_t *is;
2170u_int hv;
2171{
2172	ipstate_t **isp;
2173	u_int hvm;
2174
2175	ASSERT(rw_read_locked(&ipf_state.ipf_lk) == 0);
2176
2177	hvm = is->is_hv;
2178	/*
2179	 * Remove the hash from the old location...
2180	 */
2181	isp = is->is_phnext;
2182	if (is->is_hnext)
2183		is->is_hnext->is_phnext = isp;
2184	*isp = is->is_hnext;
2185	if (ips_table[hvm] == NULL)
2186		ips_stats.iss_inuse--;
2187	ips_stats.iss_bucketlen[hvm]--;
2188
2189	/*
2190	 * ...and put the hash in the new one.
2191	 */
2192	hvm = DOUBLE_HASH(hv);
2193	is->is_hv = hvm;
2194	isp = &ips_table[hvm];
2195	if (*isp)
2196		(*isp)->is_phnext = &is->is_hnext;
2197	else
2198		ips_stats.iss_inuse++;
2199	ips_stats.iss_bucketlen[hvm]++;
2200	is->is_phnext = isp;
2201	is->is_hnext = *isp;
2202	*isp = is;
2203}
2204
2205
2206/* ------------------------------------------------------------------------ */
2207/* Function:    fr_stlookup                                                 */
2208/* Returns:     ipstate_t* - NULL == no matching state found,               */
2209/*                           else pointer to state information is returned  */
2210/* Parameters:  fin(I) - pointer to packet information                      */
2211/*              tcp(I) - pointer to TCP/UDP header.                         */
2212/*                                                                          */
2213/* Search the state table for a matching entry to the packet described by   */
2214/* the contents of *fin.                                                    */
2215/*                                                                          */
2216/* If we return NULL then no lock on ipf_state is held.                     */
2217/* If we return non-null then a read-lock on ipf_state is held.             */
2218/* ------------------------------------------------------------------------ */
2219ipstate_t *fr_stlookup(fin, tcp, ifqp)
2220fr_info_t *fin;
2221tcphdr_t *tcp;
2222ipftq_t **ifqp;
2223{
2224	u_int hv, hvm, pr, v, tryagain;
2225	ipstate_t *is, **isp;
2226	u_short dport, sport;
2227	i6addr_t src, dst;
2228	struct icmp *ic;
2229	ipftq_t *ifq;
2230	int oow;
2231
2232	is = NULL;
2233	ifq = NULL;
2234	tcp = fin->fin_dp;
2235	ic = (struct icmp *)tcp;
2236	hv = (pr = fin->fin_fi.fi_p);
2237	src = fin->fin_fi.fi_src;
2238	dst = fin->fin_fi.fi_dst;
2239	hv += src.in4.s_addr;
2240	hv += dst.in4.s_addr;
2241
2242	v = fin->fin_fi.fi_v;
2243#ifdef	USE_INET6
2244	if (v == 6) {
2245		hv  += fin->fin_fi.fi_src.i6[1];
2246		hv  += fin->fin_fi.fi_src.i6[2];
2247		hv  += fin->fin_fi.fi_src.i6[3];
2248
2249		if ((fin->fin_p == IPPROTO_ICMPV6) &&
2250		    IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
2251			hv -= dst.in4.s_addr;
2252		} else {
2253			hv += fin->fin_fi.fi_dst.i6[1];
2254			hv += fin->fin_fi.fi_dst.i6[2];
2255			hv += fin->fin_fi.fi_dst.i6[3];
2256		}
2257	}
2258#endif
2259
2260	/*
2261	 * Search the hash table for matching packet header info.
2262	 */
2263	switch (pr)
2264	{
2265#ifdef	USE_INET6
2266	case IPPROTO_ICMPV6 :
2267		tryagain = 0;
2268		if (v == 6) {
2269			if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
2270			    (ic->icmp_type == ICMP6_ECHO_REPLY)) {
2271				hv += ic->icmp_id;
2272			}
2273		}
2274		READ_ENTER(&ipf_state);
2275icmp6again:
2276		hvm = DOUBLE_HASH(hv);
2277		for (isp = &ips_table[hvm]; ((is = *isp) != NULL); ) {
2278			isp = &is->is_hnext;
2279			if ((is->is_p != pr) || (is->is_v != v))
2280				continue;
2281			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2282			if (is != NULL &&
2283			    fr_matchicmpqueryreply(v, &is->is_icmp,
2284						   ic, fin->fin_rev)) {
2285				if (fin->fin_rev)
2286					ifq = &ips_icmpacktq;
2287				else
2288					ifq = &ips_icmptq;
2289				break;
2290			}
2291		}
2292
2293		if (is != NULL) {
2294			if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
2295				hv += fin->fin_fi.fi_src.i6[0];
2296				hv += fin->fin_fi.fi_src.i6[1];
2297				hv += fin->fin_fi.fi_src.i6[2];
2298				hv += fin->fin_fi.fi_src.i6[3];
2299				fr_ipsmove(is, hv);
2300				MUTEX_DOWNGRADE(&ipf_state);
2301			}
2302			break;
2303		}
2304		RWLOCK_EXIT(&ipf_state);
2305
2306		/*
2307		 * No matching icmp state entry. Perhaps this is a
2308		 * response to another state entry.
2309		 *
2310		 * XXX With some ICMP6 packets, the "other" address is already
2311		 * in the packet, after the ICMP6 header, and this could be
2312		 * used in place of the multicast address.  However, taking
2313		 * advantage of this requires some significant code changes
2314		 * to handle the specific types where that is the case.
2315		 */
2316		if ((ips_stats.iss_wild != 0) && (v == 6) && (tryagain == 0) &&
2317		    !IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_src.in6)) {
2318			hv -= fin->fin_fi.fi_src.i6[0];
2319			hv -= fin->fin_fi.fi_src.i6[1];
2320			hv -= fin->fin_fi.fi_src.i6[2];
2321			hv -= fin->fin_fi.fi_src.i6[3];
2322			tryagain = 1;
2323			WRITE_ENTER(&ipf_state);
2324			goto icmp6again;
2325		}
2326
2327		is = fr_checkicmp6matchingstate(fin);
2328		if (is != NULL)
2329			return is;
2330		break;
2331#endif
2332
2333	case IPPROTO_ICMP :
2334		if (v == 4) {
2335			hv += ic->icmp_id;
2336		}
2337		hv = DOUBLE_HASH(hv);
2338		READ_ENTER(&ipf_state);
2339		for (isp = &ips_table[hv]; ((is = *isp) != NULL); ) {
2340			isp = &is->is_hnext;
2341			if ((is->is_p != pr) || (is->is_v != v))
2342				continue;
2343			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2344			if (is != NULL &&
2345			    fr_matchicmpqueryreply(v, &is->is_icmp,
2346						   ic, fin->fin_rev)) {
2347				if (fin->fin_rev)
2348					ifq = &ips_icmpacktq;
2349				else
2350					ifq = &ips_icmptq;
2351				break;
2352			}
2353		}
2354		if (is == NULL) {
2355			RWLOCK_EXIT(&ipf_state);
2356		}
2357		break;
2358
2359	case IPPROTO_TCP :
2360	case IPPROTO_UDP :
2361		ifqp = NULL;
2362		sport = htons(fin->fin_data[0]);
2363		hv += sport;
2364		dport = htons(fin->fin_data[1]);
2365		hv += dport;
2366		oow = 0;
2367		tryagain = 0;
2368		READ_ENTER(&ipf_state);
2369retry_tcpudp:
2370		hvm = DOUBLE_HASH(hv);
2371		for (isp = &ips_table[hvm]; ((is = *isp) != NULL); ) {
2372			isp = &is->is_hnext;
2373			if ((is->is_p != pr) || (is->is_v != v))
2374				continue;
2375			fin->fin_flx &= ~FI_OOW;
2376			is = fr_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
2377			if (is != NULL) {
2378				if (pr == IPPROTO_TCP) {
2379					if (!fr_tcpstate(fin, tcp, is)) {
2380						oow |= fin->fin_flx & FI_OOW;
2381						continue;
2382					}
2383				}
2384				break;
2385			}
2386		}
2387		if (is != NULL) {
2388			if (tryagain &&
2389			    !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
2390				hv += dport;
2391				hv += sport;
2392				fr_ipsmove(is, hv);
2393				MUTEX_DOWNGRADE(&ipf_state);
2394			}
2395			break;
2396		}
2397		RWLOCK_EXIT(&ipf_state);
2398
2399		if (!tryagain && ips_stats.iss_wild) {
2400			hv -= dport;
2401			hv -= sport;
2402			tryagain = 1;
2403			WRITE_ENTER(&ipf_state);
2404			goto retry_tcpudp;
2405		}
2406		fin->fin_flx |= oow;
2407		break;
2408
2409#if 0
2410	case IPPROTO_GRE :
2411		gre = fin->fin_dp;
2412		if (GRE_REV(gre->gr_flags) == 1) {
2413			hv += gre->gr_call;
2414		}
2415		/* FALLTHROUGH */
2416#endif
2417	default :
2418		ifqp = NULL;
2419		hvm = DOUBLE_HASH(hv);
2420		READ_ENTER(&ipf_state);
2421		for (isp = &ips_table[hvm]; ((is = *isp) != NULL); ) {
2422			isp = &is->is_hnext;
2423			if ((is->is_p != pr) || (is->is_v != v))
2424				continue;
2425			is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2426			if (is != NULL) {
2427				ifq = &ips_iptq;
2428				break;
2429			}
2430		}
2431		if (is == NULL) {
2432			RWLOCK_EXIT(&ipf_state);
2433		}
2434		break;
2435	}
2436
2437	if ((is != NULL) && ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
2438	    (is->is_tqehead[fin->fin_rev] != NULL))
2439		ifq = is->is_tqehead[fin->fin_rev];
2440	if (ifq != NULL && ifqp != NULL)
2441		*ifqp = ifq;
2442	return is;
2443}
2444
2445
2446/* ------------------------------------------------------------------------ */
2447/* Function:    fr_updatestate                                              */
2448/* Returns:     Nil                                                         */
2449/* Parameters:  fin(I) - pointer to packet information                      */
2450/*              is(I)  - pointer to state table entry                       */
2451/* Read Locks:  ipf_state                                                   */
2452/*                                                                          */
2453/* Updates packet and byte counters for a newly received packet.  Seeds the */
2454/* fragment cache with a new entry as required.                             */
2455/* ------------------------------------------------------------------------ */
2456void fr_updatestate(fin, is, ifq)
2457fr_info_t *fin;
2458ipstate_t *is;
2459ipftq_t *ifq;
2460{
2461	ipftqent_t *tqe;
2462	int i, pass;
2463
2464	i = (fin->fin_rev << 1) + fin->fin_out;
2465
2466	/*
2467	 * For TCP packets, ifq == NULL.  For all others, check if this new
2468	 * queue is different to the last one it was on and move it if so.
2469	 */
2470	tqe = &is->is_sti;
2471	MUTEX_ENTER(&is->is_lock);
2472	if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
2473		ifq = is->is_tqehead[fin->fin_rev];
2474
2475	if (ifq != NULL)
2476		fr_movequeue(tqe, tqe->tqe_ifq, ifq);
2477
2478	is->is_pkts[i]++;
2479	is->is_bytes[i] += fin->fin_plen;
2480	MUTEX_EXIT(&is->is_lock);
2481
2482#ifdef	IPFILTER_SYNC
2483	if (is->is_flags & IS_STATESYNC)
2484		ipfsync_update(SMC_STATE, fin, is->is_sync);
2485#endif
2486
2487	ATOMIC_INCL(ips_stats.iss_hits);
2488
2489	fin->fin_fr = is->is_rule;
2490
2491	/*
2492	 * If this packet is a fragment and the rule says to track fragments,
2493	 * then create a new fragment cache entry.
2494	 */
2495	pass = is->is_pass;
2496	if ((fin->fin_flx & FI_FRAG) && FR_ISPASS(pass))
2497		(void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
2498}
2499
2500
2501/* ------------------------------------------------------------------------ */
2502/* Function:    fr_checkstate                                               */
2503/* Returns:     frentry_t* - NULL == search failed,                         */
2504/*                           else pointer to rule for matching state        */
2505/* Parameters:  ifp(I)   - pointer to interface                             */
2506/*              passp(I) - pointer to filtering result flags                */
2507/*                                                                          */
2508/* Check if a packet is associated with an entry in the state table.        */
2509/* ------------------------------------------------------------------------ */
2510frentry_t *fr_checkstate(fin, passp)
2511fr_info_t *fin;
2512u_32_t *passp;
2513{
2514	ipstate_t *is;
2515	frentry_t *fr;
2516	tcphdr_t *tcp;
2517	ipftq_t *ifq;
2518	u_int pass;
2519
2520	if (fr_state_lock || (ips_list == NULL) ||
2521	    (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
2522		return NULL;
2523
2524	is = NULL;
2525	if ((fin->fin_flx & FI_TCPUDP) ||
2526	    (fin->fin_fi.fi_p == IPPROTO_ICMP)
2527#ifdef	USE_INET6
2528	    || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
2529#endif
2530	    )
2531		tcp = fin->fin_dp;
2532	else
2533		tcp = NULL;
2534
2535	/*
2536	 * Search the hash table for matching packet header info.
2537	 */
2538	ifq = NULL;
2539	is = fin->fin_state;
2540	if (is == NULL)
2541		is = fr_stlookup(fin, tcp, &ifq);
2542	switch (fin->fin_p)
2543	{
2544#ifdef	USE_INET6
2545	case IPPROTO_ICMPV6 :
2546		if (is != NULL)
2547			break;
2548		if (fin->fin_v == 6) {
2549			is = fr_checkicmp6matchingstate(fin);
2550			if (is != NULL)
2551				goto matched;
2552		}
2553		break;
2554#endif
2555	case IPPROTO_ICMP :
2556		if (is != NULL)
2557			break;
2558		/*
2559		 * No matching icmp state entry. Perhaps this is a
2560		 * response to another state entry.
2561		 */
2562		is = fr_checkicmpmatchingstate(fin);
2563		if (is != NULL)
2564			goto matched;
2565		break;
2566	case IPPROTO_TCP :
2567		if (is == NULL)
2568			break;
2569
2570		if (is->is_pass & FR_NEWISN) {
2571			if (fin->fin_out == 0)
2572				fr_fixinisn(fin, is);
2573			else if (fin->fin_out == 1)
2574				fr_fixoutisn(fin, is);
2575		}
2576		break;
2577	default :
2578		if (fin->fin_rev)
2579			ifq = &ips_udpacktq;
2580		else
2581			ifq = &ips_udptq;
2582		break;
2583	}
2584	if (is == NULL) {
2585		ATOMIC_INCL(ips_stats.iss_miss);
2586		return NULL;
2587	}
2588
2589matched:
2590	fr = is->is_rule;
2591	if (fr != NULL) {
2592		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2593			if (fin->fin_nattag == NULL)
2594				return NULL;
2595			if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) != 0)
2596				return NULL;
2597		}
2598		(void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
2599		fin->fin_icode = fr->fr_icode;
2600	}
2601
2602	fin->fin_rule = is->is_rulen;
2603	pass = is->is_pass;
2604	fr_updatestate(fin, is, ifq);
2605	if (fin->fin_out == 1)
2606		fin->fin_nat = is->is_nat[fin->fin_rev];
2607
2608	fin->fin_state = is;
2609	is->is_touched = fr_ticks;
2610	MUTEX_ENTER(&is->is_lock);
2611	is->is_ref++;
2612	MUTEX_EXIT(&is->is_lock);
2613	RWLOCK_EXIT(&ipf_state);
2614	fin->fin_flx |= FI_STATE;
2615	if ((pass & FR_LOGFIRST) != 0)
2616		pass &= ~(FR_LOGFIRST|FR_LOG);
2617	*passp = pass;
2618	return fr;
2619}
2620
2621
2622/* ------------------------------------------------------------------------ */
2623/* Function:    fr_fixoutisn                                                */
2624/* Returns:     Nil                                                         */
2625/* Parameters:  fin(I)   - pointer to packet information                    */
2626/*              is(I)  - pointer to master state structure                  */
2627/*                                                                          */
2628/* Called only for outbound packets, adjusts the sequence number and the    */
2629/* TCP checksum to match that change.                                       */
2630/* ------------------------------------------------------------------------ */
2631static void fr_fixoutisn(fin, is)
2632fr_info_t *fin;
2633ipstate_t *is;
2634{
2635	tcphdr_t *tcp;
2636	int rev;
2637	u_32_t seq;
2638
2639	tcp = fin->fin_dp;
2640	rev = fin->fin_rev;
2641	if ((is->is_flags & IS_ISNSYN) != 0) {
2642		if (rev == 0) {
2643			seq = ntohl(tcp->th_seq);
2644			seq += is->is_isninc[0];
2645			tcp->th_seq = htonl(seq);
2646			fix_outcksum(fin, &tcp->th_sum, is->is_sumd[0]);
2647		}
2648	}
2649	if ((is->is_flags & IS_ISNACK) != 0) {
2650		if (rev == 1) {
2651			seq = ntohl(tcp->th_seq);
2652			seq += is->is_isninc[1];
2653			tcp->th_seq = htonl(seq);
2654			fix_outcksum(fin, &tcp->th_sum, is->is_sumd[1]);
2655		}
2656	}
2657}
2658
2659
2660/* ------------------------------------------------------------------------ */
2661/* Function:    fr_fixinisn                                                 */
2662/* Returns:     Nil                                                         */
2663/* Parameters:  fin(I)   - pointer to packet information                    */
2664/*              is(I)  - pointer to master state structure                  */
2665/*                                                                          */
2666/* Called only for inbound packets, adjusts the acknowledge number and the  */
2667/* TCP checksum to match that change.                                       */
2668/* ------------------------------------------------------------------------ */
2669static void fr_fixinisn(fin, is)
2670fr_info_t *fin;
2671ipstate_t *is;
2672{
2673	tcphdr_t *tcp;
2674	int rev;
2675	u_32_t ack;
2676
2677	tcp = fin->fin_dp;
2678	rev = fin->fin_rev;
2679	if ((is->is_flags & IS_ISNSYN) != 0) {
2680		if (rev == 1) {
2681			ack = ntohl(tcp->th_ack);
2682			ack -= is->is_isninc[0];
2683			tcp->th_ack = htonl(ack);
2684			fix_incksum(fin, &tcp->th_sum, is->is_sumd[0]);
2685		}
2686	}
2687	if ((is->is_flags & IS_ISNACK) != 0) {
2688		if (rev == 0) {
2689			ack = ntohl(tcp->th_ack);
2690			ack -= is->is_isninc[1];
2691			tcp->th_ack = htonl(ack);
2692			fix_incksum(fin, &tcp->th_sum, is->is_sumd[1]);
2693		}
2694	}
2695}
2696
2697
2698/* ------------------------------------------------------------------------ */
2699/* Function:    fr_statesync                                                */
2700/* Returns:     Nil                                                         */
2701/* Parameters:  ifp(I) - pointer to interface                               */
2702/*                                                                          */
2703/* Walk through all state entries and if an interface pointer match is      */
2704/* found then look it up again, based on its name in case the pointer has   */
2705/* changed since last time.                                                 */
2706/*                                                                          */
2707/* If ifp is passed in as being non-null then we are only doing updates for */
2708/* existing, matching, uses of it.                                          */
2709/* ------------------------------------------------------------------------ */
2710void fr_statesync(ifp)
2711void *ifp;
2712{
2713	ipstate_t *is;
2714	int i;
2715
2716	if (fr_running <= 0)
2717		return;
2718
2719	WRITE_ENTER(&ipf_state);
2720
2721	if (fr_running <= 0) {
2722		RWLOCK_EXIT(&ipf_state);
2723		return;
2724	}
2725
2726	for (is = ips_list; is; is = is->is_next) {
2727		/*
2728		 * Look up all the interface names in the state entry.
2729		 */
2730		for (i = 0; i < 4; i++) {
2731			if (ifp == NULL || ifp == is->is_ifp[i])
2732				is->is_ifp[i] = fr_resolvenic(is->is_ifname[i],
2733							      is->is_v);
2734		}
2735	}
2736	RWLOCK_EXIT(&ipf_state);
2737}
2738
2739
2740/* ------------------------------------------------------------------------ */
2741/* Function:    fr_delstate                                                 */
2742/* Returns:     Nil                                                         */
2743/* Parameters:  is(I)  - pointer to state structure to delete               */
2744/*              why(I) - if not 0, log reason why it was deleted            */
2745/* Write Locks: ipf_state                                                   */
2746/*                                                                          */
2747/* Deletes a state entry from the enumerated list as well as the hash table */
2748/* and timeout queue lists.  Make adjustments to hash table statistics and  */
2749/* global counters as required.                                             */
2750/* ------------------------------------------------------------------------ */
2751static void fr_delstate(is, why)
2752ipstate_t *is;
2753int why;
2754{
2755
2756	ASSERT(rw_read_locked(&ipf_state.ipf_lk) == 0);
2757
2758	/*
2759	 * Since we want to delete this, remove it from the state table,
2760	 * where it can be found & used, first.
2761	 */
2762	if (is->is_pnext != NULL) {
2763		*is->is_pnext = is->is_next;
2764
2765		if (is->is_next != NULL)
2766			is->is_next->is_pnext = is->is_pnext;
2767
2768		is->is_pnext = NULL;
2769		is->is_next = NULL;
2770	}
2771
2772	if (is->is_phnext != NULL) {
2773		*is->is_phnext = is->is_hnext;
2774		if (is->is_hnext != NULL)
2775			is->is_hnext->is_phnext = is->is_phnext;
2776		if (ips_table[is->is_hv] == NULL)
2777			ips_stats.iss_inuse--;
2778		ips_stats.iss_bucketlen[is->is_hv]--;
2779
2780		is->is_phnext = NULL;
2781		is->is_hnext = NULL;
2782	}
2783
2784	/*
2785	 * Because ips_stats.iss_wild is a count of entries in the state
2786	 * table that have wildcard flags set, only decerement it once
2787	 * and do it here.
2788	 */
2789	if (is->is_flags & (SI_WILDP|SI_WILDA)) {
2790		if (!(is->is_flags & SI_CLONED)) {
2791			ATOMIC_DECL(ips_stats.iss_wild);
2792		}
2793		is->is_flags &= ~(SI_WILDP|SI_WILDA);
2794	}
2795
2796	/*
2797	 * Next, remove it from the timeout queue it is in.
2798	 */
2799	fr_deletequeueentry(&is->is_sti);
2800
2801	if (is->is_me != NULL) {
2802		*is->is_me = NULL;
2803		is->is_me = NULL;
2804	}
2805
2806	/*
2807	 * If it is still in use by something else, do not go any further,
2808	 * but note that at this point it is now an orphan.
2809	 */
2810	is->is_ref--;
2811	if (is->is_ref > 0)
2812		return;
2813
2814	if (is->is_tqehead[0] != NULL) {
2815		if (fr_deletetimeoutqueue(is->is_tqehead[0]) == 0)
2816			fr_freetimeoutqueue(is->is_tqehead[0]);
2817	}
2818	if (is->is_tqehead[1] != NULL) {
2819		if (fr_deletetimeoutqueue(is->is_tqehead[1]) == 0)
2820			fr_freetimeoutqueue(is->is_tqehead[1]);
2821	}
2822
2823#ifdef	IPFILTER_SYNC
2824	if (is->is_sync)
2825		ipfsync_del(is->is_sync);
2826#endif
2827#ifdef	IPFILTER_SCAN
2828	(void) ipsc_detachis(is);
2829#endif
2830
2831	if (ipstate_logging != 0 && why != 0)
2832		ipstate_log(is, why);
2833
2834	if (is->is_p == IPPROTO_TCP)
2835		ips_stats.iss_fin++;
2836	else
2837		ips_stats.iss_expire++;
2838
2839	if (is->is_rule != NULL) {
2840		is->is_rule->fr_statecnt--;
2841		(void)fr_derefrule(&is->is_rule);
2842	}
2843
2844	MUTEX_DESTROY(&is->is_lock);
2845	KFREE(is);
2846	ips_num--;
2847}
2848
2849
2850/* ------------------------------------------------------------------------ */
2851/* Function:    fr_timeoutstate                                             */
2852/* Returns:     Nil                                                         */
2853/* Parameters:  Nil                                                         */
2854/*                                                                          */
2855/* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
2856/* used here is to keep the queue sorted with the oldest things at the top  */
2857/* and the youngest at the bottom.  So if the top one doesn't need to be    */
2858/* expired then neither will any under it.                                  */
2859/* ------------------------------------------------------------------------ */
2860void fr_timeoutstate()
2861{
2862	ipftq_t *ifq, *ifqnext;
2863	ipftqent_t *tqe, *tqn;
2864	ipstate_t *is;
2865	SPL_INT(s);
2866
2867	SPL_NET(s);
2868	WRITE_ENTER(&ipf_state);
2869	for (ifq = ips_tqtqb; ifq != NULL; ifq = ifq->ifq_next)
2870		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
2871			if (tqe->tqe_die > fr_ticks)
2872				break;
2873			tqn = tqe->tqe_next;
2874			is = tqe->tqe_parent;
2875			fr_delstate(is, ISL_EXPIRE);
2876		}
2877
2878	for (ifq = ips_utqe; ifq != NULL; ifq = ifqnext) {
2879		ifqnext = ifq->ifq_next;
2880
2881		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
2882			if (tqe->tqe_die > fr_ticks)
2883				break;
2884			tqn = tqe->tqe_next;
2885			is = tqe->tqe_parent;
2886			fr_delstate(is, ISL_EXPIRE);
2887		}
2888	}
2889
2890	for (ifq = ips_utqe; ifq != NULL; ifq = ifqnext) {
2891		ifqnext = ifq->ifq_next;
2892
2893		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
2894		    (ifq->ifq_ref == 0)) {
2895			fr_freetimeoutqueue(ifq);
2896		}
2897	}
2898
2899	if (fr_state_doflush) {
2900		(void) fr_state_flush(2, 0);
2901		fr_state_doflush = 0;
2902	}
2903
2904	RWLOCK_EXIT(&ipf_state);
2905	SPL_X(s);
2906}
2907
2908
2909/* ------------------------------------------------------------------------ */
2910/* Function:    fr_state_flush                                              */
2911/* Returns:     int - 0 == success, -1 == failure                           */
2912/* Parameters:  Nil                                                         */
2913/* Write Locks: ipf_state                                                   */
2914/*                                                                          */
2915/* Flush state tables.  Three actions currently defined:                    */
2916/* which == 0 : flush all state table entries                               */
2917/* which == 1 : flush TCP connections which have started to close but are   */
2918/*	      stuck for some reason.                                        */
2919/* which == 2 : flush TCP connections which have been idle for a long time, */
2920/*	      starting at > 4 days idle and working back in successive half-*/
2921/*	      days to at most 12 hours old.  If this fails to free enough   */
2922/*            slots then work backwards in half hour slots to 30 minutes.   */
2923/*            If that too fails, then work backwards in 30 second intervals */
2924/*            for the last 30 minutes to at worst 30 seconds idle.          */
2925/* ------------------------------------------------------------------------ */
2926static int fr_state_flush(which, proto)
2927int which, proto;
2928{
2929	ipftq_t *ifq, *ifqnext;
2930	ipftqent_t *tqe, *tqn;
2931	ipstate_t *is, **isp;
2932	int delete, removed;
2933	long try, maxtick;
2934	u_long interval;
2935	SPL_INT(s);
2936
2937	removed = 0;
2938
2939	SPL_NET(s);
2940	for (isp = &ips_list; ((is = *isp) != NULL); ) {
2941		delete = 0;
2942
2943		if ((proto != 0) && (is->is_v != proto)) {
2944			isp = &is->is_next;
2945			continue;
2946		}
2947
2948		switch (which)
2949		{
2950		case 0 :
2951			delete = 1;
2952			break;
2953		case 1 :
2954		case 2 :
2955			if (is->is_p != IPPROTO_TCP)
2956				break;
2957			if ((is->is_state[0] != IPF_TCPS_ESTABLISHED) ||
2958			    (is->is_state[1] != IPF_TCPS_ESTABLISHED))
2959				delete = 1;
2960			break;
2961		}
2962
2963		if (delete) {
2964			fr_delstate(is, ISL_FLUSH);
2965			removed++;
2966		} else
2967			isp = &is->is_next;
2968	}
2969
2970	if (which != 2) {
2971		SPL_X(s);
2972		return removed;
2973	}
2974
2975	/*
2976	 * Asked to remove inactive entries because the table is full, try
2977	 * again, 3 times, if first attempt failed with a different criteria
2978	 * each time.  The order tried in must be in decreasing age.
2979	 * Another alternative is to implement random drop and drop N entries
2980	 * at random until N have been freed up.
2981	 */
2982	if (fr_ticks - ips_last_force_flush < IPF_TTLVAL(5))
2983		goto force_flush_skipped;
2984	ips_last_force_flush = fr_ticks;
2985
2986	if (fr_ticks > IPF_TTLVAL(43200))
2987		interval = IPF_TTLVAL(43200);
2988	else if (fr_ticks > IPF_TTLVAL(1800))
2989		interval = IPF_TTLVAL(1800);
2990	else if (fr_ticks > IPF_TTLVAL(30))
2991		interval = IPF_TTLVAL(30);
2992	else
2993		interval = IPF_TTLVAL(10);
2994	try = fr_ticks - (fr_ticks - interval);
2995	if (try < 0)
2996		goto force_flush_skipped;
2997
2998	while (removed == 0) {
2999		maxtick = fr_ticks - interval;
3000		if (maxtick < 0)
3001			break;
3002
3003		while (try < maxtick) {
3004			for (ifq = ips_tqtqb; ifq != NULL;
3005			     ifq = ifq->ifq_next) {
3006				for (tqn = ifq->ifq_head;
3007				     ((tqe = tqn) != NULL); ) {
3008					if (tqe->tqe_die > try)
3009						break;
3010					tqn = tqe->tqe_next;
3011					is = tqe->tqe_parent;
3012					fr_delstate(is, ISL_EXPIRE);
3013					removed++;
3014				}
3015			}
3016
3017			for (ifq = ips_utqe; ifq != NULL; ifq = ifqnext) {
3018				ifqnext = ifq->ifq_next;
3019
3020				for (tqn = ifq->ifq_head;
3021				     ((tqe = tqn) != NULL); ) {
3022					if (tqe->tqe_die > try)
3023						break;
3024					tqn = tqe->tqe_next;
3025					is = tqe->tqe_parent;
3026					fr_delstate(is, ISL_EXPIRE);
3027					removed++;
3028				}
3029			}
3030			if (try + interval > maxtick)
3031				break;
3032			try += interval;
3033		}
3034
3035		if (removed == 0) {
3036			if (interval == IPF_TTLVAL(43200)) {
3037				interval = IPF_TTLVAL(1800);
3038			} else if (interval == IPF_TTLVAL(1800)) {
3039				interval = IPF_TTLVAL(30);
3040			} else if (interval == IPF_TTLVAL(30)) {
3041				interval = IPF_TTLVAL(10);
3042			} else {
3043				break;
3044			}
3045		}
3046	}
3047force_flush_skipped:
3048	SPL_X(s);
3049	return removed;
3050}
3051
3052
3053
3054/* ------------------------------------------------------------------------ */
3055/* Function:    fr_tcp_age                                                  */
3056/* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3057/* Parameters:  tq(I)    - pointer to timeout queue information             */
3058/*              fin(I)   - pointer to packet information                    */
3059/*              tqtab(I) - TCP timeout queue table this is in               */
3060/*              flags(I) - flags from state/NAT entry                       */
3061/*                                                                          */
3062/* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3063/*                                                                          */
3064/* - (try to) base state transitions on real evidence only,                 */
3065/*   i.e. packets that are sent and have been received by ipfilter;         */
3066/*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
3067/*                                                                          */
3068/* - deal with half-closed connections correctly;                           */
3069/*                                                                          */
3070/* - store the state of the source in state[0] such that ipfstat            */
3071/*   displays the state as source/dest instead of dest/source; the calls    */
3072/*   to fr_tcp_age have been changed accordingly.                           */
3073/*                                                                          */
3074/* Internal Parameters:                                                     */
3075/*                                                                          */
3076/*    state[0] = state of source (host that initiated connection)           */
3077/*    state[1] = state of dest   (host that accepted the connection)        */
3078/*                                                                          */
3079/*    dir == 0 : a packet from source to dest                               */
3080/*    dir == 1 : a packet from dest to source                               */
3081/*                                                                          */
3082/* Locking: it is assumed that the parent of the tqe structure is locked.   */
3083/* ------------------------------------------------------------------------ */
3084int fr_tcp_age(tqe, fin, tqtab, flags)
3085ipftqent_t *tqe;
3086fr_info_t *fin;
3087ipftq_t *tqtab;
3088int flags;
3089{
3090	int dlen, ostate, nstate, rval, dir;
3091	u_char tcpflags;
3092	tcphdr_t *tcp;
3093
3094	tcp = fin->fin_dp;
3095
3096	rval = 0;
3097	dir = fin->fin_rev;
3098	tcpflags = tcp->th_flags;
3099	dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
3100
3101	if (tcpflags & TH_RST) {
3102		if (!(tcpflags & TH_PUSH) && !dlen)
3103			nstate = IPF_TCPS_CLOSED;
3104		else
3105			nstate = IPF_TCPS_CLOSE_WAIT;
3106		rval = 1;
3107	} else {
3108		ostate = tqe->tqe_state[1 - dir];
3109		nstate = tqe->tqe_state[dir];
3110
3111		switch (nstate)
3112		{
3113		case IPF_TCPS_CLOSED: /* 0 */
3114			if ((tcpflags & TH_OPENING) == TH_OPENING) {
3115				/*
3116				 * 'dir' received an S and sends SA in
3117				 * response, CLOSED -> SYN_RECEIVED
3118				 */
3119				nstate = IPF_TCPS_SYN_RECEIVED;
3120				rval = 1;
3121			} else if ((tcpflags & TH_OPENING) == TH_SYN) {
3122				/* 'dir' sent S, CLOSED -> SYN_SENT */
3123				nstate = IPF_TCPS_SYN_SENT;
3124				rval = 1;
3125			}
3126			/*
3127			 * the next piece of code makes it possible to get
3128			 * already established connections into the state table
3129			 * after a restart or reload of the filter rules; this
3130			 * does not work when a strict 'flags S keep state' is
3131			 * used for tcp connections of course
3132			 */
3133			if (((flags & IS_TCPFSM) == 0) &&
3134			    ((tcpflags & TH_ACKMASK) == TH_ACK)) {
3135				/*
3136				 * we saw an A, guess 'dir' is in ESTABLISHED
3137				 * mode
3138				 */
3139				switch (ostate)
3140				{
3141				case IPF_TCPS_CLOSED :
3142				case IPF_TCPS_SYN_RECEIVED :
3143					nstate = IPF_TCPS_HALF_ESTAB;
3144					rval = 1;
3145					break;
3146				case IPF_TCPS_HALF_ESTAB :
3147				case IPF_TCPS_ESTABLISHED :
3148					nstate = IPF_TCPS_ESTABLISHED;
3149					rval = 1;
3150					break;
3151				default :
3152					break;
3153				}
3154			}
3155			/*
3156			 * TODO: besides regular ACK packets we can have other
3157			 * packets as well; it is yet to be determined how we
3158			 * should initialize the states in those cases
3159			 */
3160			break;
3161
3162		case IPF_TCPS_LISTEN: /* 1 */
3163			/* NOT USED */
3164			break;
3165
3166		case IPF_TCPS_SYN_SENT: /* 2 */
3167			if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
3168				/*
3169				 * A retransmitted SYN packet.  We do not reset
3170				 * the timeout here to fr_tcptimeout because a
3171				 * connection connect timeout does not renew
3172				 * after every packet that is sent.  We need to
3173				 * set rval so as to indicate the packet has
3174				 * passed the check for its flags being valid
3175				 * in the TCP FSM.  Setting rval to 2 has the
3176				 * result of not resetting the timeout.
3177				 */
3178				rval = 2;
3179			} else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
3180				   TH_ACK) {
3181				/*
3182				 * we see an A from 'dir' which is in SYN_SENT
3183				 * state: 'dir' sent an A in response to an SA
3184				 * which it received, SYN_SENT -> ESTABLISHED
3185				 */
3186				nstate = IPF_TCPS_ESTABLISHED;
3187				rval = 1;
3188			} else if (tcpflags & TH_FIN) {
3189				/*
3190				 * we see an F from 'dir' which is in SYN_SENT
3191				 * state and wants to close its side of the
3192				 * connection; SYN_SENT -> FIN_WAIT_1
3193				 */
3194				nstate = IPF_TCPS_FIN_WAIT_1;
3195				rval = 1;
3196			} else if ((tcpflags & TH_OPENING) == TH_OPENING) {
3197				/*
3198				 * we see an SA from 'dir' which is already in
3199				 * SYN_SENT state, this means we have a
3200				 * simultaneous open; SYN_SENT -> SYN_RECEIVED
3201				 */
3202				nstate = IPF_TCPS_SYN_RECEIVED;
3203				rval = 1;
3204			}
3205			break;
3206
3207		case IPF_TCPS_SYN_RECEIVED: /* 3 */
3208			if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
3209				/*
3210				 * we see an A from 'dir' which was in
3211				 * SYN_RECEIVED state so it must now be in
3212				 * established state, SYN_RECEIVED ->
3213				 * ESTABLISHED
3214				 */
3215				nstate = IPF_TCPS_ESTABLISHED;
3216				rval = 1;
3217			} else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
3218				   TH_OPENING) {
3219				/*
3220				 * We see an SA from 'dir' which is already in
3221				 * SYN_RECEIVED state.
3222				 */
3223				rval = 2;
3224			} else if (tcpflags & TH_FIN) {
3225				/*
3226				 * we see an F from 'dir' which is in
3227				 * SYN_RECEIVED state and wants to close its
3228				 * side of the connection; SYN_RECEIVED ->
3229				 * FIN_WAIT_1
3230				 */
3231				nstate = IPF_TCPS_FIN_WAIT_1;
3232				rval = 1;
3233			}
3234			break;
3235
3236		case IPF_TCPS_HALF_ESTAB: /* 4 */
3237			if (tcpflags & TH_FIN) {
3238				nstate = IPF_TCPS_FIN_WAIT_1;
3239				rval = 1;
3240			} else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
3241				/*
3242				 * If we've picked up a connection in mid
3243				 * flight, we could be looking at a follow on
3244				 * packet from the same direction as the one
3245				 * that created this state.  Recognise it but
3246				 * do not advance the entire connection's
3247				 * state.
3248				 */
3249				switch (ostate)
3250				{
3251				case IPF_TCPS_CLOSED :
3252				case IPF_TCPS_SYN_SENT :
3253				case IPF_TCPS_SYN_RECEIVED :
3254					rval = 1;
3255					break;
3256				case IPF_TCPS_HALF_ESTAB :
3257				case IPF_TCPS_ESTABLISHED :
3258					nstate = IPF_TCPS_ESTABLISHED;
3259					rval = 1;
3260					break;
3261				default :
3262					break;
3263				}
3264			}
3265			break;
3266
3267		case IPF_TCPS_ESTABLISHED: /* 5 */
3268			rval = 1;
3269			if (tcpflags & TH_FIN) {
3270				/*
3271				 * 'dir' closed its side of the connection;
3272				 * this gives us a half-closed connection;
3273				 * ESTABLISHED -> FIN_WAIT_1
3274				 */
3275				nstate = IPF_TCPS_FIN_WAIT_1;
3276			} else if (tcpflags & TH_ACK) {
3277				/*
3278				 * an ACK, should we exclude other flags here?
3279				 */
3280				if (ostate == IPF_TCPS_FIN_WAIT_1) {
3281					/*
3282					 * We know the other side did an active
3283					 * close, so we are ACKing the recvd
3284					 * FIN packet (does the window matching
3285					 * code guarantee this?) and go into
3286					 * CLOSE_WAIT state; this gives us a
3287					 * half-closed connection
3288					 */
3289					nstate = IPF_TCPS_CLOSE_WAIT;
3290				} else if (ostate < IPF_TCPS_CLOSE_WAIT) {
3291					/*
3292					 * still a fully established
3293					 * connection reset timeout
3294					 */
3295					nstate = IPF_TCPS_ESTABLISHED;
3296				}
3297			}
3298			break;
3299
3300		case IPF_TCPS_CLOSE_WAIT: /* 6 */
3301			rval = 1;
3302			if (tcpflags & TH_FIN) {
3303				/*
3304				 * application closed and 'dir' sent a FIN,
3305				 * we're now going into LAST_ACK state
3306				 */
3307				nstate = IPF_TCPS_LAST_ACK;
3308			} else {
3309				/*
3310				 * we remain in CLOSE_WAIT because the other
3311				 * side has closed already and we did not
3312				 * close our side yet; reset timeout
3313				 */
3314				nstate = IPF_TCPS_CLOSE_WAIT;
3315			}
3316			break;
3317
3318		case IPF_TCPS_FIN_WAIT_1: /* 7 */
3319			rval = 1;
3320			if ((tcpflags & TH_ACK) &&
3321			    ostate > IPF_TCPS_CLOSE_WAIT) {
3322				/*
3323				 * if the other side is not active anymore
3324				 * it has sent us a FIN packet that we are
3325				 * ack'ing now with an ACK; this means both
3326				 * sides have now closed the connection and
3327				 * we go into TIME_WAIT
3328				 */
3329				/*
3330				 * XXX: how do we know we really are ACKing
3331				 * the FIN packet here? does the window code
3332				 * guarantee that?
3333				 */
3334				nstate = IPF_TCPS_TIME_WAIT;
3335			} else {
3336				/*
3337				 * we closed our side of the connection
3338				 * already but the other side is still active
3339				 * (ESTABLISHED/CLOSE_WAIT); continue with
3340				 * this half-closed connection
3341				 */
3342				nstate = IPF_TCPS_FIN_WAIT_1;
3343			}
3344			break;
3345
3346		case IPF_TCPS_CLOSING: /* 8 */
3347			/* NOT USED */
3348			break;
3349
3350		case IPF_TCPS_LAST_ACK: /* 9 */
3351			if (tcpflags & TH_ACK) {
3352				if ((tcpflags & TH_PUSH) || dlen)
3353					/*
3354					 * there is still data to be delivered,
3355					 * reset timeout
3356					 */
3357					rval = 1;
3358				else
3359					rval = 2;
3360			}
3361			/*
3362			 * we cannot detect when we go out of LAST_ACK state to
3363			 * CLOSED because that is based on the reception of ACK
3364			 * packets; ipfilter can only detect that a packet
3365			 * has been sent by a host
3366			 */
3367			break;
3368
3369		case IPF_TCPS_FIN_WAIT_2: /* 10 */
3370			rval = 1;
3371			if ((tcpflags & TH_OPENING) == TH_OPENING)
3372				nstate = IPF_TCPS_SYN_RECEIVED;
3373			else if (tcpflags & TH_SYN)
3374				nstate = IPF_TCPS_SYN_SENT;
3375			break;
3376
3377		case IPF_TCPS_TIME_WAIT: /* 11 */
3378			/* we're in 2MSL timeout now */
3379			rval = 1;
3380			break;
3381
3382		default :
3383#if defined(_KERNEL)
3384# if SOLARIS
3385			cmn_err(CE_NOTE,
3386				"tcp %lx flags %x si %lx nstate %d ostate %d\n",
3387				(u_long)tcp, tcpflags, (u_long)tqe,
3388				nstate, ostate);
3389# else
3390			printf("tcp %lx flags %x si %lx nstate %d ostate %d\n",
3391				(u_long)tcp, tcpflags, (u_long)tqe,
3392				nstate, ostate);
3393# endif
3394#else
3395			abort();
3396#endif
3397			break;
3398		}
3399	}
3400
3401	/*
3402	 * If rval == 2 then do not update the queue position, but treat the
3403	 * packet as being ok.
3404	 */
3405	if (rval == 2)
3406		rval = 1;
3407	else if (rval == 1) {
3408		tqe->tqe_state[dir] = nstate;
3409		if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
3410			fr_movequeue(tqe, tqe->tqe_ifq, tqtab + nstate);
3411	}
3412
3413	return rval;
3414}
3415
3416
3417/* ------------------------------------------------------------------------ */
3418/* Function:    ipstate_log                                                 */
3419/* Returns:     Nil                                                         */
3420/* Parameters:  is(I)   - pointer to state structure                        */
3421/*              type(I) - type of log entry to create                       */
3422/*                                                                          */
3423/* Creates a state table log entry using the state structure and type info. */
3424/* passed in.  Log packet/byte counts, source/destination address and other */
3425/* protocol specific information.                                           */
3426/* ------------------------------------------------------------------------ */
3427void ipstate_log(is, type)
3428struct ipstate *is;
3429u_int type;
3430{
3431#ifdef	IPFILTER_LOG
3432	struct	ipslog	ipsl;
3433	size_t sizes[1];
3434	void *items[1];
3435	int types[1];
3436
3437	/*
3438	 * Copy information out of the ipstate_t structure and into the
3439	 * structure used for logging.
3440	 */
3441	ipsl.isl_type = type;
3442	ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
3443	ipsl.isl_bytes[0] = is->is_bytes[0];
3444	ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
3445	ipsl.isl_bytes[1] = is->is_bytes[1];
3446	ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
3447	ipsl.isl_bytes[2] = is->is_bytes[2];
3448	ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
3449	ipsl.isl_bytes[3] = is->is_bytes[3];
3450	ipsl.isl_src = is->is_src;
3451	ipsl.isl_dst = is->is_dst;
3452	ipsl.isl_p = is->is_p;
3453	ipsl.isl_v = is->is_v;
3454	ipsl.isl_flags = is->is_flags;
3455	ipsl.isl_tag = is->is_tag;
3456	ipsl.isl_rulen = is->is_rulen;
3457	(void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
3458
3459	if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
3460		ipsl.isl_sport = is->is_sport;
3461		ipsl.isl_dport = is->is_dport;
3462		if (ipsl.isl_p == IPPROTO_TCP) {
3463			ipsl.isl_state[0] = is->is_state[0];
3464			ipsl.isl_state[1] = is->is_state[1];
3465		}
3466	} else if (ipsl.isl_p == IPPROTO_ICMP) {
3467		ipsl.isl_itype = is->is_icmp.ici_type;
3468	} else if (ipsl.isl_p == IPPROTO_ICMPV6) {
3469		ipsl.isl_itype = is->is_icmp.ici_type;
3470	} else {
3471		ipsl.isl_ps.isl_filler[0] = 0;
3472		ipsl.isl_ps.isl_filler[1] = 0;
3473	}
3474
3475	items[0] = &ipsl;
3476	sizes[0] = sizeof(ipsl);
3477	types[0] = 0;
3478
3479	if (ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1)) {
3480		ATOMIC_INCL(ips_stats.iss_logged);
3481	} else {
3482		ATOMIC_INCL(ips_stats.iss_logfail);
3483	}
3484#endif
3485}
3486
3487
3488#ifdef	USE_INET6
3489/* ------------------------------------------------------------------------ */
3490/* Function:    fr_checkicmp6matchingstate                                  */
3491/* Returns:     ipstate_t* - NULL == no match found,                        */
3492/*                           else  pointer to matching state entry          */
3493/* Parameters:  fin(I) - pointer to packet information                      */
3494/* Locks:       NULL == no locks, else Read Lock on ipf_state               */
3495/*                                                                          */
3496/* If we've got an ICMPv6 error message, using the information stored in    */
3497/* the ICMPv6 packet, look for a matching state table entry.                */
3498/* ------------------------------------------------------------------------ */
3499static ipstate_t *fr_checkicmp6matchingstate(fin)
3500fr_info_t *fin;
3501{
3502	struct icmp6_hdr *ic6, *oic;
3503	int type, backward, i;
3504	ipstate_t *is, **isp;
3505	u_short sport, dport;
3506	i6addr_t dst, src;
3507	u_short savelen;
3508	icmpinfo_t *ic;
3509	fr_info_t ofin;
3510	tcphdr_t *tcp;
3511	ip6_t *oip6;
3512	u_char	pr;
3513	u_int hv;
3514
3515	/*
3516	 * Does it at least have the return (basic) IP header ?
3517	 * Is it an actual recognised ICMP error type?
3518	 * Only a basic IP header (no options) should be with
3519	 * an ICMP error header.
3520	 */
3521	if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
3522	    !(fin->fin_flx & FI_ICMPERR))
3523		return NULL;
3524
3525	ic6 = fin->fin_dp;
3526	type = ic6->icmp6_type;
3527
3528	oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
3529	if (fin->fin_plen < sizeof(*oip6))
3530		return NULL;
3531
3532	bcopy((char *)fin, (char *)&ofin, sizeof(fin));
3533	ofin.fin_v = 6;
3534	ofin.fin_ifp = fin->fin_ifp;
3535	ofin.fin_out = !fin->fin_out;
3536	ofin.fin_m = NULL;	/* if dereferenced, panic XXX */
3537	ofin.fin_mp = NULL;	/* if dereferenced, panic XXX */
3538
3539	/*
3540	 * We make a fin entry to be able to feed it to
3541	 * matchsrcdst. Note that not all fields are necessary
3542	 * but this is the cleanest way. Note further we fill
3543	 * in fin_mp such that if someone uses it we'll get
3544	 * a kernel panic. fr_matchsrcdst does not use this.
3545	 *
3546	 * watch out here, as ip is in host order and oip6 in network
3547	 * order. Any change we make must be undone afterwards.
3548	 */
3549	savelen = oip6->ip6_plen;
3550	oip6->ip6_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
3551	ofin.fin_flx = FI_NOCKSUM;
3552	ofin.fin_ip = (ip_t *)oip6;
3553	ofin.fin_plen = oip6->ip6_plen;
3554	(void) fr_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
3555	ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
3556	oip6->ip6_plen = savelen;
3557
3558	if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
3559		oic = (struct icmp6_hdr *)(oip6 + 1);
3560		/*
3561		 * an ICMP error can only be generated as a result of an
3562		 * ICMP query, not as the response on an ICMP error
3563		 *
3564		 * XXX theoretically ICMP_ECHOREP and the other reply's are
3565		 * ICMP query's as well, but adding them here seems strange XXX
3566		 */
3567		 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
3568		    	return NULL;
3569
3570		/*
3571		 * perform a lookup of the ICMP packet in the state table
3572		 */
3573		hv = (pr = oip6->ip6_nxt);
3574		src.in6 = oip6->ip6_src;
3575		hv += src.in4.s_addr;
3576		dst.in6 = oip6->ip6_dst;
3577		hv += dst.in4.s_addr;
3578		hv += oic->icmp6_id;
3579		hv += oic->icmp6_seq;
3580		hv = DOUBLE_HASH(hv);
3581
3582		READ_ENTER(&ipf_state);
3583		for (isp = &ips_table[hv]; ((is = *isp) != NULL); ) {
3584			ic = &is->is_icmp;
3585			isp = &is->is_hnext;
3586			if ((is->is_p == pr) &&
3587			    !(is->is_pass & FR_NOICMPERR) &&
3588			    (oic->icmp6_id == ic->ici_id) &&
3589			    (oic->icmp6_seq == ic->ici_seq) &&
3590			    (is = fr_matchsrcdst(&ofin, is, &src,
3591						 &dst, NULL, FI_ICMPCMP))) {
3592			    	/*
3593			    	 * in the state table ICMP query's are stored
3594			    	 * with the type of the corresponding ICMP
3595			    	 * response. Correct here
3596			    	 */
3597				if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
3598				     (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
3599				     (ic->ici_type - 1 == oic->icmp6_type )) {
3600				    	ips_stats.iss_hits++;
3601					backward = IP6_NEQ(&is->is_dst, &src);
3602					fin->fin_rev = !backward;
3603					i = (backward << 1) + fin->fin_out;
3604    					is->is_icmppkts[i]++;
3605					return is;
3606				}
3607			}
3608		}
3609		RWLOCK_EXIT(&ipf_state);
3610		return NULL;
3611	}
3612
3613	hv = (pr = oip6->ip6_nxt);
3614	src.in6 = oip6->ip6_src;
3615	hv += src.i6[0];
3616	hv += src.i6[1];
3617	hv += src.i6[2];
3618	hv += src.i6[3];
3619	dst.in6 = oip6->ip6_dst;
3620	hv += dst.i6[0];
3621	hv += dst.i6[1];
3622	hv += dst.i6[2];
3623	hv += dst.i6[3];
3624
3625	if ((oip6->ip6_nxt == IPPROTO_TCP) || (oip6->ip6_nxt == IPPROTO_UDP)) {
3626		tcp = (tcphdr_t *)(oip6 + 1);
3627		dport = tcp->th_dport;
3628		sport = tcp->th_sport;
3629		hv += dport;
3630		hv += sport;
3631	} else
3632		tcp = NULL;
3633	hv = DOUBLE_HASH(hv);
3634
3635	READ_ENTER(&ipf_state);
3636	for (isp = &ips_table[hv]; ((is = *isp) != NULL); ) {
3637		isp = &is->is_hnext;
3638		/*
3639		 * Only allow this icmp though if the
3640		 * encapsulated packet was allowed through the
3641		 * other way around. Note that the minimal amount
3642		 * of info present does not allow for checking against
3643		 * tcp internals such as seq and ack numbers.
3644		 */
3645		if ((is->is_p != pr) || (is->is_v != 6) ||
3646		    (is->is_pass & FR_NOICMPERR))
3647			continue;
3648		is = fr_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
3649		if (is != NULL) {
3650			ips_stats.iss_hits++;
3651			backward = IP6_NEQ(&is->is_dst, &src);
3652			fin->fin_rev = !backward;
3653			i = (backward << 1) + fin->fin_out;
3654			is->is_icmppkts[i]++;
3655			/*
3656			 * we deliberately do not touch the timeouts
3657			 * for the accompanying state table entry.
3658			 * It remains to be seen if that is correct. XXX
3659			 */
3660			return is;
3661		}
3662	}
3663	RWLOCK_EXIT(&ipf_state);
3664	return NULL;
3665}
3666#endif
3667
3668
3669/* ------------------------------------------------------------------------ */
3670/* Function:    fr_sttab_init                                               */
3671/* Returns:     Nil                                                         */
3672/* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
3673/*                                                                          */
3674/* Initialise the array of timeout queues for TCP.                          */
3675/* ------------------------------------------------------------------------ */
3676void fr_sttab_init(tqp)
3677ipftq_t *tqp;
3678{
3679	int i;
3680
3681	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
3682		tqp[i].ifq_ttl = 0;
3683		tqp[i].ifq_ref = 1;
3684		tqp[i].ifq_head = NULL;
3685		tqp[i].ifq_tail = &tqp[i].ifq_head;
3686		tqp[i].ifq_next = tqp + i + 1;
3687		MUTEX_INIT(&tqp[i].ifq_lock, "ipftq tcp tab");
3688	}
3689	tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
3690	tqp[IPF_TCPS_CLOSED].ifq_ttl = fr_tcpclosed;
3691	tqp[IPF_TCPS_LISTEN].ifq_ttl = fr_tcptimeout;
3692	tqp[IPF_TCPS_SYN_SENT].ifq_ttl = fr_tcptimeout;
3693	tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = fr_tcptimeout;
3694	tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = fr_tcpidletimeout;
3695	tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = fr_tcphalfclosed;
3696	tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = fr_tcphalfclosed;
3697	tqp[IPF_TCPS_CLOSING].ifq_ttl = fr_tcptimeout;
3698	tqp[IPF_TCPS_LAST_ACK].ifq_ttl = fr_tcplastack;
3699	tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = fr_tcpclosewait;
3700	tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = fr_tcptimeout;
3701	tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = fr_tcptimeout;
3702}
3703
3704
3705/* ------------------------------------------------------------------------ */
3706/* Function:    fr_sttab_destroy                                            */
3707/* Returns:     Nil                                                         */
3708/* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
3709/*                                                                          */
3710/* Do whatever is necessary to "destroy" each of the entries in the array   */
3711/* of timeout queues for TCP.                                               */
3712/* ------------------------------------------------------------------------ */
3713void fr_sttab_destroy(tqp)
3714ipftq_t *tqp;
3715{
3716	int i;
3717
3718	for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
3719		MUTEX_DESTROY(&tqp[i].ifq_lock);
3720}
3721
3722
3723/* ------------------------------------------------------------------------ */
3724/* Function:    fr_statederef                                               */
3725/* Returns:     Nil                                                         */
3726/* Parameters:  isp(I) - pointer to pointer to state table entry            */
3727/*                                                                          */
3728/* Decrement the reference counter for this state table entry and free it   */
3729/* if there are no more things using it.                                    */
3730/*                                                                          */
3731/* When operating in userland (ipftest), we have no timers to clear a state */
3732/* entry.  Therefore, we make a few simple tests before deleting an entry   */
3733/* outright.  We compare states on each side looking for a combination of   */
3734/* TIME_WAIT (should really be FIN_WAIT_2?) and LAST_ACK.  Then we factor   */
3735/* in packet direction with the interface list to make sure we don't        */
3736/* prematurely delete an entry on a final inbound packet that's we're also  */
3737/* supposed to route elsewhere.                                             */
3738/*                                                                          */
3739/* Internal parameters:                                                     */
3740/*    state[0] = state of source (host that initiated connection)           */
3741/*    state[1] = state of dest   (host that accepted the connection)        */
3742/*                                                                          */
3743/*    dir == 0 : a packet from source to dest                               */
3744/*    dir == 1 : a packet from dest to source                               */
3745/* ------------------------------------------------------------------------ */
3746void fr_statederef(fin, isp)
3747fr_info_t *fin;
3748ipstate_t **isp;
3749{
3750	ipstate_t *is = *isp;
3751#if 0
3752	int nstate, ostate, dir, eol;
3753
3754	eol = 0; /* End-of-the-line flag. */
3755	dir = fin->fin_rev;
3756	ostate = is->is_state[1 - dir];
3757	nstate = is->is_state[dir];
3758	/*
3759	 * Determine whether this packet is local or routed.  State entries
3760	 * with us as the destination will have an interface list of
3761	 * int1,-,-,int1.  Entries with us as the origin run as -,int1,int1,-.
3762	 */
3763	if ((fin->fin_p == IPPROTO_TCP) && (fin->fin_out == 0)) {
3764		if ((strcmp(is->is_ifname[0], is->is_ifname[3]) == 0) &&
3765		    (strcmp(is->is_ifname[1], is->is_ifname[2]) == 0)) {
3766			if ((dir == 0) &&
3767			    (strcmp(is->is_ifname[1], "-") == 0) &&
3768			    (strcmp(is->is_ifname[0], "-") != 0)) {
3769				eol = 1;
3770			} else if ((dir == 1) &&
3771				   (strcmp(is->is_ifname[0], "-") == 0) &&
3772				   (strcmp(is->is_ifname[1], "-") != 0)) {
3773				eol = 1;
3774			}
3775		}
3776	}
3777#endif
3778
3779	fin = fin;	/* LINT */
3780	is = *isp;
3781	*isp = NULL;
3782	WRITE_ENTER(&ipf_state);
3783	is->is_ref--;
3784	if (is->is_ref == 0) {
3785		is->is_ref++;		/* To counter ref-- in fr_delstate() */
3786		fr_delstate(is, ISL_EXPIRE);
3787#ifndef	_KERNEL
3788#if 0
3789	} else if (((fin->fin_out == 1) || (eol == 1)) &&
3790		   ((ostate == IPF_TCPS_LAST_ACK) &&
3791		   (nstate == IPF_TCPS_TIME_WAIT))) {
3792		;
3793#else
3794	} else if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
3795		   (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
3796#endif
3797		fr_delstate(is, ISL_ORPHAN);
3798#endif
3799	}
3800	RWLOCK_EXIT(&ipf_state);
3801}
3802
3803
3804/* ------------------------------------------------------------------------ */
3805/* Function:    fr_setstatequeue                                            */
3806/* Returns:     Nil                                                         */
3807/* Parameters:  is(I) - pointer to state structure                          */
3808/*              rev(I) - forward(0) or reverse(1) direction                 */
3809/* Locks:       ipf_state (read or write)                                   */
3810/*                                                                          */
3811/* Put the state entry on its default queue entry, using rev as a helped in */
3812/* determining which queue it should be placed on.                          */
3813/* ------------------------------------------------------------------------ */
3814void fr_setstatequeue(is, rev)
3815ipstate_t *is;
3816int rev;
3817{
3818	ipftq_t *oifq, *nifq;
3819
3820
3821	if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
3822		nifq = is->is_tqehead[rev];
3823	else
3824		nifq = NULL;
3825
3826	if (nifq == NULL) {
3827		switch (is->is_p)
3828		{
3829#ifdef USE_INET6
3830		case IPPROTO_ICMPV6 :
3831			if (rev == 1)
3832				nifq = &ips_icmpacktq;
3833			else
3834				nifq = &ips_icmptq;
3835			break;
3836#endif
3837		case IPPROTO_ICMP :
3838			if (rev == 1)
3839				nifq = &ips_icmpacktq;
3840			else
3841				nifq = &ips_icmptq;
3842			break;
3843		case IPPROTO_TCP :
3844			nifq = ips_tqtqb + is->is_state[rev];
3845			break;
3846
3847		case IPPROTO_UDP :
3848			if (rev == 1)
3849				nifq = &ips_udpacktq;
3850			else
3851				nifq = &ips_udptq;
3852			break;
3853
3854		default :
3855			nifq = &ips_iptq;
3856			break;
3857		}
3858	}
3859
3860	oifq = is->is_sti.tqe_ifq;
3861	/*
3862	 * If it's currently on a timeout queue, move it from one queue to
3863	 * another, else put it on the end of the newly determined queue.
3864	 */
3865	if (oifq != NULL)
3866		fr_movequeue(&is->is_sti, oifq, nifq);
3867	else
3868		fr_queueappend(&is->is_sti, nifq, is);
3869	return;
3870}
3871