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