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