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