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