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