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