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