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