xref: /titanic_52/usr/src/uts/common/inet/ipf/fil.c (revision 40cdc2e8babc6bb3ab847f6a129fc9eb76c5f4d5)
1 /*
2  * Copyright (C) 1993-2003 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
7  * Use is subject to license terms.
8  */
9 
10 #if defined(KERNEL) || defined(_KERNEL)
11 # undef KERNEL
12 # undef _KERNEL
13 # define        KERNEL	1
14 # define        _KERNEL	1
15 #endif
16 #include <sys/errno.h>
17 #include <sys/types.h>
18 #include <sys/param.h>
19 #include <sys/time.h>
20 #if defined(__NetBSD__)
21 # if (NetBSD >= 199905) && !defined(IPFILTER_LKM) && defined(_KERNEL)
22 #  include "opt_ipfilter_log.h"
23 # endif
24 #endif
25 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
26     (__FreeBSD_version >= 220000)
27 # if (__FreeBSD_version >= 400000)
28 #  if !defined(IPFILTER_LKM)
29 #   include "opt_inet6.h"
30 #  endif
31 #  if (__FreeBSD_version == 400019)
32 #   define CSUM_DELAY_DATA
33 #  endif
34 # endif
35 # include <sys/filio.h>
36 #else
37 # include <sys/ioctl.h>
38 #endif
39 #if !defined(_AIX51)
40 # include <sys/fcntl.h>
41 #endif
42 #if defined(_KERNEL)
43 # include <sys/systm.h>
44 # include <sys/file.h>
45 #else
46 # include <stdio.h>
47 # include <string.h>
48 # include <stdlib.h>
49 # include <stddef.h>
50 # include <sys/file.h>
51 # define _KERNEL
52 # ifdef __OpenBSD__
53 struct file;
54 # endif
55 # include <sys/uio.h>
56 # undef _KERNEL
57 #endif
58 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
59     !defined(linux)
60 # include <sys/mbuf.h>
61 #else
62 # if !defined(linux)
63 #  include <sys/byteorder.h>
64 # endif
65 # if (SOLARIS2 < 5) && defined(sun)
66 #  include <sys/dditypes.h>
67 # endif
68 #endif
69 #ifdef __hpux
70 # define _NET_ROUTE_INCLUDED
71 #endif
72 #if !defined(linux)
73 # include <sys/protosw.h>
74 #endif
75 #include <sys/socket.h>
76 #include <net/if.h>
77 #ifdef sun
78 # include <net/af.h>
79 #endif
80 #if !defined(_KERNEL) && defined(__FreeBSD__)
81 # include "radix_ipf.h"
82 #endif
83 #include <net/route.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #if !defined(linux)
88 # include <netinet/ip_var.h>
89 #endif
90 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
91 # include <sys/hashing.h>
92 # include <netinet/in_var.h>
93 #endif
94 #include <netinet/tcp.h>
95 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
96 # include <netinet/udp.h>
97 # include <netinet/ip_icmp.h>
98 #endif
99 #ifdef __hpux
100 # undef _NET_ROUTE_INCLUDED
101 #endif
102 #include "netinet/ip_compat.h"
103 #ifdef	USE_INET6
104 # include <netinet/icmp6.h>
105 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
106 #  include <netinet6/in6_var.h>
107 # endif
108 #endif
109 #include <netinet/tcpip.h>
110 #include "netinet/ip_fil.h"
111 #include "netinet/ip_nat.h"
112 #include "netinet/ip_frag.h"
113 #include "netinet/ip_state.h"
114 #include "netinet/ip_proxy.h"
115 #include "netinet/ip_auth.h"
116 #include "netinet/ipf_stack.h"
117 #ifdef IPFILTER_SCAN
118 # include "netinet/ip_scan.h"
119 #endif
120 #ifdef IPFILTER_SYNC
121 # include "netinet/ip_sync.h"
122 #endif
123 #include "netinet/ip_pool.h"
124 #include "netinet/ip_htable.h"
125 #ifdef IPFILTER_COMPILED
126 # include "netinet/ip_rules.h"
127 #endif
128 #if defined(IPFILTER_BPF) && defined(_KERNEL)
129 # include <net/bpf.h>
130 #endif
131 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
132 # include <sys/malloc.h>
133 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
134 #  include "opt_ipfilter.h"
135 # endif
136 #endif
137 #include "netinet/ipl.h"
138 /* END OF INCLUDES */
139 
140 #if !defined(lint)
141 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
142 static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.64 2005/08/13 05:19:59 darrenr Exp $";
143 #endif
144 
145 #ifndef	_KERNEL
146 # include "ipf.h"
147 # include "ipt.h"
148 # include "bpf-ipf.h"
149 extern	int	opts;
150 
151 # define	FR_VERBOSE(verb_pr)			verbose verb_pr
152 # define	FR_DEBUG(verb_pr)			debug verb_pr
153 #else /* #ifndef _KERNEL */
154 # define	FR_VERBOSE(verb_pr)
155 # define	FR_DEBUG(verb_pr)
156 #endif /* _KERNEL */
157 
158 
159 char	ipfilter_version[] = IPL_VERSION;
160 int	fr_features = 0
161 #ifdef	IPFILTER_LKM
162 		| IPF_FEAT_LKM
163 #endif
164 #ifdef	IPFILTER_LOG
165 		| IPF_FEAT_LOG
166 #endif
167 #ifdef	IPFILTER_LOOKUP
168 		| IPF_FEAT_LOOKUP
169 #endif
170 #ifdef	IPFILTER_BPF
171 		| IPF_FEAT_BPF
172 #endif
173 #ifdef	IPFILTER_COMPILED
174 		| IPF_FEAT_COMPILED
175 #endif
176 #ifdef	IPFILTER_CKSUM
177 		| IPF_FEAT_CKSUM
178 #endif
179 #ifdef	IPFILTER_SYNC
180 		| IPF_FEAT_SYNC
181 #endif
182 #ifdef	IPFILTER_SCAN
183 		| IPF_FEAT_SCAN
184 #endif
185 #ifdef	USE_INET6
186 		| IPF_FEAT_IPV6
187 #endif
188 	;
189 
190 #define	IPF_BUMP(x)	(x)++
191 
192 static	INLINE int	fr_ipfcheck __P((fr_info_t *, frentry_t *, int));
193 static	INLINE int	fr_ipfcheck __P((fr_info_t *, frentry_t *, int));
194 static	int		fr_portcheck __P((frpcmp_t *, u_short *));
195 static	int		frflushlist __P((int, minor_t, int *, frentry_t **,
196 					 ipf_stack_t *));
197 static	ipfunc_t	fr_findfunc __P((ipfunc_t));
198 static	frentry_t	*fr_firewall __P((fr_info_t *, u_32_t *));
199 static	int		fr_funcinit __P((frentry_t *fr, ipf_stack_t *));
200 static	INLINE void	frpr_ah __P((fr_info_t *));
201 static	INLINE void	frpr_esp __P((fr_info_t *));
202 static	INLINE void	frpr_gre __P((fr_info_t *));
203 static	INLINE void	frpr_udp __P((fr_info_t *));
204 static	INLINE void	frpr_tcp __P((fr_info_t *));
205 static	INLINE void	frpr_icmp __P((fr_info_t *));
206 static	INLINE void	frpr_ipv4hdr __P((fr_info_t *));
207 static	INLINE int	frpr_pullup __P((fr_info_t *, int));
208 static	INLINE void	frpr_short __P((fr_info_t *, int));
209 static	INLINE void	frpr_tcpcommon __P((fr_info_t *));
210 static	INLINE void	frpr_udpcommon __P((fr_info_t *));
211 static	INLINE int	fr_updateipid __P((fr_info_t *));
212 #ifdef	IPFILTER_LOOKUP
213 static	int		fr_grpmapinit __P((frentry_t *fr, ipf_stack_t *));
214 static	INLINE void	*fr_resolvelookup __P((u_int, u_int, lookupfunc_t *,
215 					       ipf_stack_t *));
216 #endif
217 static	void		frsynclist __P((int, int, void *, char *, frentry_t *,
218     ipf_stack_t *));
219 static	void		*fr_ifsync __P((int, int, char *, char *,
220 					void *, void *, ipf_stack_t *));
221 static	ipftuneable_t	*fr_findtunebyname __P((const char *, ipf_stack_t *));
222 static	ipftuneable_t	*fr_findtunebycookie __P((void *, void **, ipf_stack_t *));
223 
224 
225 /*
226  * bit values for identifying presence of individual IP options
227  * All of these tables should be ordered by increasing key value on the left
228  * hand side to allow for binary searching of the array and include a trailer
229  * with a 0 for the bitmask for linear searches to easily find the end with.
230  */
231 const	struct	optlist	ipopts[20] = {
232 	{ IPOPT_NOP,	0x000001 },
233 	{ IPOPT_RR,	0x000002 },
234 	{ IPOPT_ZSU,	0x000004 },
235 	{ IPOPT_MTUP,	0x000008 },
236 	{ IPOPT_MTUR,	0x000010 },
237 	{ IPOPT_ENCODE,	0x000020 },
238 	{ IPOPT_TS,	0x000040 },
239 	{ IPOPT_TR,	0x000080 },
240 	{ IPOPT_SECURITY, 0x000100 },
241 	{ IPOPT_LSRR,	0x000200 },
242 	{ IPOPT_E_SEC,	0x000400 },
243 	{ IPOPT_CIPSO,	0x000800 },
244 	{ IPOPT_SATID,	0x001000 },
245 	{ IPOPT_SSRR,	0x002000 },
246 	{ IPOPT_ADDEXT,	0x004000 },
247 	{ IPOPT_VISA,	0x008000 },
248 	{ IPOPT_IMITD,	0x010000 },
249 	{ IPOPT_EIP,	0x020000 },
250 	{ IPOPT_FINN,	0x040000 },
251 	{ 0,		0x000000 }
252 };
253 
254 #ifdef USE_INET6
255 struct optlist ip6exthdr[] = {
256 	{ IPPROTO_HOPOPTS,		0x000001 },
257 	{ IPPROTO_IPV6,			0x000002 },
258 	{ IPPROTO_ROUTING,		0x000004 },
259 	{ IPPROTO_FRAGMENT,		0x000008 },
260 	{ IPPROTO_ESP,			0x000010 },
261 	{ IPPROTO_AH,			0x000020 },
262 	{ IPPROTO_NONE,			0x000040 },
263 	{ IPPROTO_DSTOPTS,		0x000080 },
264 	{ 0,				0 }
265 };
266 #endif
267 
268 struct optlist tcpopts[] = {
269 	{ TCPOPT_NOP,			0x000001 },
270 	{ TCPOPT_MAXSEG,		0x000002 },
271 	{ TCPOPT_WINDOW,		0x000004 },
272 	{ TCPOPT_SACK_PERMITTED,	0x000008 },
273 	{ TCPOPT_SACK,			0x000010 },
274 	{ TCPOPT_TIMESTAMP,		0x000020 },
275 	{ 0,				0x000000 }
276 };
277 
278 /*
279  * bit values for identifying presence of individual IP security options
280  */
281 const	struct	optlist	secopt[8] = {
282 	{ IPSO_CLASS_RES4,	0x01 },
283 	{ IPSO_CLASS_TOPS,	0x02 },
284 	{ IPSO_CLASS_SECR,	0x04 },
285 	{ IPSO_CLASS_RES3,	0x08 },
286 	{ IPSO_CLASS_CONF,	0x10 },
287 	{ IPSO_CLASS_UNCL,	0x20 },
288 	{ IPSO_CLASS_RES2,	0x40 },
289 	{ IPSO_CLASS_RES1,	0x80 }
290 };
291 
292 
293 /*
294  * Table of functions available for use with call rules.
295  */
296 static ipfunc_resolve_t fr_availfuncs[] = {
297 #ifdef	IPFILTER_LOOKUP
298 	{ "fr_srcgrpmap", fr_srcgrpmap, fr_grpmapinit },
299 	{ "fr_dstgrpmap", fr_dstgrpmap, fr_grpmapinit },
300 #endif
301 	{ "", NULL }
302 };
303 
304 
305 /*
306  * The next section of code is a a collection of small routines that set
307  * fields in the fr_info_t structure passed based on properties of the
308  * current packet.  There are different routines for the same protocol
309  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
310  * will "special" inspection for setup, is now more easily done by adding
311  * a new routine and expanding the frpr_ipinit*() function rather than by
312  * adding more code to a growing switch statement.
313  */
314 #ifdef USE_INET6
315 static	INLINE int	frpr_ah6 __P((fr_info_t *));
316 static	INLINE void	frpr_esp6 __P((fr_info_t *));
317 static	INLINE void	frpr_gre6 __P((fr_info_t *));
318 static	INLINE void	frpr_udp6 __P((fr_info_t *));
319 static	INLINE void	frpr_tcp6 __P((fr_info_t *));
320 static	INLINE void	frpr_icmp6 __P((fr_info_t *));
321 static	INLINE int	frpr_ipv6hdr __P((fr_info_t *));
322 static	INLINE void	frpr_short6 __P((fr_info_t *, int));
323 static	INLINE int	frpr_hopopts6 __P((fr_info_t *));
324 static	INLINE int	frpr_routing6 __P((fr_info_t *));
325 static	INLINE int	frpr_dstopts6 __P((fr_info_t *));
326 static	INLINE int	frpr_fragment6 __P((fr_info_t *));
327 static	INLINE int	frpr_ipv6exthdr __P((fr_info_t *, int, int));
328 
329 
330 /* ------------------------------------------------------------------------ */
331 /* Function:    frpr_short6                                                 */
332 /* Returns:     void                                                        */
333 /* Parameters:  fin(I) - pointer to packet information                      */
334 /*                                                                          */
335 /* IPv6 Only                                                                */
336 /* This is function enforces the 'is a packet too short to be legit' rule   */
337 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
338 /* for frpr_short() for more details.                                       */
339 /* ------------------------------------------------------------------------ */
340 static INLINE void frpr_short6(fin, xmin)
341 fr_info_t *fin;
342 int xmin;
343 {
344 
345 	if (fin->fin_dlen < xmin)
346 		fin->fin_flx |= FI_SHORT;
347 }
348 
349 
350 /* ------------------------------------------------------------------------ */
351 /* Function:    frpr_ipv6hdr                                                */
352 /* Returns:     int                                                         */
353 /* Parameters:  fin(I) - pointer to packet information                      */
354 /*                                                                          */
355 /* IPv6 Only                                                                */
356 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
357 /* per-protocol analyzer if it exists.                                      */
358 /* ------------------------------------------------------------------------ */
359 static INLINE int frpr_ipv6hdr(fin)
360 fr_info_t *fin;
361 {
362 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
363 	int p, go = 1, i, hdrcount;
364 	fr_ip_t *fi = &fin->fin_fi;
365 
366 	fin->fin_off = 0;
367 
368 	fi->fi_tos = 0;
369 	fi->fi_optmsk = 0;
370 	fi->fi_secmsk = 0;
371 	fi->fi_auth = 0;
372 
373 	p = ip6->ip6_nxt;
374 	fi->fi_ttl = ip6->ip6_hlim;
375 	fi->fi_src.in6 = ip6->ip6_src;
376 	fi->fi_dst.in6 = ip6->ip6_dst;
377 	fin->fin_id = 0;
378 
379 	hdrcount = 0;
380 	while (go && !(fin->fin_flx & (FI_BAD|FI_SHORT))) {
381 		switch (p)
382 		{
383 		case IPPROTO_UDP :
384 			frpr_udp6(fin);
385 			go = 0;
386 			break;
387 
388 		case IPPROTO_TCP :
389 			frpr_tcp6(fin);
390 			go = 0;
391 			break;
392 
393 		case IPPROTO_ICMPV6 :
394 			frpr_icmp6(fin);
395 			go = 0;
396 			break;
397 
398 		case IPPROTO_GRE :
399 			frpr_gre6(fin);
400 			go = 0;
401 			break;
402 
403 		case IPPROTO_HOPOPTS :
404 			/*
405 			 * hop by hop ext header is only allowed
406 			 * right after IPv6 header.
407 			 */
408 			if (hdrcount != 0) {
409 				fin->fin_flx |= FI_BAD;
410 				p = IPPROTO_NONE;
411 			} else {
412 				p = frpr_hopopts6(fin);
413 			}
414 			break;
415 
416 		case IPPROTO_DSTOPTS :
417 			p = frpr_dstopts6(fin);
418 			break;
419 
420 		case IPPROTO_ROUTING :
421 			p = frpr_routing6(fin);
422 			break;
423 
424 		case IPPROTO_AH :
425 			p = frpr_ah6(fin);
426 			break;
427 
428 		case IPPROTO_ESP :
429 			frpr_esp6(fin);
430 			go = 0;
431 			break;
432 
433 		case IPPROTO_IPV6 :
434 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
435 				if (ip6exthdr[i].ol_val == p) {
436 					fin->fin_flx |= ip6exthdr[i].ol_bit;
437 					break;
438 				}
439 			go = 0;
440 			break;
441 
442 		case IPPROTO_NONE :
443 			go = 0;
444 			break;
445 
446 		case IPPROTO_FRAGMENT :
447 			p = frpr_fragment6(fin);
448 			if (fin->fin_off != 0)  /* Not the first frag */
449 				go = 0;
450 			break;
451 
452 		default :
453 			go = 0;
454 			break;
455 		}
456 		hdrcount++;
457 
458 		/*
459 		 * It is important to note that at this point, for the
460 		 * extension headers (go != 0), the entire header may not have
461 		 * been pulled up when the code gets to this point.  This is
462 		 * only done for "go != 0" because the other header handlers
463 		 * will all pullup their complete header.  The other indicator
464 		 * of an incomplete packet is that this was just an extension
465 		 * header.
466 		 */
467 		if ((go != 0) && (p != IPPROTO_NONE) &&
468 		    (frpr_pullup(fin, 0) == -1)) {
469 			p = IPPROTO_NONE;
470 			go = 0;
471 		}
472 	}
473 	fi->fi_p = p;
474 
475 	if (fin->fin_flx & FI_BAD)
476 		return -1;
477 
478 	return 0;
479 }
480 
481 
482 /* ------------------------------------------------------------------------ */
483 /* Function:    frpr_ipv6exthdr                                             */
484 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
485 /* Parameters:  fin(I)      - pointer to packet information                 */
486 /*              multiple(I) - flag indicating yes/no if multiple occurances */
487 /*                            of this extension header are allowed.         */
488 /*              proto(I)    - protocol number for this extension header     */
489 /*                                                                          */
490 /* IPv6 Only                                                                */
491 /* ------------------------------------------------------------------------ */
492 static INLINE int frpr_ipv6exthdr(fin, multiple, proto)
493 fr_info_t *fin;
494 int multiple, proto;
495 {
496 	struct ip6_ext *hdr;
497 	u_short shift;
498 	int i;
499 
500 	fin->fin_flx |= FI_V6EXTHDR;
501 
502 				/* 8 is default length of extension hdr */
503 	if ((fin->fin_dlen - 8) < 0) {
504 		fin->fin_flx |= FI_SHORT;
505 		return IPPROTO_NONE;
506 	}
507 
508 	if (frpr_pullup(fin, 8) == -1)
509 		return IPPROTO_NONE;
510 
511 	hdr = fin->fin_dp;
512 	shift = 8 + (hdr->ip6e_len << 3);
513 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
514 		fin->fin_flx |= FI_BAD;
515 		return IPPROTO_NONE;
516 	}
517 
518 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
519 		if (ip6exthdr[i].ol_val == proto) {
520 			/*
521 			 * Most IPv6 extension headers are only allowed once.
522 			 */
523 			if ((multiple == 0) &&
524 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
525 				fin->fin_flx |= FI_BAD;
526 			else
527 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
528 			break;
529 		}
530 
531 	fin->fin_dp = (char *)fin->fin_dp + shift;
532 	fin->fin_dlen -= shift;
533 
534 	return hdr->ip6e_nxt;
535 }
536 
537 
538 /* ------------------------------------------------------------------------ */
539 /* Function:    frpr_hopopts6                                               */
540 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
541 /* Parameters:  fin(I) - pointer to packet information                      */
542 /*                                                                          */
543 /* IPv6 Only                                                                */
544 /* This is function checks pending hop by hop options extension header      */
545 /* ------------------------------------------------------------------------ */
546 static INLINE int frpr_hopopts6(fin)
547 fr_info_t *fin;
548 {
549 	return frpr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
550 }
551 
552 
553 /* ------------------------------------------------------------------------ */
554 /* Function:    frpr_routing6                                               */
555 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
556 /* Parameters:  fin(I) - pointer to packet information                      */
557 /*                                                                          */
558 /* IPv6 Only                                                                */
559 /* This is function checks pending routing extension header                 */
560 /* ------------------------------------------------------------------------ */
561 static INLINE int frpr_routing6(fin)
562 fr_info_t *fin;
563 {
564 	struct ip6_ext *hdr;
565 	int shift;
566 
567 	hdr = fin->fin_dp;
568 	if (frpr_ipv6exthdr(fin, 0, IPPROTO_ROUTING) == IPPROTO_NONE)
569 		return IPPROTO_NONE;
570 
571 	shift = 8 + (hdr->ip6e_len << 3);
572 	/*
573 	 * Nasty extension header length?
574 	 */
575 	if ((hdr->ip6e_len << 3) & 15) {
576 		fin->fin_flx |= FI_BAD;
577 		/*
578 		 * Compensate for the changes made in frpr_ipv6exthdr()
579 		 */
580 		fin->fin_dlen += shift;
581 		fin->fin_dp = (char *)fin->fin_dp - shift;
582 		return IPPROTO_NONE;
583 	}
584 
585 	return hdr->ip6e_nxt;
586 }
587 
588 
589 /* ------------------------------------------------------------------------ */
590 /* Function:    frpr_fragment6                                              */
591 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
592 /* Parameters:  fin(I) - pointer to packet information                      */
593 /*                                                                          */
594 /* IPv6 Only                                                                */
595 /* Examine the IPv6 fragment header and extract fragment offset information.*/
596 /*                                                                          */
597 /* We don't know where the transport layer header (or whatever is next is), */
598 /* as it could be behind destination options (amongst others).  Because     */
599 /* there is no fragment cache, there is no knowledge about whether or not an*/
600 /* upper layer header has been seen (or where it ends) and thus we are not  */
601 /* able to continue processing beyond this header with any confidence.      */
602 /* ------------------------------------------------------------------------ */
603 static INLINE int frpr_fragment6(fin)
604 fr_info_t *fin;
605 {
606 	struct ip6_frag *frag;
607 	int dlen;
608 
609 	fin->fin_flx |= FI_FRAG;
610 
611 	dlen = fin->fin_dlen;
612 	if (frpr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT) == IPPROTO_NONE)
613 		return IPPROTO_NONE;
614 
615 	if (frpr_pullup(fin, sizeof(*frag)) == -1)
616 		return IPPROTO_NONE;
617 
618 	frpr_short6(fin, sizeof(*frag));
619 
620 	if ((fin->fin_flx & FI_SHORT) != 0)
621 		return IPPROTO_NONE;
622 
623 	frag = (struct ip6_frag *)((char *)fin->fin_dp - sizeof(*frag));
624 	/*
625 	 * Fragment but no fragmentation info set?  Bad packet...
626 	 */
627 	if (frag->ip6f_offlg == 0) {
628 		fin->fin_flx |= FI_BAD;
629 		return IPPROTO_NONE;
630 	}
631 
632 	fin->fin_id = frag->ip6f_ident;
633 	fin->fin_off = frag->ip6f_offlg & IP6F_OFF_MASK;
634 	fin->fin_off = ntohs(fin->fin_off);
635 	if (fin->fin_off != 0)
636 		fin->fin_flx |= FI_FRAGBODY;
637 
638 	fin->fin_dp = (char *)frag + sizeof(*frag);
639 	fin->fin_dlen = dlen - sizeof(*frag);
640 
641 	/* length of hdrs(after frag hdr) + data */
642 	fin->fin_flen = fin->fin_dlen;
643 
644 	/*
645 	 * If the frag is not the last one and the payload length
646 	 * is not multiple of 8, it must be dropped.
647 	 */
648 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) && (dlen % 8)) {
649 		fin->fin_flx |= FI_BAD;
650 		return IPPROTO_NONE;
651 	}
652 
653 	return frag->ip6f_nxt;
654 }
655 
656 
657 /* ------------------------------------------------------------------------ */
658 /* Function:    frpr_dstopts6                                               */
659 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
660 /* Parameters:  fin(I) - pointer to packet information                      */
661 /*              nextheader(I) - stores next header value                    */
662 /*                                                                          */
663 /* IPv6 Only                                                                */
664 /* This is function checks pending destination options extension header     */
665 /* ------------------------------------------------------------------------ */
666 static INLINE int frpr_dstopts6(fin)
667 fr_info_t *fin;
668 {
669 	return frpr_ipv6exthdr(fin, 1, IPPROTO_DSTOPTS);
670 }
671 
672 
673 /* ------------------------------------------------------------------------ */
674 /* Function:    frpr_icmp6                                                  */
675 /* Returns:     void                                                        */
676 /* Parameters:  fin(I) - pointer to packet information                      */
677 /*                                                                          */
678 /* IPv6 Only                                                                */
679 /* This routine is mainly concerned with determining the minimum valid size */
680 /* for an ICMPv6 packet.                                                    */
681 /* ------------------------------------------------------------------------ */
682 static INLINE void frpr_icmp6(fin)
683 fr_info_t *fin;
684 {
685 	int minicmpsz = sizeof(struct icmp6_hdr);
686 	struct icmp6_hdr *icmp6;
687 
688 	if (frpr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1)
689 		return;
690 
691 	if (fin->fin_dlen > 1) {
692 		icmp6 = fin->fin_dp;
693 
694 		fin->fin_data[0] = *(u_short *)icmp6;
695 
696 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
697 			fin->fin_flx |= FI_ICMPQUERY;
698 
699 		switch (icmp6->icmp6_type)
700 		{
701 		case ICMP6_ECHO_REPLY :
702 		case ICMP6_ECHO_REQUEST :
703 			if (fin->fin_dlen >= 6)
704 				fin->fin_data[1] = icmp6->icmp6_id;
705 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
706 			break;
707 		case ICMP6_DST_UNREACH :
708 		case ICMP6_PACKET_TOO_BIG :
709 		case ICMP6_TIME_EXCEEDED :
710 		case ICMP6_PARAM_PROB :
711 			if ((fin->fin_m != NULL) &&
712 			    (M_LEN(fin->fin_m) < fin->fin_plen)) {
713 				if (fr_coalesce(fin) != 1)
714 					return;
715 			}
716 			fin->fin_flx |= FI_ICMPERR;
717 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
718 			break;
719 		default :
720 			break;
721 		}
722 	}
723 
724 	frpr_short6(fin, minicmpsz);
725 	fin->fin_flen -= fin->fin_dlen - minicmpsz;
726 }
727 
728 
729 /* ------------------------------------------------------------------------ */
730 /* Function:    frpr_udp6                                                   */
731 /* Returns:     void                                                        */
732 /* Parameters:  fin(I) - pointer to packet information                      */
733 /*                                                                          */
734 /* IPv6 Only                                                                */
735 /* Analyse the packet for IPv6/UDP properties.                              */
736 /* Is not expected to be called for fragmented packets.                     */
737 /* ------------------------------------------------------------------------ */
738 static INLINE void frpr_udp6(fin)
739 fr_info_t *fin;
740 {
741 
742 	fr_checkv6sum(fin);
743 
744 	frpr_short6(fin, sizeof(struct udphdr));
745 	if (frpr_pullup(fin, sizeof(struct udphdr)) == -1)
746 		return;
747 
748 	fin->fin_flen -= fin->fin_dlen - sizeof(struct udphdr);
749 
750 	frpr_udpcommon(fin);
751 }
752 
753 
754 /* ------------------------------------------------------------------------ */
755 /* Function:    frpr_tcp6                                                   */
756 /* Returns:     void                                                        */
757 /* Parameters:  fin(I) - pointer to packet information                      */
758 /*                                                                          */
759 /* IPv6 Only                                                                */
760 /* Analyse the packet for IPv6/TCP properties.                              */
761 /* Is not expected to be called for fragmented packets.                     */
762 /* ------------------------------------------------------------------------ */
763 static INLINE void frpr_tcp6(fin)
764 fr_info_t *fin;
765 {
766 
767 	fr_checkv6sum(fin);
768 
769 	frpr_short6(fin, sizeof(struct tcphdr));
770 	if (frpr_pullup(fin, sizeof(struct tcphdr)) == -1)
771 		return;
772 
773 	fin->fin_flen -= fin->fin_dlen - sizeof(struct tcphdr);
774 
775 	frpr_tcpcommon(fin);
776 }
777 
778 
779 /* ------------------------------------------------------------------------ */
780 /* Function:    frpr_esp6                                                   */
781 /* Returns:     void                                                        */
782 /* Parameters:  fin(I) - pointer to packet information                      */
783 /*                                                                          */
784 /* IPv6 Only                                                                */
785 /* Analyse the packet for ESP properties.                                   */
786 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
787 /* even though the newer ESP packets must also have a sequence number that  */
788 /* is 32bits as well, it is not possible(?) to determine the version from a */
789 /* simple packet header.                                                    */
790 /* ------------------------------------------------------------------------ */
791 static INLINE void frpr_esp6(fin)
792 fr_info_t *fin;
793 {
794 	int i;
795 	frpr_short6(fin, sizeof(grehdr_t));
796 
797 	(void) frpr_pullup(fin, 8);
798 
799 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
800 		if (ip6exthdr[i].ol_val == IPPROTO_ESP) {
801 			fin->fin_optmsk |= ip6exthdr[i].ol_bit;
802 			break;
803 		}
804 }
805 
806 
807 /* ------------------------------------------------------------------------ */
808 /* Function:    frpr_ah6                                                    */
809 /* Returns:     void                                                        */
810 /* Parameters:  fin(I) - pointer to packet information                      */
811 /*                                                                          */
812 /* IPv6 Only                                                                */
813 /* Analyse the packet for AH properties.                                    */
814 /* The minimum length is taken to be the combination of all fields in the   */
815 /* header being present and no authentication data (null algorithm used.)   */
816 /* ------------------------------------------------------------------------ */
817 static INLINE int frpr_ah6(fin)
818 fr_info_t *fin;
819 {
820 	authhdr_t *ah;
821 	int i, shift;
822 
823 	frpr_short6(fin, 12);
824 
825 	if (frpr_pullup(fin, sizeof(*ah)) == -1)
826 		return IPPROTO_NONE;
827 
828 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
829 		if (ip6exthdr[i].ol_val == IPPROTO_AH) {
830 			fin->fin_optmsk |= ip6exthdr[i].ol_bit;
831 			break;
832 		}
833 
834 	ah = (authhdr_t *)fin->fin_dp;
835 
836 	shift = (ah->ah_plen + 2) * 4;
837 	fin->fin_dlen -= shift;
838 	fin->fin_dp = (char*)fin->fin_dp + shift;
839 
840 	return ah->ah_next;
841 }
842 
843 
844 /* ------------------------------------------------------------------------ */
845 /* Function:    frpr_gre6                                                   */
846 /* Returns:     void                                                        */
847 /* Parameters:  fin(I) - pointer to packet information                      */
848 /*                                                                          */
849 /* Analyse the packet for GRE properties.                                   */
850 /* ------------------------------------------------------------------------ */
851 static INLINE void frpr_gre6(fin)
852 fr_info_t *fin;
853 {
854 	grehdr_t *gre;
855 
856 	frpr_short6(fin, sizeof(grehdr_t));
857 
858 	if (frpr_pullup(fin, sizeof(grehdr_t)) == -1)
859 		return;
860 
861 	gre = fin->fin_dp;
862 	if (GRE_REV(gre->gr_flags) == 1)
863 		fin->fin_data[0] = gre->gr_call;
864 }
865 #endif	/* USE_INET6 */
866 
867 
868 /* ------------------------------------------------------------------------ */
869 /* Function:    frpr_pullup                                                 */
870 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
871 /* Parameters:  fin(I)  - pointer to packet information                     */
872 /*              plen(I) - length (excluding L3 header) to pullup            */
873 /*                                                                          */
874 /* Short inline function to cut down on code duplication to perform a call  */
875 /* to fr_pullup to ensure there is the required amount of data,             */
876 /* consecutively in the packet buffer.                                      */
877 /* ------------------------------------------------------------------------ */
878 static INLINE int frpr_pullup(fin, plen)
879 fr_info_t *fin;
880 int plen;
881 {
882 #if defined(_KERNEL)
883 	if (fin->fin_m != NULL) {
884 		int ipoff;
885 
886 		ipoff = (char *)fin->fin_ip - MTOD(fin->fin_m, char *);
887 
888 		if (fin->fin_dp != NULL)
889 			plen += (char *)fin->fin_dp -
890 				((char *)fin->fin_ip + fin->fin_hlen);
891 		plen += fin->fin_hlen;
892 		/*
893 		 * We don't do 'plen += ipoff;' here. The fr_pullup() will
894 		 * do it for us.
895 		 */
896 		if (M_LEN(fin->fin_m) < plen + ipoff) {
897 			if (fr_pullup(fin->fin_m, fin, plen) == NULL)
898 				return -1;
899 		}
900 	}
901 #endif
902 	return 0;
903 }
904 
905 
906 /* ------------------------------------------------------------------------ */
907 /* Function:    frpr_short                                                  */
908 /* Returns:     void                                                        */
909 /* Parameters:  fin(I)  - pointer to packet information                     */
910 /*              xmin(I) - minimum header size                               */
911 /*                                                                          */
912 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
913 /* applying here is that the packet must not be fragmented within the layer */
914 /* 4 header.  That is, it must not be a fragment that has its offset set to */
915 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
916 /* entire layer 4 header must be present (min).                             */
917 /* ------------------------------------------------------------------------ */
918 static INLINE void frpr_short(fin, xmin)
919 fr_info_t *fin;
920 int xmin;
921 {
922 
923 	if (fin->fin_off == 0) {
924 		if (fin->fin_dlen < xmin)
925 			fin->fin_flx |= FI_SHORT;
926 	} else if (fin->fin_off < xmin) {
927 		fin->fin_flx |= FI_SHORT;
928 	}
929 }
930 
931 
932 /* ------------------------------------------------------------------------ */
933 /* Function:    frpr_icmp                                                   */
934 /* Returns:     void                                                        */
935 /* Parameters:  fin(I) - pointer to packet information                      */
936 /*                                                                          */
937 /* IPv4 Only                                                                */
938 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
939 /* except extrememly bad packets, both type and code will be present.       */
940 /* The expected minimum size of an ICMP packet is very much dependent on    */
941 /* the type of it.                                                          */
942 /*                                                                          */
943 /* XXX - other ICMP sanity checks?                                          */
944 /* ------------------------------------------------------------------------ */
945 static INLINE void frpr_icmp(fin)
946 fr_info_t *fin;
947 {
948 	int minicmpsz = sizeof(struct icmp);
949 	icmphdr_t *icmp;
950 	ip_t *oip;
951 	ipf_stack_t *ifs = fin->fin_ifs;
952 
953 	if (fin->fin_off != 0) {
954 		frpr_short(fin, ICMPERR_ICMPHLEN);
955 		return;
956 	}
957 
958 	if (frpr_pullup(fin, ICMPERR_ICMPHLEN) == -1)
959 		return;
960 
961 	fr_checkv4sum(fin);
962 
963 	if (fin->fin_dlen > 1) {
964 		icmp = fin->fin_dp;
965 
966 		fin->fin_data[0] = *(u_short *)icmp;
967 
968 		switch (icmp->icmp_type)
969 		{
970 		case ICMP_ECHOREPLY :
971 		case ICMP_ECHO :
972 		/* Router discovery messaes - RFC 1256 */
973 		case ICMP_ROUTERADVERT :
974 		case ICMP_ROUTERSOLICIT :
975 			minicmpsz = ICMP_MINLEN;
976 			break;
977 		/*
978 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
979 		 * 3 * timestamp(3 * 4)
980 		 */
981 		case ICMP_TSTAMP :
982 		case ICMP_TSTAMPREPLY :
983 			minicmpsz = 20;
984 			break;
985 		/*
986 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
987 		 * mask(4)
988 		 */
989 		case ICMP_MASKREQ :
990 		case ICMP_MASKREPLY :
991 			minicmpsz = 12;
992 			break;
993 		/*
994 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
995 		 */
996 		case ICMP_UNREACH :
997 			if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
998 				if (icmp->icmp_nextmtu < ifs->ifs_fr_icmpminfragmtu)
999 					fin->fin_flx |= FI_BAD;
1000 			}
1001 			/* FALLTHRU */
1002 		case ICMP_SOURCEQUENCH :
1003 		case ICMP_REDIRECT :
1004 		case ICMP_TIMXCEED :
1005 		case ICMP_PARAMPROB :
1006 			fin->fin_flx |= FI_ICMPERR;
1007 			if (fr_coalesce(fin) != 1)
1008 				return;
1009 			/*
1010 			 * ICMP error packets should not be generated for IP
1011 			 * packets that are a fragment that isn't the first
1012 			 * fragment.
1013 			 */
1014 			oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1015 			if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1016 				fin->fin_flx |= FI_BAD;
1017 			break;
1018 		default :
1019 			break;
1020 		}
1021 
1022 		if (fin->fin_dlen >= 6)				/* ID field */
1023 			fin->fin_data[1] = icmp->icmp_id;
1024 	}
1025 
1026 	frpr_short(fin, minicmpsz);
1027 }
1028 
1029 
1030 /* ------------------------------------------------------------------------ */
1031 /* Function:    frpr_tcpcommon                                              */
1032 /* Returns:     void                                                        */
1033 /* Parameters:  fin(I) - pointer to packet information                      */
1034 /*                                                                          */
1035 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1036 /* and make some checks with how they interact with other fields.           */
1037 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1038 /* valid and mark the packet as bad if not.                                 */
1039 /* ------------------------------------------------------------------------ */
1040 static INLINE void frpr_tcpcommon(fin)
1041 fr_info_t *fin;
1042 {
1043 	int flags, tlen;
1044 	tcphdr_t *tcp;
1045 
1046 	fin->fin_flx |= FI_TCPUDP;
1047 	if (fin->fin_off != 0)
1048 		return;
1049 
1050 	if (frpr_pullup(fin, sizeof(*tcp)) == -1)
1051 		return;
1052 	tcp = fin->fin_dp;
1053 
1054 	if (fin->fin_dlen > 3) {
1055 		fin->fin_sport = ntohs(tcp->th_sport);
1056 		fin->fin_dport = ntohs(tcp->th_dport);
1057 	}
1058 
1059 	if ((fin->fin_flx & FI_SHORT) != 0)
1060 		return;
1061 
1062 	/*
1063 	 * Use of the TCP data offset *must* result in a value that is at
1064 	 * least the same size as the TCP header.
1065 	 */
1066 	tlen = TCP_OFF(tcp) << 2;
1067 	if (tlen < sizeof(tcphdr_t)) {
1068 		fin->fin_flx |= FI_BAD;
1069 		return;
1070 	}
1071 
1072 	flags = tcp->th_flags;
1073 	fin->fin_tcpf = tcp->th_flags;
1074 
1075 	/*
1076 	 * If the urgent flag is set, then the urgent pointer must
1077 	 * also be set and vice versa.  Good TCP packets do not have
1078 	 * just one of these set.
1079 	 */
1080 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1081 		fin->fin_flx |= FI_BAD;
1082 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1083 		/* Ignore this case, it shows up in "real" traffic with */
1084 		/* bogus values in the urgent pointer field. */
1085 		flags = flags; /* LINT */
1086 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1087 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1088 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1089 		fin->fin_flx |= FI_BAD;
1090 	} else if (!(flags & TH_ACK)) {
1091 		/*
1092 		 * If the ack bit isn't set, then either the SYN or
1093 		 * RST bit must be set.  If the SYN bit is set, then
1094 		 * we expect the ACK field to be 0.  If the ACK is
1095 		 * not set and if URG, PSH or FIN are set, consdier
1096 		 * that to indicate a bad TCP packet.
1097 		 */
1098 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1099 			/*
1100 			 * Cisco PIX sets the ACK field to a random value.
1101 			 * In light of this, do not set FI_BAD until a patch
1102 			 * is available from Cisco to ensure that
1103 			 * interoperability between existing systems is
1104 			 * achieved.
1105 			 */
1106 			/*fin->fin_flx |= FI_BAD*/;
1107 			flags = flags; /* LINT */
1108 		} else if (!(flags & (TH_RST|TH_SYN))) {
1109 			fin->fin_flx |= FI_BAD;
1110 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1111 			fin->fin_flx |= FI_BAD;
1112 		}
1113 	}
1114 
1115 	/*
1116 	 * At this point, it's not exactly clear what is to be gained by
1117 	 * marking up which TCP options are and are not present.  The one we
1118 	 * are most interested in is the TCP window scale.  This is only in
1119 	 * a SYN packet [RFC1323] so we don't need this here...?
1120 	 * Now if we were to analyse the header for passive fingerprinting,
1121 	 * then that might add some weight to adding this...
1122 	 */
1123 	if (tlen == sizeof(tcphdr_t))
1124 		return;
1125 
1126 	if (frpr_pullup(fin, tlen) == -1)
1127 		return;
1128 
1129 #if 0
1130 	ip = fin->fin_ip;
1131 	s = (u_char *)(tcp + 1);
1132 	off = IP_HL(ip) << 2;
1133 # ifdef _KERNEL
1134 	if (fin->fin_mp != NULL) {
1135 		mb_t *m = *fin->fin_mp;
1136 
1137 		if (off + tlen > M_LEN(m))
1138 			return;
1139 	}
1140 # endif
1141 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1142 		opt = *s;
1143 		if (opt == '\0')
1144 			break;
1145 		else if (opt == TCPOPT_NOP)
1146 			ol = 1;
1147 		else {
1148 			if (tlen < 2)
1149 				break;
1150 			ol = (int)*(s + 1);
1151 			if (ol < 2 || ol > tlen)
1152 				break;
1153 		}
1154 
1155 		for (i = 9, mv = 4; mv >= 0; ) {
1156 			op = ipopts + i;
1157 			if (opt == (u_char)op->ol_val) {
1158 				optmsk |= op->ol_bit;
1159 				break;
1160 			}
1161 		}
1162 		tlen -= ol;
1163 		s += ol;
1164 	}
1165 #endif /* 0 */
1166 }
1167 
1168 
1169 
1170 /* ------------------------------------------------------------------------ */
1171 /* Function:    frpr_udpcommon                                              */
1172 /* Returns:     void                                                        */
1173 /* Parameters:  fin(I) - pointer to packet information                      */
1174 /*                                                                          */
1175 /* Extract the UDP source and destination ports, if present.  If compiled   */
1176 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1177 /* ------------------------------------------------------------------------ */
1178 static INLINE void frpr_udpcommon(fin)
1179 fr_info_t *fin;
1180 {
1181 	udphdr_t *udp;
1182 
1183 	fin->fin_flx |= FI_TCPUDP;
1184 
1185 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1186 		if (frpr_pullup(fin, sizeof(*udp)) == -1) {
1187 			fin->fin_flx |= FI_SHORT;
1188 			return;
1189 		}
1190 
1191 		udp = fin->fin_dp;
1192 
1193 		fin->fin_sport = ntohs(udp->uh_sport);
1194 		fin->fin_dport = ntohs(udp->uh_dport);
1195 	}
1196 }
1197 
1198 
1199 /* ------------------------------------------------------------------------ */
1200 /* Function:    frpr_tcp                                                    */
1201 /* Returns:     void                                                        */
1202 /* Parameters:  fin(I) - pointer to packet information                      */
1203 /*                                                                          */
1204 /* IPv4 Only                                                                */
1205 /* Analyse the packet for IPv4/TCP properties.                              */
1206 /* ------------------------------------------------------------------------ */
1207 static INLINE void frpr_tcp(fin)
1208 fr_info_t *fin;
1209 {
1210 
1211 	fr_checkv4sum(fin);
1212 
1213 	frpr_short(fin, sizeof(tcphdr_t));
1214 
1215 	frpr_tcpcommon(fin);
1216 }
1217 
1218 
1219 /* ------------------------------------------------------------------------ */
1220 /* Function:    frpr_udp                                                    */
1221 /* Returns:     void                                                        */
1222 /* Parameters:  fin(I) - pointer to packet information                      */
1223 /*                                                                          */
1224 /* IPv4 Only                                                                */
1225 /* Analyse the packet for IPv4/UDP properties.                              */
1226 /* ------------------------------------------------------------------------ */
1227 static INLINE void frpr_udp(fin)
1228 fr_info_t *fin;
1229 {
1230 
1231 	fr_checkv4sum(fin);
1232 
1233 	frpr_short(fin, sizeof(udphdr_t));
1234 
1235 	frpr_udpcommon(fin);
1236 }
1237 
1238 
1239 /* ------------------------------------------------------------------------ */
1240 /* Function:    frpr_esp                                                    */
1241 /* Returns:     void                                                        */
1242 /* Parameters:  fin(I) - pointer to packet information                      */
1243 /*                                                                          */
1244 /* Analyse the packet for ESP properties.                                   */
1245 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1246 /* even though the newer ESP packets must also have a sequence number that  */
1247 /* is 32bits as well, it is not possible(?) to determine the version from a */
1248 /* simple packet header.                                                    */
1249 /* ------------------------------------------------------------------------ */
1250 static INLINE void frpr_esp(fin)
1251 fr_info_t *fin;
1252 {
1253 	if ((fin->fin_off == 0) && (frpr_pullup(fin, 8) == -1))
1254 		return;
1255 
1256 	frpr_short(fin, 8);
1257 }
1258 
1259 
1260 /* ------------------------------------------------------------------------ */
1261 /* Function:    frpr_ah                                                     */
1262 /* Returns:     void                                                        */
1263 /* Parameters:  fin(I) - pointer to packet information                      */
1264 /*                                                                          */
1265 /* Analyse the packet for AH properties.                                    */
1266 /* The minimum length is taken to be the combination of all fields in the   */
1267 /* header being present and no authentication data (null algorithm used.)   */
1268 /* ------------------------------------------------------------------------ */
1269 static INLINE void frpr_ah(fin)
1270 fr_info_t *fin;
1271 {
1272 	authhdr_t *ah;
1273 	int len;
1274 
1275 	if ((fin->fin_off == 0) && (frpr_pullup(fin, sizeof(*ah)) == -1))
1276 		return;
1277 
1278 	ah = (authhdr_t *)fin->fin_dp;
1279 
1280 	len = (ah->ah_plen + 2) << 2;
1281 	frpr_short(fin, len);
1282 }
1283 
1284 
1285 /* ------------------------------------------------------------------------ */
1286 /* Function:    frpr_gre                                                    */
1287 /* Returns:     void                                                        */
1288 /* Parameters:  fin(I) - pointer to packet information                      */
1289 /*                                                                          */
1290 /* Analyse the packet for GRE properties.                                   */
1291 /* ------------------------------------------------------------------------ */
1292 static INLINE void frpr_gre(fin)
1293 fr_info_t *fin;
1294 {
1295 	grehdr_t *gre;
1296 
1297 	if ((fin->fin_off == 0) && (frpr_pullup(fin, sizeof(grehdr_t)) == -1))
1298 		return;
1299 
1300 	frpr_short(fin, sizeof(grehdr_t));
1301 
1302 	if (fin->fin_off == 0) {
1303 		gre = fin->fin_dp;
1304 		if (GRE_REV(gre->gr_flags) == 1)
1305 			fin->fin_data[0] = gre->gr_call;
1306 	}
1307 }
1308 
1309 
1310 /* ------------------------------------------------------------------------ */
1311 /* Function:    frpr_ipv4hdr                                                */
1312 /* Returns:     void                                                        */
1313 /* Parameters:  fin(I) - pointer to packet information                      */
1314 /*                                                                          */
1315 /* IPv4 Only                                                                */
1316 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1317 /* Check all options present and flag their presence if any exist.          */
1318 /* ------------------------------------------------------------------------ */
1319 static INLINE void frpr_ipv4hdr(fin)
1320 fr_info_t *fin;
1321 {
1322 	u_short optmsk = 0, secmsk = 0, auth = 0;
1323 	int hlen, ol, mv, p, i;
1324 	const struct optlist *op;
1325 	u_char *s, opt;
1326 	u_short off;
1327 	fr_ip_t *fi;
1328 	ip_t *ip;
1329 
1330 	fi = &fin->fin_fi;
1331 	hlen = fin->fin_hlen;
1332 
1333 	ip = fin->fin_ip;
1334 	p = ip->ip_p;
1335 	fi->fi_p = p;
1336 	fi->fi_tos = ip->ip_tos;
1337 	fin->fin_id = ip->ip_id;
1338 	off = ip->ip_off;
1339 
1340 	/* Get both TTL and protocol */
1341 	fi->fi_p = ip->ip_p;
1342 	fi->fi_ttl = ip->ip_ttl;
1343 #if 0
1344 	(*(((u_short *)fi) + 1)) = (*(((u_short *)ip) + 4));
1345 #endif
1346 
1347 	/* Zero out bits not used in IPv6 address */
1348 	fi->fi_src.i6[1] = 0;
1349 	fi->fi_src.i6[2] = 0;
1350 	fi->fi_src.i6[3] = 0;
1351 	fi->fi_dst.i6[1] = 0;
1352 	fi->fi_dst.i6[2] = 0;
1353 	fi->fi_dst.i6[3] = 0;
1354 
1355 	fi->fi_saddr = ip->ip_src.s_addr;
1356 	fi->fi_daddr = ip->ip_dst.s_addr;
1357 
1358 	/*
1359 	 * set packet attribute flags based on the offset and
1360 	 * calculate the byte offset that it represents.
1361 	 */
1362 	off &= IP_MF|IP_OFFMASK;
1363 	if (off != 0) {
1364 		fi->fi_flx |= FI_FRAG;
1365 		off &= IP_OFFMASK;
1366 		if (off != 0) {
1367 			fin->fin_flx |= FI_FRAGBODY;
1368 			off <<= 3;
1369 			if ((off + fin->fin_dlen > 65535) ||
1370 			    (fin->fin_dlen == 0) ||
1371 			    ((ip->ip_off & IP_MF) && (fin->fin_dlen & 7))) {
1372 				/*
1373 				 * The length of the packet, starting at its
1374 				 * offset cannot exceed 65535 (0xffff) as the
1375 				 * length of an IP packet is only 16 bits.
1376 				 *
1377 				 * Any fragment that isn't the last fragment
1378 				 * must have a length greater than 0 and it
1379 				 * must be an even multiple of 8.
1380 				 */
1381 				fi->fi_flx |= FI_BAD;
1382 			}
1383 		}
1384 	}
1385 	fin->fin_off = off;
1386 
1387 	/*
1388 	 * Call per-protocol setup and checking
1389 	 */
1390 	switch (p)
1391 	{
1392 	case IPPROTO_UDP :
1393 		frpr_udp(fin);
1394 		break;
1395 	case IPPROTO_TCP :
1396 		frpr_tcp(fin);
1397 		break;
1398 	case IPPROTO_ICMP :
1399 		frpr_icmp(fin);
1400 		break;
1401 	case IPPROTO_AH :
1402 		frpr_ah(fin);
1403 		break;
1404 	case IPPROTO_ESP :
1405 		frpr_esp(fin);
1406 		break;
1407 	case IPPROTO_GRE :
1408 		frpr_gre(fin);
1409 		break;
1410 	}
1411 
1412 	ip = fin->fin_ip;
1413 	if (ip == NULL)
1414 		return;
1415 
1416 	/*
1417 	 * If it is a standard IP header (no options), set the flag fields
1418 	 * which relate to options to 0.
1419 	 */
1420 	if (hlen == sizeof(*ip)) {
1421 		fi->fi_optmsk = 0;
1422 		fi->fi_secmsk = 0;
1423 		fi->fi_auth = 0;
1424 		return;
1425 	}
1426 
1427 	/*
1428 	 * So the IP header has some IP options attached.  Walk the entire
1429 	 * list of options present with this packet and set flags to indicate
1430 	 * which ones are here and which ones are not.  For the somewhat out
1431 	 * of date and obscure security classification options, set a flag to
1432 	 * represent which classification is present.
1433 	 */
1434 	fi->fi_flx |= FI_OPTIONS;
1435 
1436 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1437 		opt = *s;
1438 		if (opt == '\0')
1439 			break;
1440 		else if (opt == IPOPT_NOP)
1441 			ol = 1;
1442 		else {
1443 			if (hlen < 2)
1444 				break;
1445 			ol = (int)*(s + 1);
1446 			if (ol < 2 || ol > hlen)
1447 				break;
1448 		}
1449 		for (i = 9, mv = 4; mv >= 0; ) {
1450 			op = ipopts + i;
1451 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1452 				optmsk |= op->ol_bit;
1453 				if (opt == IPOPT_SECURITY) {
1454 					const struct optlist *sp;
1455 					u_char	sec;
1456 					int j, m;
1457 
1458 					sec = *(s + 2);	/* classification */
1459 					for (j = 3, m = 2; m >= 0; ) {
1460 						sp = secopt + j;
1461 						if (sec == sp->ol_val) {
1462 							secmsk |= sp->ol_bit;
1463 							auth = *(s + 3);
1464 							auth *= 256;
1465 							auth += *(s + 4);
1466 							break;
1467 						}
1468 						if (sec < sp->ol_val)
1469 							j -= m;
1470 						else
1471 							j += m;
1472 						m--;
1473 					}
1474 				}
1475 				break;
1476 			}
1477 			if (opt < op->ol_val)
1478 				i -= mv;
1479 			else
1480 				i += mv;
1481 			mv--;
1482 		}
1483 		hlen -= ol;
1484 		s += ol;
1485 	}
1486 
1487 	/*
1488 	 *
1489 	 */
1490 	if (auth && !(auth & 0x0100))
1491 		auth &= 0xff00;
1492 	fi->fi_optmsk = optmsk;
1493 	fi->fi_secmsk = secmsk;
1494 	fi->fi_auth = auth;
1495 }
1496 
1497 
1498 /* ------------------------------------------------------------------------ */
1499 /* Function:    fr_makefrip                                                 */
1500 /* Returns:     int - 1 == hdr checking error, 0 == OK                      */
1501 /* Parameters:  hlen(I) - length of IP packet header                        */
1502 /*              ip(I)   - pointer to the IP header                          */
1503 /*              fin(IO) - pointer to packet information                     */
1504 /*                                                                          */
1505 /* Compact the IP header into a structure which contains just the info.     */
1506 /* which is useful for comparing IP headers with and store this information */
1507 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
1508 /* this function will be called with either an IPv4 or IPv6 packet.         */
1509 /* ------------------------------------------------------------------------ */
1510 int	fr_makefrip(hlen, ip, fin)
1511 int hlen;
1512 ip_t *ip;
1513 fr_info_t *fin;
1514 {
1515 	int v;
1516 
1517 	fin->fin_nat = NULL;
1518 	fin->fin_state = NULL;
1519 	fin->fin_depth = 0;
1520 	fin->fin_hlen = (u_short)hlen;
1521 	fin->fin_ip = ip;
1522 	fin->fin_rule = 0xffffffff;
1523 	fin->fin_group[0] = -1;
1524 	fin->fin_group[1] = '\0';
1525 	fin->fin_dlen = fin->fin_plen - hlen;
1526 	fin->fin_dp = (char *)ip + hlen;
1527 
1528 	v = fin->fin_v;
1529 	if (v == 4)
1530 		frpr_ipv4hdr(fin);
1531 #ifdef	USE_INET6
1532 	else if (v == 6) {
1533 		if (frpr_ipv6hdr(fin) == -1)
1534 			return -1;
1535 	}
1536 #endif
1537 	if (fin->fin_ip == NULL)
1538 		return -1;
1539 	return 0;
1540 }
1541 
1542 
1543 /* ------------------------------------------------------------------------ */
1544 /* Function:    fr_portcheck                                                */
1545 /* Returns:     int - 1 == port matched, 0 == port match failed             */
1546 /* Parameters:  frp(I) - pointer to port check `expression'                 */
1547 /*              pop(I) - pointer to port number to evaluate                 */
1548 /*                                                                          */
1549 /* Perform a comparison of a port number against some other(s), using a     */
1550 /* structure with compare information stored in it.                         */
1551 /* ------------------------------------------------------------------------ */
1552 static INLINE int fr_portcheck(frp, pop)
1553 frpcmp_t *frp;
1554 u_short *pop;
1555 {
1556 	u_short tup, po;
1557 	int err = 1;
1558 
1559 	tup = *pop;
1560 	po = frp->frp_port;
1561 
1562 	/*
1563 	 * Do opposite test to that required and continue if that succeeds.
1564 	 */
1565 	switch (frp->frp_cmp)
1566 	{
1567 	case FR_EQUAL :
1568 		if (tup != po) /* EQUAL */
1569 			err = 0;
1570 		break;
1571 	case FR_NEQUAL :
1572 		if (tup == po) /* NOTEQUAL */
1573 			err = 0;
1574 		break;
1575 	case FR_LESST :
1576 		if (tup >= po) /* LESSTHAN */
1577 			err = 0;
1578 		break;
1579 	case FR_GREATERT :
1580 		if (tup <= po) /* GREATERTHAN */
1581 			err = 0;
1582 		break;
1583 	case FR_LESSTE :
1584 		if (tup > po) /* LT or EQ */
1585 			err = 0;
1586 		break;
1587 	case FR_GREATERTE :
1588 		if (tup < po) /* GT or EQ */
1589 			err = 0;
1590 		break;
1591 	case FR_OUTRANGE :
1592 		if (tup >= po && tup <= frp->frp_top) /* Out of range */
1593 			err = 0;
1594 		break;
1595 	case FR_INRANGE :
1596 		if (tup <= po || tup >= frp->frp_top) /* In range */
1597 			err = 0;
1598 		break;
1599 	case FR_INCRANGE :
1600 		if (tup < po || tup > frp->frp_top) /* Inclusive range */
1601 			err = 0;
1602 		break;
1603 	default :
1604 		break;
1605 	}
1606 	return err;
1607 }
1608 
1609 
1610 /* ------------------------------------------------------------------------ */
1611 /* Function:    fr_tcpudpchk                                                */
1612 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
1613 /* Parameters:  fin(I) - pointer to packet information                      */
1614 /*              ft(I)  - pointer to structure with comparison data          */
1615 /*                                                                          */
1616 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
1617 /* structure containing information that we want to match against.          */
1618 /* ------------------------------------------------------------------------ */
1619 int fr_tcpudpchk(fin, ft)
1620 fr_info_t *fin;
1621 frtuc_t *ft;
1622 {
1623 	int err = 1;
1624 
1625 	/*
1626 	 * Both ports should *always* be in the first fragment.
1627 	 * So far, I cannot find any cases where they can not be.
1628 	 *
1629 	 * compare destination ports
1630 	 */
1631 	if (ft->ftu_dcmp)
1632 		err = fr_portcheck(&ft->ftu_dst, &fin->fin_dport);
1633 
1634 	/*
1635 	 * compare source ports
1636 	 */
1637 	if (err && ft->ftu_scmp)
1638 		err = fr_portcheck(&ft->ftu_src, &fin->fin_sport);
1639 
1640 	/*
1641 	 * If we don't have all the TCP/UDP header, then how can we
1642 	 * expect to do any sort of match on it ?  If we were looking for
1643 	 * TCP flags, then NO match.  If not, then match (which should
1644 	 * satisfy the "short" class too).
1645 	 */
1646 	if (err && (fin->fin_p == IPPROTO_TCP)) {
1647 		if (fin->fin_flx & FI_SHORT)
1648 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
1649 		/*
1650 		 * Match the flags ?  If not, abort this match.
1651 		 */
1652 		if (ft->ftu_tcpfm &&
1653 		    ft->ftu_tcpf != (fin->fin_tcpf & ft->ftu_tcpfm)) {
1654 			FR_DEBUG(("f. %#x & %#x != %#x\n", fin->fin_tcpf,
1655 				 ft->ftu_tcpfm, ft->ftu_tcpf));
1656 			err = 0;
1657 		}
1658 	}
1659 	return err;
1660 }
1661 
1662 
1663 /* ------------------------------------------------------------------------ */
1664 /* Function:    fr_ipfcheck                                                 */
1665 /* Returns:     int - 0 == match, 1 == no match                             */
1666 /* Parameters:  fin(I)     - pointer to packet information                  */
1667 /*              fr(I)      - pointer to filter rule                         */
1668 /*              portcmp(I) - flag indicating whether to attempt matching on */
1669 /*                           TCP/UDP port data.                             */
1670 /*                                                                          */
1671 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
1672 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
1673 /* this function.                                                           */
1674 /* ------------------------------------------------------------------------ */
1675 static INLINE int fr_ipfcheck(fin, fr, portcmp)
1676 fr_info_t *fin;
1677 frentry_t *fr;
1678 int portcmp;
1679 {
1680 	u_32_t	*ld, *lm, *lip;
1681 	fripf_t *fri;
1682 	fr_ip_t *fi;
1683 	int i;
1684 	ipf_stack_t *ifs = fin->fin_ifs;
1685 
1686 	fi = &fin->fin_fi;
1687 	fri = fr->fr_ipf;
1688 	lip = (u_32_t *)fi;
1689 	lm = (u_32_t *)&fri->fri_mip;
1690 	ld = (u_32_t *)&fri->fri_ip;
1691 
1692 	/*
1693 	 * first 32 bits to check coversion:
1694 	 * IP version, TOS, TTL, protocol
1695 	 */
1696 	i = ((*lip & *lm) != *ld);
1697 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
1698 		   *lip, *lm, *ld));
1699 	if (i)
1700 		return 1;
1701 
1702 	/*
1703 	 * Next 32 bits is a constructed bitmask indicating which IP options
1704 	 * are present (if any) in this packet.
1705 	 */
1706 	lip++, lm++, ld++;
1707 	i |= ((*lip & *lm) != *ld);
1708 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
1709 		   *lip, *lm, *ld));
1710 	if (i)
1711 		return 1;
1712 
1713 	lip++, lm++, ld++;
1714 	/*
1715 	 * Unrolled loops (4 each, for 32 bits) for address checks.
1716 	 */
1717 	/*
1718 	 * Check the source address.
1719 	 */
1720 #ifdef	IPFILTER_LOOKUP
1721 	if (fr->fr_satype == FRI_LOOKUP) {
1722 		i = (*fr->fr_srcfunc)(fr->fr_srcptr, fi->fi_v, lip, ifs);
1723 		if (i == -1)
1724 			return 1;
1725 		lip += 3;
1726 		lm += 3;
1727 		ld += 3;
1728 	} else {
1729 #endif
1730 		i = ((*lip & *lm) != *ld);
1731 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
1732 			   *lip, *lm, *ld));
1733 		if (fi->fi_v == 6) {
1734 			lip++, lm++, ld++;
1735 			i |= ((*lip & *lm) != *ld);
1736 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
1737 				   *lip, *lm, *ld));
1738 			lip++, lm++, ld++;
1739 			i |= ((*lip & *lm) != *ld);
1740 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
1741 				   *lip, *lm, *ld));
1742 			lip++, lm++, ld++;
1743 			i |= ((*lip & *lm) != *ld);
1744 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
1745 				   *lip, *lm, *ld));
1746 		} else {
1747 			lip += 3;
1748 			lm += 3;
1749 			ld += 3;
1750 		}
1751 #ifdef	IPFILTER_LOOKUP
1752 	}
1753 #endif
1754 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
1755 	if (i)
1756 		return 1;
1757 
1758 	/*
1759 	 * Check the destination address.
1760 	 */
1761 	lip++, lm++, ld++;
1762 #ifdef	IPFILTER_LOOKUP
1763 	if (fr->fr_datype == FRI_LOOKUP) {
1764 		i = (*fr->fr_dstfunc)(fr->fr_dstptr, fi->fi_v, lip, ifs);
1765 		if (i == -1)
1766 			return 1;
1767 		lip += 3;
1768 		lm += 3;
1769 		ld += 3;
1770 	} else {
1771 #endif
1772 		i = ((*lip & *lm) != *ld);
1773 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
1774 			   *lip, *lm, *ld));
1775 		if (fi->fi_v == 6) {
1776 			lip++, lm++, ld++;
1777 			i |= ((*lip & *lm) != *ld);
1778 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
1779 				   *lip, *lm, *ld));
1780 			lip++, lm++, ld++;
1781 			i |= ((*lip & *lm) != *ld);
1782 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
1783 				   *lip, *lm, *ld));
1784 			lip++, lm++, ld++;
1785 			i |= ((*lip & *lm) != *ld);
1786 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
1787 				   *lip, *lm, *ld));
1788 		} else {
1789 			lip += 3;
1790 			lm += 3;
1791 			ld += 3;
1792 		}
1793 #ifdef	IPFILTER_LOOKUP
1794 	}
1795 #endif
1796 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
1797 	if (i)
1798 		return 1;
1799 	/*
1800 	 * IP addresses matched.  The next 32bits contains:
1801 	 * mast of old IP header security & authentication bits.
1802 	 */
1803 	lip++, lm++, ld++;
1804 	i |= ((*lip & *lm) != *ld);
1805 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n",
1806 		   *lip, *lm, *ld));
1807 
1808 	/*
1809 	 * Next we have 32 bits of packet flags.
1810 	 */
1811 	lip++, lm++, ld++;
1812 	i |= ((*lip & *lm) != *ld);
1813 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n",
1814 		   *lip, *lm, *ld));
1815 
1816 	if (i == 0) {
1817 		/*
1818 		 * If a fragment, then only the first has what we're
1819 		 * looking for here...
1820 		 */
1821 		if (portcmp) {
1822 			if (!fr_tcpudpchk(fin, &fr->fr_tuc))
1823 				i = 1;
1824 		} else {
1825 			if (fr->fr_dcmp || fr->fr_scmp ||
1826 			    fr->fr_tcpf || fr->fr_tcpfm)
1827 				i = 1;
1828 			if (fr->fr_icmpm || fr->fr_icmp) {
1829 				if (((fi->fi_p != IPPROTO_ICMP) &&
1830 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
1831 				    fin->fin_off || (fin->fin_dlen < 2))
1832 					i = 1;
1833 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
1834 					 fr->fr_icmp) {
1835 					FR_DEBUG(("i. %#x & %#x != %#x\n",
1836 						 fin->fin_data[0],
1837 						 fr->fr_icmpm, fr->fr_icmp));
1838 					i = 1;
1839 				}
1840 			}
1841 		}
1842 	}
1843 	return i;
1844 }
1845 
1846 
1847 /* ------------------------------------------------------------------------ */
1848 /* Function:    fr_scanlist                                                 */
1849 /* Returns:     int - result flags of scanning filter list                  */
1850 /* Parameters:  fin(I) - pointer to packet information                      */
1851 /*              pass(I) - default result to return for filtering            */
1852 /*                                                                          */
1853 /* Check the input/output list of rules for a match to the current packet.  */
1854 /* If a match is found, the value of fr_flags from the rule becomes the     */
1855 /* return value and fin->fin_fr points to the matched rule.                 */
1856 /*                                                                          */
1857 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
1858 /* When unwinding, it should finish up with fin_depth as 0.                 */
1859 /*                                                                          */
1860 /* Could be per interface, but this gets real nasty when you don't have,    */
1861 /* or can't easily change, the kernel source code to .                      */
1862 /* ------------------------------------------------------------------------ */
1863 int fr_scanlist(fin, pass)
1864 fr_info_t *fin;
1865 u_32_t pass;
1866 {
1867 	int rulen, portcmp, off, logged, skip;
1868 	struct frentry *fr, *fnext;
1869 	u_32_t passt, passo;
1870 	ipf_stack_t *ifs = fin->fin_ifs;
1871 
1872 	/*
1873 	 * Do not allow nesting deeper than 16 levels.
1874 	 */
1875 	if (fin->fin_depth >= 16)
1876 		return pass;
1877 
1878 	fr = fin->fin_fr;
1879 
1880 	/*
1881 	 * If there are no rules in this list, return now.
1882 	 */
1883 	if (fr == NULL)
1884 		return pass;
1885 
1886 	skip = 0;
1887 	logged = 0;
1888 	portcmp = 0;
1889 	fin->fin_depth++;
1890 	fin->fin_fr = NULL;
1891 	off = fin->fin_off;
1892 
1893 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
1894 		portcmp = 1;
1895 
1896 	for (rulen = 0; fr; fr = fnext, rulen++) {
1897 		fnext = fr->fr_next;
1898 		if (skip != 0) {
1899 			FR_VERBOSE(("%d (%#x)\n", skip, fr->fr_flags));
1900 			skip--;
1901 			continue;
1902 		}
1903 
1904 		/*
1905 		 * In all checks below, a null (zero) value in the
1906 		 * filter struture is taken to mean a wildcard.
1907 		 *
1908 		 * check that we are working for the right interface
1909 		 */
1910 #ifdef	_KERNEL
1911 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
1912 			continue;
1913 #else
1914 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
1915 			printf("\n");
1916 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
1917 				  FR_ISPASS(pass) ? 'p' :
1918 				  FR_ISACCOUNT(pass) ? 'A' :
1919 				  FR_ISAUTH(pass) ? 'a' :
1920 				  (pass & FR_NOMATCH) ? 'n' :'b'));
1921 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
1922 			continue;
1923 		FR_VERBOSE((":i"));
1924 #endif
1925 
1926 		switch (fr->fr_type)
1927 		{
1928 		case FR_T_IPF :
1929 		case FR_T_IPF|FR_T_BUILTIN :
1930 			if (fr_ipfcheck(fin, fr, portcmp))
1931 				continue;
1932 			break;
1933 #if defined(IPFILTER_BPF)
1934 		case FR_T_BPFOPC :
1935 		case FR_T_BPFOPC|FR_T_BUILTIN :
1936 		    {
1937 			u_char *mc;
1938 
1939 			if (*fin->fin_mp == NULL)
1940 				continue;
1941 			if (fin->fin_v != fr->fr_v)
1942 				continue;
1943 			mc = (u_char *)fin->fin_m;
1944 			if (!bpf_filter(fr->fr_data, mc, fin->fin_plen, 0))
1945 				continue;
1946 			break;
1947 		    }
1948 #endif
1949 		case FR_T_CALLFUNC|FR_T_BUILTIN :
1950 		    {
1951 			frentry_t *f;
1952 
1953 			f = (*fr->fr_func)(fin, &pass);
1954 			if (f != NULL)
1955 				fr = f;
1956 			else
1957 				continue;
1958 			break;
1959 		    }
1960 		default :
1961 			break;
1962 		}
1963 
1964 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
1965 			if (fin->fin_nattag == NULL)
1966 				continue;
1967 			if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
1968 				continue;
1969 		}
1970 		FR_VERBOSE(("=%s.%d *", fr->fr_group, rulen));
1971 
1972 		passt = fr->fr_flags;
1973 
1974 		/*
1975 		 * Allowing a rule with the "keep state" flag set to match
1976 		 * packets that have been tagged "out of window" by the TCP
1977 		 * state tracking is foolish as the attempt to add a new
1978 		 * state entry to the table will fail.
1979 		 */
1980 		if ((passt & FR_KEEPSTATE) && (fin->fin_flx & FI_OOW))
1981 			continue;
1982 
1983 		/*
1984 		 * If the rule is a "call now" rule, then call the function
1985 		 * in the rule, if it exists and use the results from that.
1986 		 * If the function pointer is bad, just make like we ignore
1987 		 * it, except for increasing the hit counter.
1988 		 */
1989 		if ((passt & FR_CALLNOW) != 0) {
1990 			IPF_BUMP(fr->fr_hits);
1991 			if ((fr->fr_func != NULL) &&
1992 			    (fr->fr_func != (ipfunc_t)-1)) {
1993 				frentry_t *frs;
1994 
1995 				frs = fin->fin_fr;
1996 				fin->fin_fr = fr;
1997 				fr = (*fr->fr_func)(fin, &passt);
1998 				if (fr == NULL) {
1999 					fin->fin_fr = frs;
2000 					continue;
2001 				}
2002 				passt = fr->fr_flags;
2003 				fin->fin_fr = fr;
2004 			}
2005 		} else {
2006 			fin->fin_fr = fr;
2007 		}
2008 
2009 #ifdef  IPFILTER_LOG
2010 		/*
2011 		 * Just log this packet...
2012 		 */
2013 		if ((passt & FR_LOGMASK) == FR_LOG) {
2014 			if (ipflog(fin, passt) == -1) {
2015 				if (passt & FR_LOGORBLOCK) {
2016 					passt &= ~FR_CMDMASK;
2017 					passt |= FR_BLOCK|FR_QUICK;
2018 				}
2019 				IPF_BUMP(ifs->ifs_frstats[fin->fin_out].fr_skip);
2020 			}
2021 			IPF_BUMP(ifs->ifs_frstats[fin->fin_out].fr_pkl);
2022 			logged = 1;
2023 		}
2024 #endif /* IPFILTER_LOG */
2025 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2026 		passo = pass;
2027 		if (FR_ISSKIP(passt))
2028 			skip = fr->fr_arg;
2029 		else if ((passt & FR_LOGMASK) != FR_LOG)
2030 			pass = passt;
2031 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2032 			fin->fin_icode = fr->fr_icode;
2033 		FR_DEBUG(("pass %#x\n", pass));
2034 		IPF_BUMP(fr->fr_hits);
2035 		fin->fin_rule = rulen;
2036 		(void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
2037 		if (fr->fr_grp != NULL) {
2038 			fin->fin_fr = *fr->fr_grp;
2039 			pass = fr_scanlist(fin, pass);
2040 			if (fin->fin_fr == NULL) {
2041 				fin->fin_rule = rulen;
2042 				(void) strncpy(fin->fin_group, fr->fr_group,
2043 					       FR_GROUPLEN);
2044 				fin->fin_fr = fr;
2045 			}
2046 			if (fin->fin_flx & FI_DONTCACHE)
2047 				logged = 1;
2048 		}
2049 
2050 		if (pass & FR_QUICK) {
2051 			/*
2052 			 * Finally, if we've asked to track state for this
2053 			 * packet, set it up.  Add state for "quick" rules
2054 			 * here so that if the action fails we can consider
2055 			 * the rule to "not match" and keep on processing
2056 			 * filter rules.
2057 			 */
2058 			if ((pass & FR_KEEPSTATE) &&
2059 			    !(fin->fin_flx & FI_STATE)) {
2060 				int out = fin->fin_out;
2061 
2062 				if (fr_addstate(fin, NULL, 0) != NULL) {
2063 					IPF_BUMP(ifs->ifs_frstats[out].fr_ads);
2064 				} else {
2065 					IPF_BUMP(ifs->ifs_frstats[out].fr_bads);
2066 					pass = passo;
2067 					continue;
2068 				}
2069 			}
2070 			break;
2071 		}
2072 	}
2073 	if (logged)
2074 		fin->fin_flx |= FI_DONTCACHE;
2075 	fin->fin_depth--;
2076 	return pass;
2077 }
2078 
2079 
2080 /* ------------------------------------------------------------------------ */
2081 /* Function:    fr_acctpkt                                                  */
2082 /* Returns:     frentry_t* - always returns NULL                            */
2083 /* Parameters:  fin(I) - pointer to packet information                      */
2084 /*              passp(IO) - pointer to current/new filter decision (unused) */
2085 /*                                                                          */
2086 /* Checks a packet against accounting rules, if there are any for the given */
2087 /* IP protocol version.                                                     */
2088 /*                                                                          */
2089 /* N.B.: this function returns NULL to match the prototype used by other    */
2090 /* functions called from the IPFilter "mainline" in fr_check().             */
2091 /* ------------------------------------------------------------------------ */
2092 frentry_t *fr_acctpkt(fin, passp)
2093 fr_info_t *fin;
2094 u_32_t *passp;
2095 {
2096 	char group[FR_GROUPLEN];
2097 	frentry_t *fr, *frsave;
2098 	u_32_t pass, rulen;
2099 	ipf_stack_t *ifs = fin->fin_ifs;
2100 
2101 	passp = passp;
2102 #ifdef	USE_INET6
2103 	if (fin->fin_v == 6)
2104 		fr = ifs->ifs_ipacct6[fin->fin_out][ifs->ifs_fr_active];
2105 	else
2106 #endif
2107 		fr = ifs->ifs_ipacct[fin->fin_out][ifs->ifs_fr_active];
2108 
2109 	if (fr != NULL) {
2110 		frsave = fin->fin_fr;
2111 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2112 		rulen = fin->fin_rule;
2113 		fin->fin_fr = fr;
2114 		pass = fr_scanlist(fin, FR_NOMATCH);
2115 		if (FR_ISACCOUNT(pass)) {
2116 			IPF_BUMP(ifs->ifs_frstats[0].fr_acct);
2117 		}
2118 		fin->fin_fr = frsave;
2119 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2120 		fin->fin_rule = rulen;
2121 	}
2122 	return NULL;
2123 }
2124 
2125 
2126 /* ------------------------------------------------------------------------ */
2127 /* Function:    fr_firewall                                                 */
2128 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2129 /*                           were found, returns NULL.                      */
2130 /* Parameters:  fin(I) - pointer to packet information                      */
2131 /*              passp(IO) - pointer to current/new filter decision (unused) */
2132 /*                                                                          */
2133 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2134 /* there are any matches.  The first check is to see if a match can be seen */
2135 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2136 /* matching rule is found, take any appropriate actions as defined by the   */
2137 /* rule - except logging.                                                   */
2138 /* ------------------------------------------------------------------------ */
2139 static frentry_t *fr_firewall(fin, passp)
2140 fr_info_t *fin;
2141 u_32_t *passp;
2142 {
2143 	frentry_t *fr;
2144 	u_32_t pass;
2145 	int out;
2146 	ipf_stack_t *ifs = fin->fin_ifs;
2147 
2148 	out = fin->fin_out;
2149 	pass = *passp;
2150 
2151 #ifdef	USE_INET6
2152 	if (fin->fin_v == 6)
2153 		fin->fin_fr = ifs->ifs_ipfilter6[out][ifs->ifs_fr_active];
2154 	else
2155 #endif
2156 		fin->fin_fr = ifs->ifs_ipfilter[out][ifs->ifs_fr_active];
2157 	if (fin->fin_fr != NULL)
2158 		pass = fr_scanlist(fin, ifs->ifs_fr_pass);
2159 
2160 	if ((pass & FR_NOMATCH)) {
2161 		IPF_BUMP(ifs->ifs_frstats[out].fr_nom);
2162 	}
2163 	fr = fin->fin_fr;
2164 
2165 	/*
2166 	 * Apply packets per second rate-limiting to a rule as required.
2167 	 */
2168 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2169 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2170 		pass &= ~(FR_CMDMASK|FR_DUP|FR_RETICMP|FR_RETRST);
2171 		pass |= FR_BLOCK;
2172 		IPF_BUMP(ifs->ifs_frstats[out].fr_ppshit);
2173 	}
2174 
2175 	/*
2176 	 * If we fail to add a packet to the authorization queue, then we
2177 	 * drop the packet later.  However, if it was added then pretend
2178 	 * we've dropped it already.
2179 	 */
2180 	if (FR_ISAUTH(pass)) {
2181 		if (fr_newauth(fin->fin_m, fin) != 0) {
2182 #ifdef	_KERNEL
2183 			fin->fin_m = *fin->fin_mp = NULL;
2184 #else
2185 			;
2186 #endif
2187 			fin->fin_error = 0;
2188 		} else
2189 			fin->fin_error = ENOSPC;
2190 	}
2191 
2192 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2193 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2194 		(void) (*fr->fr_func)(fin, &pass);
2195 
2196 	/*
2197 	 * If a rule is a pre-auth rule, check again in the list of rules
2198 	 * loaded for authenticated use.  It does not particulary matter
2199 	 * if this search fails because a "preauth" result, from a rule,
2200 	 * is treated as "not a pass", hence the packet is blocked.
2201 	 */
2202 	if (FR_ISPREAUTH(pass)) {
2203 		if ((fin->fin_fr = ifs->ifs_ipauth) != NULL)
2204 			pass = fr_scanlist(fin, ifs->ifs_fr_pass);
2205 	}
2206 
2207 	/*
2208 	 * If the rule has "keep frag" and the packet is actually a fragment,
2209 	 * then create a fragment state entry.
2210 	 */
2211 	if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2212 		if (fin->fin_flx & FI_FRAG) {
2213 			if (fr_newfrag(fin, pass) == -1) {
2214 				IPF_BUMP(ifs->ifs_frstats[out].fr_bnfr);
2215 			} else {
2216 				IPF_BUMP(ifs->ifs_frstats[out].fr_nfr);
2217 			}
2218 		} else {
2219 			IPF_BUMP(ifs->ifs_frstats[out].fr_cfr);
2220 		}
2221 	}
2222 
2223 	/*
2224 	 * Finally, if we've asked to track state for this packet, set it up.
2225 	 */
2226 	if ((pass & FR_KEEPSTATE) && !(fin->fin_flx & FI_STATE)) {
2227 		if (fr_addstate(fin, NULL, 0) != NULL) {
2228 			IPF_BUMP(ifs->ifs_frstats[out].fr_ads);
2229 		} else {
2230 			IPF_BUMP(ifs->ifs_frstats[out].fr_bads);
2231 			if (FR_ISPASS(pass)) {
2232 				pass &= ~FR_CMDMASK;
2233 				pass |= FR_BLOCK;
2234 			}
2235 		}
2236 	}
2237 
2238 	fr = fin->fin_fr;
2239 
2240 	if (passp != NULL)
2241 		*passp = pass;
2242 
2243 	return fr;
2244 }
2245 
2246 
2247 /* ------------------------------------------------------------------------ */
2248 /* Function:    fr_check                                                    */
2249 /* Returns:     int -  0 == packet allowed through,                         */
2250 /*              User space:                                                 */
2251 /*                    -1 == packet blocked                                  */
2252 /*                     1 == packet not matched                              */
2253 /*                    -2 == requires authentication                         */
2254 /*              Kernel:                                                     */
2255 /*                   > 0 == filter error # for packet                       */
2256 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2257 /*             hlen(I) - length of header                                   */
2258 /*             ifp(I)  - pointer to interface this packet is on             */
2259 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2260 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2261 /*                       IP packet.                                         */
2262 /* Solaris & HP-UX ONLY :                                                   */
2263 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2264 /*                       interface & direction.                             */
2265 /*                                                                          */
2266 /* fr_check() is the master function for all IPFilter packet processing.    */
2267 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2268 /* authorisation (or pre-authorisation), presence of related state info.,   */
2269 /* generating log entries, IP packet accounting, routing of packets as      */
2270 /* directed by firewall rules and of course whether or not to allow the     */
2271 /* packet to be further processed by the kernel.                            */
2272 /*                                                                          */
2273 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2274 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2275 /* by "mp" changed to a new buffer.                                         */
2276 /* ------------------------------------------------------------------------ */
2277 int fr_check(ip, hlen, ifp, out
2278 #if defined(_KERNEL) && defined(MENTAT)
2279 , qif, mp, ifs)
2280 void *qif;
2281 #else
2282 , mp, ifs)
2283 #endif
2284 mb_t **mp;
2285 ip_t *ip;
2286 int hlen;
2287 void *ifp;
2288 int out;
2289 ipf_stack_t *ifs;
2290 {
2291 	/*
2292 	 * The above really sucks, but short of writing a diff
2293 	 */
2294 	fr_info_t frinfo;
2295 	fr_info_t *fin = &frinfo;
2296 	u_32_t pass;
2297 	frentry_t *fr = NULL;
2298 	int v = IP_V(ip);
2299 	mb_t *mc = NULL;
2300 	mb_t *m;
2301 #ifdef USE_INET6
2302 	ip6_t *ip6;
2303 #endif
2304 #ifdef	_KERNEL
2305 # ifdef MENTAT
2306 	qpktinfo_t *qpi = qif;
2307 #endif
2308 #endif
2309 
2310 	SPL_INT(s);
2311 	pass = ifs->ifs_fr_pass;
2312 
2313 	/*
2314 	 * The first part of fr_check() deals with making sure that what goes
2315 	 * into the filtering engine makes some sense.  Information about the
2316 	 * the packet is distilled, collected into a fr_info_t structure and
2317 	 * the an attempt to ensure the buffer the packet is in is big enough
2318 	 * to hold all the required packet headers.
2319 	 */
2320 #ifdef	_KERNEL
2321 # ifdef MENTAT
2322 	if (!OK_32PTR(ip))
2323 		return 2;
2324 # endif
2325 
2326 
2327 	if (ifs->ifs_fr_running <= 0) {
2328 		return 0;
2329 	}
2330 
2331 	bzero((char *)fin, sizeof(*fin));
2332 
2333 # ifdef MENTAT
2334 	fin->fin_flx = qpi->qpi_flags & (FI_NOCKSUM|FI_MBCAST|FI_MULTICAST|
2335 					 FI_BROADCAST);
2336 	m = qpi->qpi_m;
2337 	fin->fin_qfm = m;
2338 	fin->fin_qpi = qpi;
2339 # else /* MENTAT */
2340 
2341 	m = *mp;
2342 
2343 #  if defined(M_MCAST)
2344 	if ((m->m_flags & M_MCAST) != 0)
2345 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2346 #  endif
2347 #  if defined(M_MLOOP)
2348 	if ((m->m_flags & M_MLOOP) != 0)
2349 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2350 #  endif
2351 #  if defined(M_BCAST)
2352 	if ((m->m_flags & M_BCAST) != 0)
2353 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2354 #  endif
2355 #  ifdef M_CANFASTFWD
2356 	/*
2357 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2358 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2359 	 * XXX get a "can-fast-forward" filter rule.
2360 	 */
2361 	m->m_flags &= ~M_CANFASTFWD;
2362 #  endif /* M_CANFASTFWD */
2363 #  ifdef CSUM_DELAY_DATA
2364 	/*
2365 	 * disable delayed checksums.
2366 	 */
2367 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2368 		in_delayed_cksum(m);
2369 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2370 	}
2371 #  endif /* CSUM_DELAY_DATA */
2372 # endif /* MENTAT */
2373 #else
2374 
2375 	bzero((char *)fin, sizeof(*fin));
2376 	m = *mp;
2377 #endif /* _KERNEL */
2378 
2379 	fin->fin_v = v;
2380 	fin->fin_m = m;
2381 	fin->fin_ip = ip;
2382 	fin->fin_mp = mp;
2383 	fin->fin_out = out;
2384 	fin->fin_ifp = ifp;
2385 	fin->fin_error = ENETUNREACH;
2386 	fin->fin_hlen = (u_short)hlen;
2387 	fin->fin_dp = (char *)ip + hlen;
2388 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2389 	fin->fin_ifs = ifs;
2390 
2391 	SPL_NET(s);
2392 
2393 #ifdef	USE_INET6
2394 	if (v == 6) {
2395 		IPF_BUMP(ifs->ifs_frstats[out].fr_ipv6);
2396 		/*
2397 		 * Jumbo grams are quite likely too big for internal buffer
2398 		 * structures to handle comfortably, for now, so just drop
2399 		 * them.
2400 		 */
2401 		ip6 = (ip6_t *)ip;
2402 		fin->fin_plen = ntohs(ip6->ip6_plen);
2403 		if (fin->fin_plen == 0) {
2404 			READ_ENTER(&ifs->ifs_ipf_mutex);
2405 			pass = FR_BLOCK|FR_NOMATCH;
2406 			goto filtered;
2407 		}
2408 		fin->fin_plen += sizeof(ip6_t);
2409 	} else
2410 #endif
2411 	{
2412 #if (OpenBSD >= 200311) && defined(_KERNEL)
2413 		ip->ip_len = ntohs(ip->ip_len);
2414 		ip->ip_off = ntohs(ip->ip_off);
2415 #endif
2416 		fin->fin_plen = ip->ip_len;
2417 	}
2418 
2419 	if (fr_makefrip(hlen, ip, fin) == -1) {
2420 		READ_ENTER(&ifs->ifs_ipf_mutex);
2421 		pass = FR_BLOCK;
2422 		goto filtered;
2423 	}
2424 
2425 	/*
2426 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2427 	 * becomes NULL and so we have no packet to free.
2428 	 */
2429 	if (*fin->fin_mp == NULL)
2430 		goto finished;
2431 
2432 	if (!out) {
2433 		if (v == 4) {
2434 #ifdef _KERNEL
2435 			if (ifs->ifs_fr_chksrc && !fr_verifysrc(fin)) {
2436 				IPF_BUMP(ifs->ifs_frstats[0].fr_badsrc);
2437 				fin->fin_flx |= FI_BADSRC;
2438 			}
2439 #endif
2440 			if (fin->fin_ip->ip_ttl < ifs->ifs_fr_minttl) {
2441 				IPF_BUMP(ifs->ifs_frstats[0].fr_badttl);
2442 				fin->fin_flx |= FI_LOWTTL;
2443 			}
2444 		}
2445 #ifdef USE_INET6
2446 		else  if (v == 6) {
2447 			ip6 = (ip6_t *)ip;
2448 #ifdef _KERNEL
2449 			if (ifs->ifs_fr_chksrc && !fr_verifysrc(fin)) {
2450 				IPF_BUMP(ifs->ifs_frstats[0].fr_badsrc);
2451 				fin->fin_flx |= FI_BADSRC;
2452 			}
2453 #endif
2454 			if (ip6->ip6_hlim < ifs->ifs_fr_minttl) {
2455 				IPF_BUMP(ifs->ifs_frstats[0].fr_badttl);
2456 				fin->fin_flx |= FI_LOWTTL;
2457 			}
2458 		}
2459 #endif
2460 	}
2461 
2462 	if (fin->fin_flx & FI_SHORT) {
2463 		IPF_BUMP(ifs->ifs_frstats[out].fr_short);
2464 	}
2465 
2466 	READ_ENTER(&ifs->ifs_ipf_mutex);
2467 
2468 	/*
2469 	 * Check auth now.  This, combined with the check below to see if apass
2470 	 * is 0 is to ensure that we don't count the packet twice, which can
2471 	 * otherwise occur when we reprocess it.  As it is, we only count it
2472 	 * after it has no auth. table matchup.  This also stops NAT from
2473 	 * occuring until after the packet has been auth'd.
2474 	 */
2475 	fr = fr_checkauth(fin, &pass);
2476 	if (!out) {
2477 		switch (fin->fin_v)
2478 		{
2479 		case 4 :
2480 			if (fr_checknatin(fin, &pass) == -1) {
2481 				RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2482 				goto finished;
2483 			}
2484 			break;
2485 #ifdef	USE_INET6
2486 		case 6 :
2487 			if (fr_checknat6in(fin, &pass) == -1) {
2488 				RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2489 				goto finished;
2490 			}
2491 			break;
2492 #endif
2493 		default :
2494 			break;
2495 		}
2496 	}
2497 	if (!out)
2498 		(void) fr_acctpkt(fin, NULL);
2499 
2500 	if (fr == NULL)
2501 		if ((fin->fin_flx & (FI_FRAG|FI_BAD)) == FI_FRAG)
2502 			fr = fr_knownfrag(fin, &pass);
2503 	if (fr == NULL)
2504 		fr = fr_checkstate(fin, &pass);
2505 
2506 	if ((pass & FR_NOMATCH) || (fr == NULL))
2507 		fr = fr_firewall(fin, &pass);
2508 
2509 	fin->fin_fr = fr;
2510 
2511 	/*
2512 	 * Only count/translate packets which will be passed on, out the
2513 	 * interface.
2514 	 */
2515 	if (out && FR_ISPASS(pass)) {
2516 		(void) fr_acctpkt(fin, NULL);
2517 
2518 		switch (fin->fin_v)
2519 		{
2520 		case 4 :
2521 			if (fr_checknatout(fin, &pass) == -1) {
2522 				RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2523 				goto finished;
2524 			}
2525 			break;
2526 #ifdef	USE_INET6
2527 		case 6 :
2528 			if (fr_checknat6out(fin, &pass) == -1) {
2529 				RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2530 				goto finished;
2531 			}
2532 			break;
2533 #endif
2534 		default :
2535 			break;
2536 		}
2537 
2538 		if ((ifs->ifs_fr_update_ipid != 0) && (v == 4)) {
2539 			if (fr_updateipid(fin) == -1) {
2540 				IPF_BUMP(ifs->ifs_frstats[1].fr_ipud);
2541 				pass &= ~FR_CMDMASK;
2542 				pass |= FR_BLOCK;
2543 			} else {
2544 				IPF_BUMP(ifs->ifs_frstats[0].fr_ipud);
2545 			}
2546 		}
2547 	}
2548 
2549 #ifdef	IPFILTER_LOG
2550 	if ((ifs->ifs_fr_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
2551 		(void) fr_dolog(fin, &pass);
2552 	}
2553 #endif
2554 
2555 	if (fin->fin_state != NULL)
2556 		fr_statederef((ipstate_t **)&fin->fin_state, ifs);
2557 
2558 	if (fin->fin_nat != NULL) {
2559 		if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT)) {
2560 			WRITE_ENTER(&ifs->ifs_ipf_nat);
2561 			nat_delete((nat_t *)fin->fin_nat, NL_DESTROY, ifs);
2562 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
2563 			fin->fin_nat = NULL;
2564 		} else {
2565 			fr_natderef((nat_t **)&fin->fin_nat, ifs);
2566 		}
2567 	}
2568 
2569 	/*
2570 	 * Only allow FR_DUP to work if a rule matched - it makes no sense to
2571 	 * set FR_DUP as a "default" as there are no instructions about where
2572 	 * to send the packet.  Use fin_m here because it may have changed
2573 	 * (without an update of 'm') in prior processing.
2574 	 */
2575 	if ((fr != NULL) && (pass & FR_DUP)) {
2576 		mc = M_DUPLICATE(fin->fin_m);
2577 	}
2578 
2579 	if (pass & (FR_RETRST|FR_RETICMP)) {
2580 		/*
2581 		 * Should we return an ICMP packet to indicate error
2582 		 * status passing through the packet filter ?
2583 		 * WARNING: ICMP error packets AND TCP RST packets should
2584 		 * ONLY be sent in repsonse to incoming packets.  Sending them
2585 		 * in response to outbound packets can result in a panic on
2586 		 * some operating systems.
2587 		 */
2588 		if (!out) {
2589 			if (pass & FR_RETICMP) {
2590 				int dst;
2591 
2592 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
2593 					dst = 1;
2594 				else
2595 					dst = 0;
2596 				(void) fr_send_icmp_err(ICMP_UNREACH, fin, dst);
2597 				IPF_BUMP(ifs->ifs_frstats[0].fr_ret);
2598 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
2599 				   !(fin->fin_flx & FI_SHORT)) {
2600 				if (fr_send_reset(fin) == 0) {
2601 					IPF_BUMP(ifs->ifs_frstats[1].fr_ret);
2602 				}
2603 			}
2604 		} else {
2605 			if (pass & FR_RETRST)
2606 				fin->fin_error = ECONNRESET;
2607 		}
2608 	}
2609 
2610 	/*
2611 	 * If we didn't drop off the bottom of the list of rules (and thus
2612 	 * the 'current' rule fr is not NULL), then we may have some extra
2613 	 * instructions about what to do with a packet.
2614 	 * Once we're finished return to our caller, freeing the packet if
2615 	 * we are dropping it (* BSD ONLY *).
2616 	 * Reassign m from fin_m as we may have a new buffer, now.
2617 	 */
2618 filtered:
2619 	m = fin->fin_m;
2620 
2621 	if (fr != NULL) {
2622 		frdest_t *fdp;
2623 
2624 		fdp = &fr->fr_tifs[fin->fin_rev];
2625 
2626 		if (!out && (pass & FR_FASTROUTE)) {
2627 			/*
2628 			 * For fastroute rule, no destioation interface defined
2629 			 * so pass NULL as the frdest_t parameter
2630 			 */
2631 			(void) fr_fastroute(m, mp, fin, NULL);
2632 			m = *mp = NULL;
2633 		} else if ((fdp->fd_ifp != NULL) &&
2634 			   (fdp->fd_ifp != (struct ifnet *)-1)) {
2635 			/* this is for to rules: */
2636 			(void) fr_fastroute(m, mp, fin, fdp);
2637 			m = *mp = NULL;
2638 		}
2639 
2640 		/*
2641 		 * Generate a duplicated packet.
2642 		 */
2643 		if (mc != NULL)
2644 			(void) fr_fastroute(mc, &mc, fin, &fr->fr_dif);
2645 	}
2646 
2647 	/*
2648 	 * This late because the likes of fr_fastroute() use fin_fr.
2649 	 */
2650 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2651 
2652 finished:
2653 	if (!FR_ISPASS(pass)) {
2654 		IPF_BUMP(ifs->ifs_frstats[out].fr_block);
2655 		if (*mp != NULL) {
2656 			FREE_MB_T(*mp);
2657 			m = *mp = NULL;
2658 		}
2659 	} else {
2660 		IPF_BUMP(ifs->ifs_frstats[out].fr_pass);
2661 #if defined(_KERNEL) && defined(__sgi)
2662 		if ((fin->fin_hbuf != NULL) &&
2663 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
2664 			COPYBACK(m, 0, fin->fin_plen, fin->fin_hbuf);
2665 		}
2666 #endif
2667 	}
2668 
2669 	SPL_X(s);
2670 
2671 #ifdef _KERNEL
2672 # if OpenBSD >= 200311
2673 	if (FR_ISPASS(pass) && (v == 4)) {
2674 		ip = fin->fin_ip;
2675 		ip->ip_len = ntohs(ip->ip_len);
2676 		ip->ip_off = ntohs(ip->ip_off);
2677 	}
2678 # endif
2679 	return (FR_ISPASS(pass)) ? 0 : fin->fin_error;
2680 #else /* _KERNEL */
2681 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
2682 	if ((pass & FR_NOMATCH) != 0)
2683 		return 1;
2684 
2685 	if ((pass & FR_RETMASK) != 0)
2686 		switch (pass & FR_RETMASK)
2687 		{
2688 		case FR_RETRST :
2689 			return 3;
2690 		case FR_RETICMP :
2691 			return 4;
2692 		case FR_FAKEICMP :
2693 			return 5;
2694 		}
2695 
2696 	switch (pass & FR_CMDMASK)
2697 	{
2698 	case FR_PASS :
2699 		return 0;
2700 	case FR_BLOCK :
2701 		return -1;
2702 	case FR_AUTH :
2703 		return -2;
2704 	case FR_ACCOUNT :
2705 		return -3;
2706 	case FR_PREAUTH :
2707 		return -4;
2708 	}
2709 	return 2;
2710 #endif /* _KERNEL */
2711 }
2712 
2713 
2714 #ifdef	IPFILTER_LOG
2715 /* ------------------------------------------------------------------------ */
2716 /* Function:    fr_dolog                                                    */
2717 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
2718 /* Parameters:  fin(I) - pointer to packet information                      */
2719 /*              passp(IO) - pointer to current/new filter decision (unused) */
2720 /*                                                                          */
2721 /* Checks flags set to see how a packet should be logged, if it is to be    */
2722 /* logged.  Adjust statistics based on its success or not.                  */
2723 /* ------------------------------------------------------------------------ */
2724 frentry_t *fr_dolog(fin, passp)
2725 fr_info_t *fin;
2726 u_32_t *passp;
2727 {
2728 	u_32_t pass;
2729 	int out;
2730 	ipf_stack_t *ifs = fin->fin_ifs;
2731 
2732 	out = fin->fin_out;
2733 	pass = *passp;
2734 
2735 	if ((ifs->ifs_fr_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
2736 		pass |= FF_LOGNOMATCH;
2737 		IPF_BUMP(ifs->ifs_frstats[out].fr_npkl);
2738 		goto logit;
2739 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
2740 	    (FR_ISPASS(pass) && (ifs->ifs_fr_flags & FF_LOGPASS))) {
2741 		if ((pass & FR_LOGMASK) != FR_LOGP)
2742 			pass |= FF_LOGPASS;
2743 		IPF_BUMP(ifs->ifs_frstats[out].fr_ppkl);
2744 		goto logit;
2745 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
2746 		   (FR_ISBLOCK(pass) && (ifs->ifs_fr_flags & FF_LOGBLOCK))) {
2747 		if ((pass & FR_LOGMASK) != FR_LOGB)
2748 			pass |= FF_LOGBLOCK;
2749 		IPF_BUMP(ifs->ifs_frstats[out].fr_bpkl);
2750 logit:
2751 		if (ipflog(fin, pass) == -1) {
2752 			IPF_BUMP(ifs->ifs_frstats[out].fr_skip);
2753 
2754 			/*
2755 			 * If the "or-block" option has been used then
2756 			 * block the packet if we failed to log it.
2757 			 */
2758 			if ((pass & FR_LOGORBLOCK) &&
2759 			    FR_ISPASS(pass)) {
2760 				pass &= ~FR_CMDMASK;
2761 				pass |= FR_BLOCK;
2762 			}
2763 		}
2764 		*passp = pass;
2765 	}
2766 
2767 	return fin->fin_fr;
2768 }
2769 #endif /* IPFILTER_LOG */
2770 
2771 
2772 /* ------------------------------------------------------------------------ */
2773 /* Function:    ipf_cksum                                                   */
2774 /* Returns:     u_short - IP header checksum                                */
2775 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
2776 /*              len(I)  - length of buffer in bytes                         */
2777 /*                                                                          */
2778 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
2779 /*                                                                          */
2780 /* N.B.: addr should be 16bit aligned.                                      */
2781 /* ------------------------------------------------------------------------ */
2782 u_short ipf_cksum(addr, len)
2783 u_short *addr;
2784 int len;
2785 {
2786 	u_32_t sum = 0;
2787 
2788 	for (sum = 0; len > 1; len -= 2)
2789 		sum += *addr++;
2790 
2791 	/* mop up an odd byte, if necessary */
2792 	if (len == 1)
2793 		sum += *(u_char *)addr;
2794 
2795 	/*
2796 	 * add back carry outs from top 16 bits to low 16 bits
2797 	 */
2798 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
2799 	sum += (sum >> 16);			/* add carry */
2800 	return (u_short)(~sum);
2801 }
2802 
2803 
2804 /* ------------------------------------------------------------------------ */
2805 /* Function:    fr_cksum                                                    */
2806 /* Returns:     u_short - layer 4 checksum                                  */
2807 /* Parameters:  m(I  )     - pointer to buffer holding packet               */
2808 /*              ip(I)      - pointer to IP header                           */
2809 /*              l4proto(I) - protocol to caclulate checksum for             */
2810 /*              l4hdr(I)   - pointer to layer 4 header                      */
2811 /*                                                                          */
2812 /* Calculates the TCP checksum for the packet held in "m", using the data   */
2813 /* in the IP header "ip" to seed it.                                        */
2814 /*                                                                          */
2815 /* NB: This function assumes we've pullup'd enough for all of the IP header */
2816 /* and the TCP header.  We also assume that data blocks aren't allocated in */
2817 /* odd sizes.                                                               */
2818 /*                                                                          */
2819 /* Expects ip_len to be in host byte order when called.                     */
2820 /* ------------------------------------------------------------------------ */
2821 u_short fr_cksum(m, ip, l4proto, l4hdr)
2822 mb_t *m;
2823 ip_t *ip;
2824 int l4proto;
2825 void *l4hdr;
2826 {
2827 	u_short *sp, slen, sumsave, l4hlen, *csump;
2828 	u_int sum, sum2;
2829 	int hlen;
2830 #ifdef	USE_INET6
2831 	ip6_t *ip6;
2832 #endif
2833 
2834 	csump = NULL;
2835 	sumsave = 0;
2836 	l4hlen = 0;
2837 	sp = NULL;
2838 	slen = 0;
2839 	hlen = 0;
2840 	sum = 0;
2841 
2842 	/*
2843 	 * Add up IP Header portion
2844 	 */
2845 #ifdef	USE_INET6
2846 	if (IP_V(ip) == 4) {
2847 #endif
2848 		hlen = IP_HL(ip) << 2;
2849 		slen = ip->ip_len - hlen;
2850 		sum = htons((u_short)l4proto);
2851 		sum += htons(slen);
2852 		sp = (u_short *)&ip->ip_src;
2853 		sum += *sp++;	/* ip_src */
2854 		sum += *sp++;
2855 		sum += *sp++;	/* ip_dst */
2856 		sum += *sp++;
2857 #ifdef	USE_INET6
2858 	} else if (IP_V(ip) == 6) {
2859 		ip6 = (ip6_t *)ip;
2860 		hlen = sizeof(*ip6);
2861 		slen = ntohs(ip6->ip6_plen);
2862 		sum = htons((u_short)l4proto);
2863 		sum += htons(slen);
2864 		sp = (u_short *)&ip6->ip6_src;
2865 		sum += *sp++;	/* ip6_src */
2866 		sum += *sp++;
2867 		sum += *sp++;
2868 		sum += *sp++;
2869 		sum += *sp++;
2870 		sum += *sp++;
2871 		sum += *sp++;
2872 		sum += *sp++;
2873 		sum += *sp++;	/* ip6_dst */
2874 		sum += *sp++;
2875 		sum += *sp++;
2876 		sum += *sp++;
2877 		sum += *sp++;
2878 		sum += *sp++;
2879 		sum += *sp++;
2880 		sum += *sp++;
2881 	}
2882 #endif
2883 
2884 	switch (l4proto)
2885 	{
2886 	case IPPROTO_UDP :
2887 		csump = &((udphdr_t *)l4hdr)->uh_sum;
2888 		l4hlen = sizeof(udphdr_t);
2889 		break;
2890 
2891 	case IPPROTO_TCP :
2892 		csump = &((tcphdr_t *)l4hdr)->th_sum;
2893 		l4hlen = sizeof(tcphdr_t);
2894 		break;
2895 	case IPPROTO_ICMP :
2896 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
2897 		l4hlen = 4;
2898 		sum = 0;
2899 		break;
2900 	default :
2901 		break;
2902 	}
2903 
2904 	if (csump != NULL) {
2905 		sumsave = *csump;
2906 		*csump = 0;
2907 	}
2908 
2909 	l4hlen = l4hlen;	/* LINT */
2910 
2911 #ifdef	_KERNEL
2912 # ifdef MENTAT
2913 	{
2914 	void *rp = m->b_rptr;
2915 
2916 	if ((unsigned char *)ip > m->b_rptr && (unsigned char *)ip < m->b_wptr)
2917 		m->b_rptr = (u_char *)ip;
2918 	sum2 = ip_cksum(m, hlen, sum);	/* hlen == offset */
2919 	m->b_rptr = rp;
2920 	sum2 = (sum2 & 0xffff) + (sum2 >> 16);
2921 	sum2 = ~sum2 & 0xffff;
2922 	}
2923 # else /* MENTAT */
2924 #  if defined(BSD) || defined(sun)
2925 #   if BSD >= 199103
2926 	m->m_data += hlen;
2927 #   else
2928 	m->m_off += hlen;
2929 #   endif
2930 	m->m_len -= hlen;
2931 	sum2 = in_cksum(m, slen);
2932 	m->m_len += hlen;
2933 #   if BSD >= 199103
2934 	m->m_data -= hlen;
2935 #   else
2936 	m->m_off -= hlen;
2937 #   endif
2938 	/*
2939 	 * Both sum and sum2 are partial sums, so combine them together.
2940 	 */
2941 	sum += ~sum2 & 0xffff;
2942 	while (sum > 0xffff)
2943 		sum = (sum & 0xffff) + (sum >> 16);
2944 	sum2 = ~sum & 0xffff;
2945 #  else /* defined(BSD) || defined(sun) */
2946 {
2947 	union {
2948 		u_char	c[2];
2949 		u_short	s;
2950 	} bytes;
2951 	u_short len = ip->ip_len;
2952 #   if defined(__sgi)
2953 	int add;
2954 #   endif
2955 
2956 	/*
2957 	 * Add up IP Header portion
2958 	 */
2959 	if (sp != (u_short *)l4hdr)
2960 		sp = (u_short *)l4hdr;
2961 
2962 	switch (l4proto)
2963 	{
2964 	case IPPROTO_UDP :
2965 		sum += *sp++;	/* sport */
2966 		sum += *sp++;	/* dport */
2967 		sum += *sp++;	/* udp length */
2968 		sum += *sp++;	/* checksum */
2969 		break;
2970 
2971 	case IPPROTO_TCP :
2972 		sum += *sp++;	/* sport */
2973 		sum += *sp++;	/* dport */
2974 		sum += *sp++;	/* seq */
2975 		sum += *sp++;
2976 		sum += *sp++;	/* ack */
2977 		sum += *sp++;
2978 		sum += *sp++;	/* off */
2979 		sum += *sp++;	/* win */
2980 		sum += *sp++;	/* checksum */
2981 		sum += *sp++;	/* urp */
2982 		break;
2983 	case IPPROTO_ICMP :
2984 		sum = *sp++;	/* type/code */
2985 		sum += *sp++;	/* checksum */
2986 		break;
2987 	}
2988 
2989 #   ifdef	__sgi
2990 	/*
2991 	 * In case we had to copy the IP & TCP header out of mbufs,
2992 	 * skip over the mbuf bits which are the header
2993 	 */
2994 	if ((caddr_t)ip != mtod(m, caddr_t)) {
2995 		hlen = (caddr_t)sp - (caddr_t)ip;
2996 		while (hlen) {
2997 			add = MIN(hlen, m->m_len);
2998 			sp = (u_short *)(mtod(m, caddr_t) + add);
2999 			hlen -= add;
3000 			if (add == m->m_len) {
3001 				m = m->m_next;
3002 				if (!hlen) {
3003 					if (!m)
3004 						break;
3005 					sp = mtod(m, u_short *);
3006 				}
3007 				PANIC((!m),("fr_cksum(1): not enough data"));
3008 			}
3009 		}
3010 	}
3011 #   endif
3012 
3013 	len -= (l4hlen + hlen);
3014 	if (len <= 0)
3015 		goto nodata;
3016 
3017 	while (len > 1) {
3018 		if (((caddr_t)sp - mtod(m, caddr_t)) >= m->m_len) {
3019 			m = m->m_next;
3020 			PANIC((!m),("fr_cksum(2): not enough data"));
3021 			sp = mtod(m, u_short *);
3022 		}
3023 		if (((caddr_t)(sp + 1) - mtod(m, caddr_t)) > m->m_len) {
3024 			bytes.c[0] = *(u_char *)sp;
3025 			m = m->m_next;
3026 			PANIC((!m),("fr_cksum(3): not enough data"));
3027 			sp = mtod(m, u_short *);
3028 			bytes.c[1] = *(u_char *)sp;
3029 			sum += bytes.s;
3030 			sp = (u_short *)((u_char *)sp + 1);
3031 		}
3032 		if ((u_long)sp & 1) {
3033 			bcopy((char *)sp++, (char *)&bytes.s, sizeof(bytes.s));
3034 			sum += bytes.s;
3035 		} else
3036 			sum += *sp++;
3037 		len -= 2;
3038 	}
3039 
3040 	if (len != 0)
3041 		sum += ntohs(*(u_char *)sp << 8);
3042 nodata:
3043 	while (sum > 0xffff)
3044 		sum = (sum & 0xffff) + (sum >> 16);
3045 	sum2 = (u_short)(~sum & 0xffff);
3046 }
3047 #  endif /*  defined(BSD) || defined(sun) */
3048 # endif /* MENTAT */
3049 #else /* _KERNEL */
3050 	for (; slen > 1; slen -= 2)
3051 	        sum += *sp++;
3052 	if (slen)
3053 		sum += ntohs(*(u_char *)sp << 8);
3054 	while (sum > 0xffff)
3055 		sum = (sum & 0xffff) + (sum >> 16);
3056 	sum2 = (u_short)(~sum & 0xffff);
3057 #endif /* _KERNEL */
3058 	if (csump != NULL)
3059 		*csump = sumsave;
3060 	return sum2;
3061 }
3062 
3063 
3064 #if defined(_KERNEL) && ( ((BSD < 199103) && !defined(MENTAT)) || \
3065     defined(__sgi) ) && !defined(linux) && !defined(_AIX51)
3066 /*
3067  * Copyright (c) 1982, 1986, 1988, 1991, 1993
3068  *	The Regents of the University of California.  All rights reserved.
3069  *
3070  * Redistribution and use in source and binary forms, with or without
3071  * modification, are permitted provided that the following conditions
3072  * are met:
3073  * 1. Redistributions of source code must retain the above copyright
3074  *    notice, this list of conditions and the following disclaimer.
3075  * 2. Redistributions in binary form must reproduce the above copyright
3076  *    notice, this list of conditions and the following disclaimer in the
3077  *    documentation and/or other materials provided with the distribution.
3078  * 3. Neither the name of the University nor the names of its contributors
3079  *    may be used to endorse or promote products derived from this software
3080  *    without specific prior written permission.
3081  *
3082  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3083  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3084  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3085  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3086  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3087  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3088  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3089  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3090  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3091  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3092  * SUCH DAMAGE.
3093  *
3094  *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
3095  * $Id: fil.c,v 2.243.2.64 2005/08/13 05:19:59 darrenr Exp $
3096  */
3097 /*
3098  * Copy data from an mbuf chain starting "off" bytes from the beginning,
3099  * continuing for "len" bytes, into the indicated buffer.
3100  */
3101 void
3102 m_copydata(m, off, len, cp)
3103 	mb_t *m;
3104 	int off;
3105 	int len;
3106 	caddr_t cp;
3107 {
3108 	unsigned count;
3109 
3110 	if (off < 0 || len < 0)
3111 		panic("m_copydata");
3112 	while (off > 0) {
3113 		if (m == 0)
3114 			panic("m_copydata");
3115 		if (off < m->m_len)
3116 			break;
3117 		off -= m->m_len;
3118 		m = m->m_next;
3119 	}
3120 	while (len > 0) {
3121 		if (m == 0)
3122 			panic("m_copydata");
3123 		count = MIN(m->m_len - off, len);
3124 		bcopy(mtod(m, caddr_t) + off, cp, count);
3125 		len -= count;
3126 		cp += count;
3127 		off = 0;
3128 		m = m->m_next;
3129 	}
3130 }
3131 
3132 
3133 /*
3134  * Copy data from a buffer back into the indicated mbuf chain,
3135  * starting "off" bytes from the beginning, extending the mbuf
3136  * chain if necessary.
3137  */
3138 void
3139 m_copyback(m0, off, len, cp)
3140 	struct	mbuf *m0;
3141 	int off;
3142 	int len;
3143 	caddr_t cp;
3144 {
3145 	int mlen;
3146 	struct mbuf *m = m0, *n;
3147 	int totlen = 0;
3148 
3149 	if (m0 == 0)
3150 		return;
3151 	while (off > (mlen = m->m_len)) {
3152 		off -= mlen;
3153 		totlen += mlen;
3154 		if (m->m_next == 0) {
3155 			n = m_getclr(M_DONTWAIT, m->m_type);
3156 			if (n == 0)
3157 				goto out;
3158 			n->m_len = min(MLEN, len + off);
3159 			m->m_next = n;
3160 		}
3161 		m = m->m_next;
3162 	}
3163 	while (len > 0) {
3164 		mlen = min(m->m_len - off, len);
3165 		bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
3166 		cp += mlen;
3167 		len -= mlen;
3168 		mlen += off;
3169 		off = 0;
3170 		totlen += mlen;
3171 		if (len == 0)
3172 			break;
3173 		if (m->m_next == 0) {
3174 			n = m_get(M_DONTWAIT, m->m_type);
3175 			if (n == 0)
3176 				break;
3177 			n->m_len = min(MLEN, len);
3178 			m->m_next = n;
3179 		}
3180 		m = m->m_next;
3181 	}
3182 out:
3183 #if 0
3184 	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
3185 		m->m_pkthdr.len = totlen;
3186 #endif
3187 	return;
3188 }
3189 #endif /* (_KERNEL) && ( ((BSD < 199103) && !MENTAT) || __sgi) */
3190 
3191 
3192 /* ------------------------------------------------------------------------ */
3193 /* Function:    fr_findgroup                                                */
3194 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3195 /* Parameters:  group(I) - group name to search for                         */
3196 /*              unit(I)  - device to which this group belongs               */
3197 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3198 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3199 /*                         to where to add the next (last) group or where   */
3200 /*                         to delete group from.                            */
3201 /*                                                                          */
3202 /* Search amongst the defined groups for a particular group number.         */
3203 /* ------------------------------------------------------------------------ */
3204 frgroup_t *fr_findgroup(group, unit, set, fgpp, ifs)
3205 char *group;
3206 minor_t unit;
3207 int set;
3208 frgroup_t ***fgpp;
3209 ipf_stack_t *ifs;
3210 {
3211 	frgroup_t *fg, **fgp;
3212 
3213 	/*
3214 	 * Which list of groups to search in is dependent on which list of
3215 	 * rules are being operated on.
3216 	 */
3217 	fgp = &ifs->ifs_ipfgroups[unit][set];
3218 
3219 	while ((fg = *fgp) != NULL) {
3220 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3221 			break;
3222 		else
3223 			fgp = &fg->fg_next;
3224 	}
3225 	if (fgpp != NULL)
3226 		*fgpp = fgp;
3227 	return fg;
3228 }
3229 
3230 
3231 /* ------------------------------------------------------------------------ */
3232 /* Function:    fr_addgroup                                                 */
3233 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3234 /*                            != NULL == pointer to the group               */
3235 /* Parameters:  num(I)   - group number to add                              */
3236 /*              head(I)  - rule pointer that is using this as the head      */
3237 /*              flags(I) - rule flags which describe the type of rule it is */
3238 /*              unit(I)  - device to which this group will belong to        */
3239 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3240 /* Write Locks: ipf_mutex                                                   */
3241 /*                                                                          */
3242 /* Add a new group head, or if it already exists, increase the reference    */
3243 /* count to it.                                                             */
3244 /* ------------------------------------------------------------------------ */
3245 frgroup_t *fr_addgroup(group, head, flags, unit, set, ifs)
3246 char *group;
3247 void *head;
3248 u_32_t flags;
3249 minor_t unit;
3250 int set;
3251 ipf_stack_t *ifs;
3252 {
3253 	frgroup_t *fg, **fgp;
3254 	u_32_t gflags;
3255 
3256 	if (group == NULL)
3257 		return NULL;
3258 
3259 	if (unit == IPL_LOGIPF && *group == '\0')
3260 		return NULL;
3261 
3262 	fgp = NULL;
3263 	gflags = flags & FR_INOUT;
3264 
3265 	fg = fr_findgroup(group, unit, set, &fgp, ifs);
3266 	if (fg != NULL) {
3267 		if (fg->fg_flags == 0)
3268 			fg->fg_flags = gflags;
3269 		else if (gflags != fg->fg_flags)
3270 			return NULL;
3271 		fg->fg_ref++;
3272 		return fg;
3273 	}
3274 	KMALLOC(fg, frgroup_t *);
3275 	if (fg != NULL) {
3276 		fg->fg_head = head;
3277 		fg->fg_start = NULL;
3278 		fg->fg_next = *fgp;
3279 		bcopy(group, fg->fg_name, FR_GROUPLEN);
3280 		fg->fg_flags = gflags;
3281 		fg->fg_ref = 1;
3282 		*fgp = fg;
3283 	}
3284 	return fg;
3285 }
3286 
3287 
3288 /* ------------------------------------------------------------------------ */
3289 /* Function:    fr_delgroup                                                 */
3290 /* Returns:     Nil                                                         */
3291 /* Parameters:  group(I) - group name to delete                             */
3292 /*              unit(I)  - device to which this group belongs               */
3293 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3294 /* Write Locks: ipf_mutex                                                   */
3295 /*                                                                          */
3296 /* Attempt to delete a group head.                                          */
3297 /* Only do this when its reference count reaches 0.                         */
3298 /* ------------------------------------------------------------------------ */
3299 void fr_delgroup(group, unit, set, ifs)
3300 char *group;
3301 minor_t unit;
3302 int set;
3303 ipf_stack_t *ifs;
3304 {
3305 	frgroup_t *fg, **fgp;
3306 
3307 	fg = fr_findgroup(group, unit, set, &fgp, ifs);
3308 	if (fg == NULL)
3309 		return;
3310 
3311 	fg->fg_ref--;
3312 	if (fg->fg_ref == 0) {
3313 		*fgp = fg->fg_next;
3314 		KFREE(fg);
3315 	}
3316 }
3317 
3318 
3319 /* ------------------------------------------------------------------------ */
3320 /* Function:    fr_getrulen                                                 */
3321 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3322 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3323 /*              flags(I) - which set of rules to find the rule in           */
3324 /*              group(I) - group name                                       */
3325 /*              n(I)     - rule number to find                              */
3326 /*                                                                          */
3327 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3328 /* group # g doesn't exist or there are less than n rules in the group.     */
3329 /* ------------------------------------------------------------------------ */
3330 frentry_t *fr_getrulen(unit, group, n, ifs)
3331 int unit;
3332 char *group;
3333 u_32_t n;
3334 ipf_stack_t *ifs;
3335 {
3336 	frentry_t *fr;
3337 	frgroup_t *fg;
3338 
3339 	fg = fr_findgroup(group, unit, ifs->ifs_fr_active, NULL, ifs);
3340 	if (fg == NULL)
3341 		return NULL;
3342 	for (fr = fg->fg_head; fr && n; fr = fr->fr_next, n--)
3343 		;
3344 	if (n != 0)
3345 		return NULL;
3346 	return fr;
3347 }
3348 
3349 
3350 /* ------------------------------------------------------------------------ */
3351 /* Function:    fr_rulen                                                    */
3352 /* Returns:     int - >= 0 - rule number, -1 == search failed               */
3353 /* Parameters:  unit(I) - device for which to count the rule's number       */
3354 /*              fr(I)   - pointer to rule to match                          */
3355 /*                                                                          */
3356 /* Return the number for a rule on a specific filtering device.             */
3357 /* ------------------------------------------------------------------------ */
3358 int fr_rulen(unit, fr, ifs)
3359 int unit;
3360 frentry_t *fr;
3361 ipf_stack_t *ifs;
3362 {
3363 	frentry_t *fh;
3364 	frgroup_t *fg;
3365 	u_32_t n = 0;
3366 
3367 	if (fr == NULL)
3368 		return -1;
3369 	fg = fr_findgroup(fr->fr_group, unit, ifs->ifs_fr_active, NULL, ifs);
3370 	if (fg == NULL)
3371 		return -1;
3372 	for (fh = fg->fg_head; fh; n++, fh = fh->fr_next)
3373 		if (fh == fr)
3374 			break;
3375 	if (fh == NULL)
3376 		return -1;
3377 	return n;
3378 }
3379 
3380 
3381 /* ------------------------------------------------------------------------ */
3382 /* Function:    frflushlist                                                 */
3383 /* Returns:     int - >= 0 - number of flushed rules                        */
3384 /* Parameters:  set(I)   - which set of rules (inactive/inactive) this is   */
3385 /*              unit(I)  - device for which to flush rules                  */
3386 /*              flags(I) - which set of rules to flush                      */
3387 /*              nfreedp(O) - pointer to int where flush count is stored     */
3388 /*              listp(I)   - pointer to list to flush pointer               */
3389 /* Write Locks: ipf_mutex                                                   */
3390 /*                                                                          */
3391 /* Recursively flush rules from the list, descending groups as they are     */
3392 /* encountered.  if a rule is the head of a group and it has lost all its   */
3393 /* group members, then also delete the group reference.  nfreedp is needed  */
3394 /* to store the accumulating count of rules removed, whereas the returned   */
3395 /* value is just the number removed from the current list.  The latter is   */
3396 /* needed to correctly adjust reference counts on rules that define groups. */
3397 /*                                                                          */
3398 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3399 /* ------------------------------------------------------------------------ */
3400 static int frflushlist(set, unit, nfreedp, listp, ifs)
3401 int set;
3402 minor_t unit;
3403 int *nfreedp;
3404 frentry_t **listp;
3405 ipf_stack_t *ifs;
3406 {
3407 	int freed = 0;
3408 	frentry_t *fp;
3409 
3410 	while ((fp = *listp) != NULL) {
3411 		if ((fp->fr_type & FR_T_BUILTIN) ||
3412 		    !(fp->fr_flags & FR_COPIED)) {
3413 			listp = &fp->fr_next;
3414 			continue;
3415 		}
3416 		*listp = fp->fr_next;
3417 		if (fp->fr_grp != NULL) {
3418 			(void) frflushlist(set, unit, nfreedp, fp->fr_grp, ifs);
3419 		}
3420 
3421 		if (fp->fr_grhead != NULL) {
3422 			fr_delgroup(fp->fr_grhead, unit, set, ifs);
3423 			*fp->fr_grhead = '\0';
3424 		}
3425 
3426 		ASSERT(fp->fr_ref > 0);
3427 		fp->fr_next = NULL;
3428 		if (fr_derefrule(&fp, ifs) == 0)
3429 			freed++;
3430 	}
3431 	*nfreedp += freed;
3432 	return freed;
3433 }
3434 
3435 
3436 /* ------------------------------------------------------------------------ */
3437 /* Function:    frflush                                                     */
3438 /* Returns:     int - >= 0 - number of flushed rules                        */
3439 /* Parameters:  unit(I)  - device for which to flush rules                  */
3440 /*              flags(I) - which set of rules to flush                      */
3441 /*                                                                          */
3442 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3443 /* and IPv6) as defined by the value of flags.                              */
3444 /* ------------------------------------------------------------------------ */
3445 int frflush(unit, proto, flags, ifs)
3446 minor_t unit;
3447 int proto, flags;
3448 ipf_stack_t *ifs;
3449 {
3450 	int flushed = 0, set;
3451 
3452 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
3453 
3454 	set = ifs->ifs_fr_active;
3455 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3456 		set = 1 - set;
3457 
3458 	if (flags & FR_OUTQUE) {
3459 		if (proto == 0 || proto == 6) {
3460 			(void) frflushlist(set, unit,
3461 			    &flushed, &ifs->ifs_ipfilter6[1][set], ifs);
3462 			(void) frflushlist(set, unit,
3463 			    &flushed, &ifs->ifs_ipacct6[1][set], ifs);
3464 		}
3465 		if (proto == 0 || proto == 4) {
3466 			(void) frflushlist(set, unit,
3467 			    &flushed, &ifs->ifs_ipfilter[1][set], ifs);
3468 			(void) frflushlist(set, unit,
3469 			    &flushed, &ifs->ifs_ipacct[1][set], ifs);
3470 		}
3471 	}
3472 	if (flags & FR_INQUE) {
3473 		if (proto == 0 || proto == 6) {
3474 			(void) frflushlist(set, unit,
3475 			    &flushed, &ifs->ifs_ipfilter6[0][set], ifs);
3476 			(void) frflushlist(set, unit,
3477 			    &flushed, &ifs->ifs_ipacct6[0][set], ifs);
3478 		}
3479 		if (proto == 0 || proto == 4) {
3480 			(void) frflushlist(set, unit,
3481 			    &flushed, &ifs->ifs_ipfilter[0][set], ifs);
3482 			(void) frflushlist(set, unit,
3483 			    &flushed, &ifs->ifs_ipacct[0][set], ifs);
3484 		}
3485 	}
3486 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
3487 
3488 	if (unit == IPL_LOGIPF) {
3489 		int tmp;
3490 
3491 		tmp = frflush(IPL_LOGCOUNT, proto, flags, ifs);
3492 		if (tmp >= 0)
3493 			flushed += tmp;
3494 	}
3495 	return flushed;
3496 }
3497 
3498 
3499 /* ------------------------------------------------------------------------ */
3500 /* Function:    memstr                                                      */
3501 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3502 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3503 /*              dst(I)  - pointer to byte sequence to search                */
3504 /*              slen(I) - match length                                      */
3505 /*              dlen(I) - length available to search in                     */
3506 /*                                                                          */
3507 /* Search dst for a sequence of bytes matching those at src and extend for  */
3508 /* slen bytes.                                                              */
3509 /* ------------------------------------------------------------------------ */
3510 char *memstr(src, dst, slen, dlen)
3511 char *src, *dst;
3512 int slen, dlen;
3513 {
3514 	char *s = NULL;
3515 
3516 	while (dlen >= slen) {
3517 		if (bcmp(src, dst, slen) == 0) {
3518 			s = dst;
3519 			break;
3520 		}
3521 		dst++;
3522 		dlen--;
3523 	}
3524 	return s;
3525 }
3526 /* ------------------------------------------------------------------------ */
3527 /* Function:    fr_fixskip                                                  */
3528 /* Returns:     Nil                                                         */
3529 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3530 /*              rp(I)        - rule added/removed with skip in it.          */
3531 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3532 /*                             depending on whether a rule was just added   */
3533 /*                             or removed.                                  */
3534 /*                                                                          */
3535 /* Adjust all the rules in a list which would have skip'd past the position */
3536 /* where we are inserting to skip to the right place given the change.      */
3537 /* ------------------------------------------------------------------------ */
3538 void fr_fixskip(listp, rp, addremove)
3539 frentry_t **listp, *rp;
3540 int addremove;
3541 {
3542 	int rules, rn;
3543 	frentry_t *fp;
3544 
3545 	rules = 0;
3546 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3547 		rules++;
3548 
3549 	if (!fp)
3550 		return;
3551 
3552 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3553 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3554 			fp->fr_arg += addremove;
3555 }
3556 
3557 
3558 #ifdef	_KERNEL
3559 /* ------------------------------------------------------------------------ */
3560 /* Function:    count4bits                                                  */
3561 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3562 /* Parameters:  ip(I) - 32bit IP address                                    */
3563 /*                                                                          */
3564 /* IPv4 ONLY                                                                */
3565 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3566 /* consecutive 1's is different to that passed, return -1, else return #    */
3567 /* of bits.                                                                 */
3568 /* ------------------------------------------------------------------------ */
3569 int	count4bits(ip)
3570 u_32_t	ip;
3571 {
3572 	u_32_t	ipn;
3573 	int	cnt = 0, i, j;
3574 
3575 	ip = ipn = ntohl(ip);
3576 	for (i = 32; i; i--, ipn *= 2)
3577 		if (ipn & 0x80000000)
3578 			cnt++;
3579 		else
3580 			break;
3581 	ipn = 0;
3582 	for (i = 32, j = cnt; i; i--, j--) {
3583 		ipn *= 2;
3584 		if (j > 0)
3585 			ipn++;
3586 	}
3587 	if (ipn == ip)
3588 		return cnt;
3589 	return -1;
3590 }
3591 
3592 
3593 #ifdef USE_INET6
3594 /* ------------------------------------------------------------------------ */
3595 /* Function:    count6bits                                                  */
3596 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3597 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3598 /*                                                                          */
3599 /* IPv6 ONLY                                                                */
3600 /* count consecutive 1's in bit mask.                                       */
3601 /* ------------------------------------------------------------------------ */
3602 int count6bits(msk)
3603 u_32_t *msk;
3604 {
3605 	int i = 0, k;
3606 	u_32_t j;
3607 
3608 	for (k = 3; k >= 0; k--)
3609 		if (msk[k] == 0xffffffff)
3610 			i += 32;
3611 		else {
3612 			for (j = msk[k]; j; j <<= 1)
3613 				if (j & 0x80000000)
3614 					i++;
3615 		}
3616 	return i;
3617 }
3618 # endif
3619 #endif /* _KERNEL */
3620 
3621 
3622 /* ------------------------------------------------------------------------ */
3623 /* Function:    fr_ifsync                                                   */
3624 /* Returns:     void *    - new interface identifier                        */
3625 /* Parameters:  action(I)  - type of synchronisation to do                  */
3626 /*              v(I)       - IP version being sync'd (v4 or v6)             */
3627 /*              newifp(I)  - interface identifier being introduced/removed  */
3628 /*              oldifp(I)  - interface identifier in a filter rule          */
3629 /*              newname(I) - name associated with newifp interface          */
3630 /*              oldname(I) - name associated with oldifp interface          */
3631 /*		ifs       - pointer to IPF stack instance		    */
3632 /*                                                                          */
3633 /* This function returns what the new value for "oldifp" should be for its  */
3634 /* caller.  In some cases it will not change, in some it will.              */
3635 /* action == IPFSYNC_RESYNC                                                 */
3636 /*   a new value for oldifp will always be looked up, according to oldname, */
3637 /*   the values of newname and newifp are ignored.                          */
3638 /* action == IPFSYNC_NEWIFP                                                 */
3639 /*   if oldname matches newname then we are doing a sync for the matching   */
3640 /*   interface, so we return newifp to be used in place of oldifp.  If the  */
3641 /*   the names don't match, just return oldifp.                             */
3642 /* action == IPFSYNC_OLDIFP                                                 */
3643 /*   if oldifp matches newifp then we are are doing a sync to remove any    */
3644 /*   references to oldifp, so we return "-1".                               */
3645 /* -----								    */
3646 /* NOTE:								    */
3647 /* This function processes NIC event from PF_HOOKS. The action parameter    */
3648 /* is set in ipf_nic_event_v4()/ipf_nic_event_v6() function. There is	    */
3649 /* one single switch statement() in ipf_nic_event_vx() function, which	    */
3650 /* translates the HOOK event type to action parameter passed to fr_ifsync.  */
3651 /* The translation table looks as follows:				    */
3652 /*	event		| action					    */
3653 /*	----------------+-------------					    */
3654 /*	NE_PLUMB	| IPFSYNC_NEWIFP				    */
3655 /*	NE_UNPLUMB	| IPFSYNC_OLDIFP				    */
3656 /*    NE_ADDRESS_CHANGE	| IPFSYNC_RESYNC				    */
3657 /*									    */
3658 /* The oldname and oldifp parameters are taken from IPF entry (rule, state  */
3659 /* table entry, NAT table entry, fragment ...). The newname and newifp	    */
3660 /* parameters come from hook event data, parameters are taken from event    */
3661 /* in ipf_nic_event_vx() functions. Any time NIC changes, the IPF is	    */
3662 /* notified by hook function.						    */
3663 /*									    */
3664 /* We get NE_UNPLUMB event from PF_HOOKS even if someone coincidently tries */
3665 /* to plumb the interface, which is already plumbed. In such case we always */
3666 /* get the event from PF_HOOKS as follows:				    */
3667 /*	event:	NE_PLUMB						    */
3668 /*	NIC:	0x0							    */
3669 /* ------------------------------------------------------------------------ */
3670 static void *fr_ifsync(action, v, newname, oldname, newifp, oldifp, ifs)
3671 int action, v;
3672 char *newname, *oldname;
3673 void *newifp, *oldifp;
3674 ipf_stack_t *ifs;
3675 {
3676 	void *rval = oldifp;
3677 
3678 	switch (action)
3679 	{
3680 	case IPFSYNC_RESYNC :
3681 		if (oldname[0] != '\0') {
3682 			rval = fr_resolvenic(oldname, v, ifs);
3683 		}
3684 		break;
3685 	case IPFSYNC_NEWIFP :
3686 		if (!strncmp(newname, oldname, LIFNAMSIZ))
3687 			rval = newifp;
3688 		break;
3689 	case IPFSYNC_OLDIFP :
3690 		/*
3691 		 * If interface gets unplumbed it must be invalidated, which
3692 		 * means set all existing references to the interface to -1.
3693 		 * We don't want to invalidate references for wildcard
3694 		 * (unbound) rules (entries).
3695 		 */
3696 		if (newifp == oldifp)
3697 			rval = (oldifp) ? (void *)-1 : NULL;
3698 		break;
3699 	}
3700 
3701 	return rval;
3702 }
3703 
3704 
3705 /* ------------------------------------------------------------------------ */
3706 /* Function:    frsynclist                                                  */
3707 /* Returns:     void                                                        */
3708 /* Parameters:  action(I) - type of synchronisation to do                   */
3709 /*              v(I)      - IP version being sync'd (v4 or v6)              */
3710 /*              ifp(I)    - interface identifier associated with action     */
3711 /*              ifname(I) - name associated with ifp parameter              */
3712 /*              fr(I)     - pointer to filter rule                          */
3713 /*		ifs       - pointer to IPF stack instance		    */
3714 /* Write Locks: ipf_mutex                                                   */
3715 /*                                                                          */
3716 /* Walk through a list of filter rules and resolve any interface names into */
3717 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3718 /* used in the rule.  The interface pointer is used to limit the lookups to */
3719 /* a specific set of matching names if it is non-NULL.                      */
3720 /* ------------------------------------------------------------------------ */
3721 static void frsynclist(action, v, ifp, ifname, fr, ifs)
3722 int action, v;
3723 void *ifp;
3724 char *ifname;
3725 frentry_t *fr;
3726 ipf_stack_t *ifs;
3727 {
3728 	frdest_t *fdp;
3729 	int rv, i;
3730 
3731 	for (; fr; fr = fr->fr_next) {
3732 		rv = fr->fr_v;
3733 		if (v != 0 && v != rv)
3734 			continue;
3735 
3736 		/*
3737 		 * Lookup all the interface names that are part of the rule.
3738 		 */
3739 		for (i = 0; i < 4; i++) {
3740 			fr->fr_ifas[i] = fr_ifsync(action, rv, ifname,
3741 						   fr->fr_ifnames[i],
3742 						   ifp, fr->fr_ifas[i],
3743 						   ifs);
3744 		}
3745 
3746 		fdp = &fr->fr_tifs[0];
3747 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3748 					   ifp, fdp->fd_ifp, ifs);
3749 
3750 		fdp = &fr->fr_tifs[1];
3751 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3752 					   ifp, fdp->fd_ifp, ifs);
3753 
3754 		fdp = &fr->fr_dif;
3755 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3756 					   ifp, fdp->fd_ifp, ifs);
3757 
3758 		if (action != IPFSYNC_RESYNC)
3759 			continue;
3760 
3761 		if (fr->fr_type == FR_T_IPF) {
3762 			if (fr->fr_satype != FRI_NORMAL &&
3763 			    fr->fr_satype != FRI_LOOKUP) {
3764 				(void)fr_ifpaddr(rv, fr->fr_satype,
3765 						 fr->fr_ifas[fr->fr_sifpidx],
3766 						 &fr->fr_src, &fr->fr_smsk,
3767 						 ifs);
3768 			}
3769 			if (fr->fr_datype != FRI_NORMAL &&
3770 			    fr->fr_datype != FRI_LOOKUP) {
3771 				(void)fr_ifpaddr(rv, fr->fr_datype,
3772 						 fr->fr_ifas[fr->fr_difpidx],
3773 						 &fr->fr_dst, &fr->fr_dmsk,
3774 						 ifs);
3775 			}
3776 		}
3777 
3778 #ifdef	IPFILTER_LOOKUP
3779 		if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP &&
3780 		    fr->fr_srcptr == NULL) {
3781 			fr->fr_srcptr = fr_resolvelookup(fr->fr_srctype,
3782 							 fr->fr_srcnum,
3783 							 &fr->fr_srcfunc, ifs);
3784 		}
3785 		if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP &&
3786 		    fr->fr_dstptr == NULL) {
3787 			fr->fr_dstptr = fr_resolvelookup(fr->fr_dsttype,
3788 							 fr->fr_dstnum,
3789 							 &fr->fr_dstfunc, ifs);
3790 		}
3791 #endif
3792 	}
3793 }
3794 
3795 
3796 #ifdef	_KERNEL
3797 /* ------------------------------------------------------------------------ */
3798 /* Function:    frsync                                                      */
3799 /* Returns:     void                                                        */
3800 /* Parameters:  action(I) - type of synchronisation to do                   */
3801 /*              v(I)      - IP version being sync'd (v4 or v6)              */
3802 /*              ifp(I)    - interface identifier associated with action     */
3803 /*              name(I)   - name associated with ifp parameter              */
3804 /*                                                                          */
3805 /* frsync() is called when we suspect that the interface list or            */
3806 /* information about interfaces (like IP#) has changed.  Go through all     */
3807 /* filter rules, NAT entries and the state table and check if anything      */
3808 /* needs to be changed/updated.                                             */
3809 /* With the filtering hooks added to Solaris, we needed to change the manner*/
3810 /* in which this was done to support three different types of sync:         */
3811 /* - complete resync of all interface name/identifiers                      */
3812 /* - new interface being announced with its name and identifier             */
3813 /* - interface removal being announced by only its identifier               */
3814 /* ------------------------------------------------------------------------ */
3815 void frsync(action, v, ifp, name, ifs)
3816 int action, v;
3817 void *ifp;
3818 char *name;
3819 ipf_stack_t *ifs;
3820 {
3821 	int i;
3822 
3823 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
3824 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct[0][ifs->ifs_fr_active], ifs);
3825 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct[1][ifs->ifs_fr_active], ifs);
3826 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter[0][ifs->ifs_fr_active], ifs);
3827 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter[1][ifs->ifs_fr_active], ifs);
3828 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct6[0][ifs->ifs_fr_active], ifs);
3829 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct6[1][ifs->ifs_fr_active], ifs);
3830 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter6[0][ifs->ifs_fr_active], ifs);
3831 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter6[1][ifs->ifs_fr_active], ifs);
3832 
3833 	for (i = 0; i < IPL_LOGSIZE; i++) {
3834 		frgroup_t *g;
3835 
3836 		for (g = ifs->ifs_ipfgroups[i][0]; g != NULL; g = g->fg_next)
3837 			frsynclist(action, v, ifp, name, g->fg_start, ifs);
3838 		for (g = ifs->ifs_ipfgroups[i][1]; g != NULL; g = g->fg_next)
3839 			frsynclist(action, v, ifp, name, g->fg_start, ifs);
3840 	}
3841 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
3842 }
3843 
3844 
3845 /*
3846  * In the functions below, bcopy() is called because the pointer being
3847  * copied _from_ in this instance is a pointer to a char buf (which could
3848  * end up being unaligned) and on the kernel's local stack.
3849  */
3850 /* ------------------------------------------------------------------------ */
3851 /* Function:    copyinptr                                                   */
3852 /* Returns:     int - 0 = success, else failure                             */
3853 /* Parameters:  src(I)  - pointer to the source address                     */
3854 /*              dst(I)  - destination address                               */
3855 /*              size(I) - number of bytes to copy                           */
3856 /*                                                                          */
3857 /* Copy a block of data in from user space, given a pointer to the pointer  */
3858 /* to start copying from (src) and a pointer to where to store it (dst).    */
3859 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
3860 /* ------------------------------------------------------------------------ */
3861 int copyinptr(src, dst, size)
3862 void *src, *dst;
3863 size_t size;
3864 {
3865 	caddr_t ca;
3866 	int err;
3867 
3868 # if SOLARIS
3869 	err = COPYIN(src, (caddr_t)&ca, sizeof(ca));
3870 	if (err != 0)
3871 		return err;
3872 # else
3873 	bcopy(src, (caddr_t)&ca, sizeof(ca));
3874 # endif
3875 	err = COPYIN(ca, dst, size);
3876 	return err;
3877 }
3878 
3879 
3880 /* ------------------------------------------------------------------------ */
3881 /* Function:    copyoutptr                                                  */
3882 /* Returns:     int - 0 = success, else failure                             */
3883 /* Parameters:  src(I)  - pointer to the source address                     */
3884 /*              dst(I)  - destination address                               */
3885 /*              size(I) - number of bytes to copy                           */
3886 /*                                                                          */
3887 /* Copy a block of data out to user space, given a pointer to the pointer   */
3888 /* to start copying from (src) and a pointer to where to store it (dst).    */
3889 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
3890 /* ------------------------------------------------------------------------ */
3891 int copyoutptr(src, dst, size)
3892 void *src, *dst;
3893 size_t size;
3894 {
3895 	caddr_t ca;
3896 	int err;
3897 
3898 # if SOLARIS
3899 	err = COPYIN(dst, (caddr_t)&ca, sizeof(ca));
3900 	if (err != 0)
3901 		return err;
3902 # else
3903 	bcopy(dst, (caddr_t)&ca, sizeof(ca));
3904 # endif
3905 	err = COPYOUT(src, ca, size);
3906 	return err;
3907 }
3908 #endif
3909 
3910 
3911 /* ------------------------------------------------------------------------ */
3912 /* Function:    fr_lock                                                     */
3913 /* Returns:	int - 0 = success, else error				    */
3914 /* Parameters:  data(I)  - pointer to lock value to set                     */
3915 /*              lockp(O) - pointer to location to store old lock value      */
3916 /*                                                                          */
3917 /* Get the new value for the lock integer, set it and return the old value  */
3918 /* in *lockp.                                                               */
3919 /* ------------------------------------------------------------------------ */
3920 int fr_lock(data, lockp)
3921 caddr_t data;
3922 int *lockp;
3923 {
3924 	int arg, err;
3925 
3926 	err = BCOPYIN(data, (caddr_t)&arg, sizeof(arg));
3927 	if (err != 0)
3928 		return (EFAULT);
3929 	err = BCOPYOUT((caddr_t)lockp, data, sizeof(*lockp));
3930 	if (err != 0)
3931 		return (EFAULT);
3932 	*lockp = arg;
3933 	return (0);
3934 }
3935 
3936 
3937 /* ------------------------------------------------------------------------ */
3938 /* Function:    fr_getstat                                                  */
3939 /* Returns:     Nil                                                         */
3940 /* Parameters:  fiop(I)  - pointer to ipfilter stats structure              */
3941 /*                                                                          */
3942 /* Stores a copy of current pointers, counters, etc, in the friostat        */
3943 /* structure.                                                               */
3944 /* ------------------------------------------------------------------------ */
3945 void fr_getstat(fiop, ifs)
3946 friostat_t *fiop;
3947 ipf_stack_t *ifs;
3948 {
3949 	int i, j;
3950 
3951 	bcopy((char *)&ifs->ifs_frstats, (char *)fiop->f_st,
3952 	    sizeof(filterstats_t) * 2);
3953 	fiop->f_locks[IPL_LOGSTATE] = ifs->ifs_fr_state_lock;
3954 	fiop->f_locks[IPL_LOGNAT] = ifs->ifs_fr_nat_lock;
3955 	fiop->f_locks[IPL_LOGIPF] = ifs->ifs_fr_frag_lock;
3956 	fiop->f_locks[IPL_LOGAUTH] = ifs->ifs_fr_auth_lock;
3957 
3958 	for (i = 0; i < 2; i++)
3959 		for (j = 0; j < 2; j++) {
3960 			fiop->f_ipf[i][j] = ifs->ifs_ipfilter[i][j];
3961 			fiop->f_acct[i][j] = ifs->ifs_ipacct[i][j];
3962 			fiop->f_ipf6[i][j] = ifs->ifs_ipfilter6[i][j];
3963 			fiop->f_acct6[i][j] = ifs->ifs_ipacct6[i][j];
3964 		}
3965 
3966 	fiop->f_ticks = ifs->ifs_fr_ticks;
3967 	fiop->f_active = ifs->ifs_fr_active;
3968 	fiop->f_froute[0] = ifs->ifs_fr_frouteok[0];
3969 	fiop->f_froute[1] = ifs->ifs_fr_frouteok[1];
3970 
3971 	fiop->f_running = ifs->ifs_fr_running;
3972 	for (i = 0; i < IPL_LOGSIZE; i++) {
3973 		fiop->f_groups[i][0] = ifs->ifs_ipfgroups[i][0];
3974 		fiop->f_groups[i][1] = ifs->ifs_ipfgroups[i][1];
3975 	}
3976 #ifdef  IPFILTER_LOG
3977 	fiop->f_logging = 1;
3978 #else
3979 	fiop->f_logging = 0;
3980 #endif
3981 	fiop->f_defpass = ifs->ifs_fr_pass;
3982 	fiop->f_features = fr_features;
3983 	(void) strncpy(fiop->f_version, ipfilter_version,
3984 		       sizeof(fiop->f_version));
3985 }
3986 
3987 
3988 #ifdef	USE_INET6
3989 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
3990 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
3991 	-1,			/* 1: UNUSED */
3992 	-1,			/* 2: UNUSED */
3993 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
3994 	-1,			/* 4: ICMP_SOURCEQUENCH */
3995 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
3996 	-1,			/* 6: UNUSED */
3997 	-1,			/* 7: UNUSED */
3998 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
3999 	-1,			/* 9: UNUSED */
4000 	-1,			/* 10: UNUSED */
4001 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4002 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4003 	-1,			/* 13: ICMP_TSTAMP */
4004 	-1,			/* 14: ICMP_TSTAMPREPLY */
4005 	-1,			/* 15: ICMP_IREQ */
4006 	-1,			/* 16: ICMP_IREQREPLY */
4007 	-1,			/* 17: ICMP_MASKREQ */
4008 	-1,			/* 18: ICMP_MASKREPLY */
4009 };
4010 
4011 
4012 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4013 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4014 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4015 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4016 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4017 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4018 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4019 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4020 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4021 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4022 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4023 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4024 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4025 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4026 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4027 };
4028 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4029 #endif
4030 
4031 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4032 
4033 
4034 /* ------------------------------------------------------------------------ */
4035 /* Function:    fr_matchicmpqueryreply                                      */
4036 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4037 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4038 /*              ic(I)   - ICMP information                                  */
4039 /*              icmp(I) - ICMP packet header                                */
4040 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4041 /*                                                                          */
4042 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4043 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4044 /* else return 0 for no match.                                              */
4045 /* ------------------------------------------------------------------------ */
4046 int fr_matchicmpqueryreply(v, ic, icmp, rev)
4047 int v;
4048 icmpinfo_t *ic;
4049 icmphdr_t *icmp;
4050 int rev;
4051 {
4052 	int ictype;
4053 
4054 	ictype = ic->ici_type;
4055 
4056 	if (v == 4) {
4057 		/*
4058 		 * If we matched its type on the way in, then when going out
4059 		 * it will still be the same type.
4060 		 */
4061 		if ((!rev && (icmp->icmp_type == ictype)) ||
4062 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4063 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4064 				return 1;
4065 			if (icmp->icmp_id == ic->ici_id)
4066 				return 1;
4067 		}
4068 	}
4069 #ifdef	USE_INET6
4070 	else if (v == 6) {
4071 		if ((!rev && (icmp->icmp_type == ictype)) ||
4072 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4073 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4074 				return 1;
4075 			if (icmp->icmp_id == ic->ici_id)
4076 				return 1;
4077 		}
4078 	}
4079 #endif
4080 	return 0;
4081 }
4082 
4083 
4084 #ifdef	IPFILTER_LOOKUP
4085 /* ------------------------------------------------------------------------ */
4086 /* Function:    fr_resolvelookup                                            */
4087 /* Returns:     void * - NULL = failure, else success.                      */
4088 /* Parameters:  type(I)     - type of lookup these parameters are for.      */
4089 /*              number(I)   - table number to use when searching            */
4090 /*              funcptr(IO) - pointer to pointer for storing IP address     */
4091 /*                           searching function.                            */
4092 /*                                                                          */
4093 /* Search for the "table" number passed in amongst those configured for     */
4094 /* that particular type.  If the type is recognised then the function to    */
4095 /* call to do the IP address search will be change, regardless of whether   */
4096 /* or not the "table" number exists.                                        */
4097 /* ------------------------------------------------------------------------ */
4098 static void *fr_resolvelookup(type, number, funcptr, ifs)
4099 u_int type, number;
4100 lookupfunc_t *funcptr;
4101 ipf_stack_t *ifs;
4102 {
4103 	char name[FR_GROUPLEN];
4104 	iphtable_t *iph;
4105 	ip_pool_t *ipo;
4106 	void *ptr;
4107 
4108 #if defined(SNPRINTF) && defined(_KERNEL)
4109 	(void) SNPRINTF(name, sizeof(name), "%u", number);
4110 #else
4111 	(void) sprintf(name, "%u", number);
4112 #endif
4113 
4114 	READ_ENTER(&ifs->ifs_ip_poolrw);
4115 
4116 	switch (type)
4117 	{
4118 	case IPLT_POOL :
4119 # if (defined(__osf__) && defined(_KERNEL))
4120 		ptr = NULL;
4121 		*funcptr = NULL;
4122 # else
4123 		ipo = ip_pool_find(IPL_LOGIPF, name, ifs);
4124 		ptr = ipo;
4125 		if (ipo != NULL) {
4126 			ATOMIC_INC32(ipo->ipo_ref);
4127 		}
4128 		*funcptr = ip_pool_search;
4129 # endif
4130 		break;
4131 	case IPLT_HASH :
4132 		iph = fr_findhtable(IPL_LOGIPF, name, ifs);
4133 		ptr = iph;
4134 		if (iph != NULL) {
4135 			ATOMIC_INC32(iph->iph_ref);
4136 		}
4137 		*funcptr = fr_iphmfindip;
4138 		break;
4139 	default:
4140 		ptr = NULL;
4141 		*funcptr = NULL;
4142 		break;
4143 	}
4144 	RWLOCK_EXIT(&ifs->ifs_ip_poolrw);
4145 
4146 	return ptr;
4147 }
4148 #endif
4149 
4150 
4151 /* ------------------------------------------------------------------------ */
4152 /* Function:    frrequest                                                   */
4153 /* Returns:     int - 0 == success, > 0 == errno value                      */
4154 /* Parameters:  unit(I)     - device for which this is for                  */
4155 /*              req(I)      - ioctl command (SIOC*)                         */
4156 /*              data(I)     - pointr to ioctl data                          */
4157 /*              set(I)      - 1 or 0 (filter set)                           */
4158 /*              makecopy(I) - flag indicating whether data points to a rule */
4159 /*                            in kernel space & hence doesn't need copying. */
4160 /*                                                                          */
4161 /* This function handles all the requests which operate on the list of      */
4162 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4163 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4164 /* names are resolved here and other sanity checks are made on the content  */
4165 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4166 /* then make sure they are created and initialised before exiting.          */
4167 /* ------------------------------------------------------------------------ */
4168 int frrequest(unit, req, data, set, makecopy, ifs)
4169 int unit;
4170 ioctlcmd_t req;
4171 int set, makecopy;
4172 caddr_t data;
4173 ipf_stack_t *ifs;
4174 {
4175 	frentry_t frd, *fp, *f, **fprev, **ftail;
4176 	int error = 0, in, v;
4177 	void *ptr, *uptr;
4178 	u_int *p, *pp;
4179 	frgroup_t *fg;
4180 	char *group;
4181 
4182 	fg = NULL;
4183 	fp = &frd;
4184 	if (makecopy != 0) {
4185 		error = fr_inobj(data, fp, IPFOBJ_FRENTRY);
4186 		if (error)
4187 			return EFAULT;
4188 		if ((fp->fr_flags & FR_T_BUILTIN) != 0)
4189 			return EINVAL;
4190 		fp->fr_ref = 0;
4191 		fp->fr_flags |= FR_COPIED;
4192 	} else {
4193 		fp = (frentry_t *)data;
4194 		if ((fp->fr_type & FR_T_BUILTIN) == 0)
4195 			return EINVAL;
4196 		fp->fr_flags &= ~FR_COPIED;
4197 	}
4198 
4199 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4200 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL)))
4201 		return EINVAL;
4202 
4203 	v = fp->fr_v;
4204 	uptr = fp->fr_data;
4205 
4206 	/*
4207 	 * Only filter rules for IPv4 or IPv6 are accepted.
4208 	 */
4209 	if (v == 4)
4210 		/*EMPTY*/;
4211 #ifdef	USE_INET6
4212 	else if (v == 6)
4213 		/*EMPTY*/;
4214 #endif
4215 	else {
4216 		return EINVAL;
4217 	}
4218 
4219 	/*
4220 	 * If the rule is being loaded from user space, i.e. we had to copy it
4221 	 * into kernel space, then do not trust the function pointer in the
4222 	 * rule.
4223 	 */
4224 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4225 		if (fr_findfunc(fp->fr_func) == NULL)
4226 			return ESRCH;
4227 		error = fr_funcinit(fp, ifs);
4228 		if (error != 0)
4229 			return error;
4230 	}
4231 
4232 	ptr = NULL;
4233 	/*
4234 	 * Check that the group number does exist and that its use (in/out)
4235 	 * matches what the rule is.
4236 	 */
4237 	if (!strncmp(fp->fr_grhead, "0", FR_GROUPLEN))
4238 		*fp->fr_grhead = '\0';
4239 	group = fp->fr_group;
4240 	if (!strncmp(group, "0", FR_GROUPLEN))
4241 		*group = '\0';
4242 
4243 	if (FR_ISACCOUNT(fp->fr_flags))
4244 		unit = IPL_LOGCOUNT;
4245 
4246 	if ((req != (int)SIOCZRLST) && (*group != '\0')) {
4247 		fg = fr_findgroup(group, unit, set, NULL, ifs);
4248 		if (fg == NULL)
4249 			return ESRCH;
4250 		if (fg->fg_flags == 0)
4251 			fg->fg_flags = fp->fr_flags & FR_INOUT;
4252 		else if (fg->fg_flags != (fp->fr_flags & FR_INOUT))
4253 			return ESRCH;
4254 	}
4255 
4256 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4257 
4258 	/*
4259 	 * Work out which rule list this change is being applied to.
4260 	 */
4261 	ftail = NULL;
4262 	fprev = NULL;
4263 	if (unit == IPL_LOGAUTH)
4264 		fprev = &ifs->ifs_ipauth;
4265 	else if (v == 4) {
4266 		if (FR_ISACCOUNT(fp->fr_flags))
4267 			fprev = &ifs->ifs_ipacct[in][set];
4268 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4269 			fprev = &ifs->ifs_ipfilter[in][set];
4270 	} else if (v == 6) {
4271 		if (FR_ISACCOUNT(fp->fr_flags))
4272 			fprev = &ifs->ifs_ipacct6[in][set];
4273 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4274 			fprev = &ifs->ifs_ipfilter6[in][set];
4275 	}
4276 	if (fprev == NULL)
4277 		return ESRCH;
4278 
4279 	if (*group != '\0') {
4280 	    if (!fg && !(fg = fr_findgroup(group, unit, set, NULL, ifs)))
4281 			return ESRCH;
4282 		fprev = &fg->fg_start;
4283 	}
4284 
4285 	ftail = fprev;
4286 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4287 		if (fp->fr_collect <= f->fr_collect) {
4288 			ftail = fprev;
4289 			f = NULL;
4290 			break;
4291 		}
4292 		fprev = ftail;
4293 	}
4294 
4295 	/*
4296 	 * Copy in extra data for the rule.
4297 	 */
4298 	if (fp->fr_dsize != 0) {
4299 		if (makecopy != 0) {
4300 			KMALLOCS(ptr, void *, fp->fr_dsize);
4301 			if (!ptr)
4302 				return ENOMEM;
4303 			error = COPYIN(uptr, ptr, fp->fr_dsize);
4304 		} else {
4305 			ptr = uptr;
4306 			error = 0;
4307 		}
4308 		if (error != 0) {
4309 			KFREES(ptr, fp->fr_dsize);
4310 			return ENOMEM;
4311 		}
4312 		fp->fr_data = ptr;
4313 	} else
4314 		fp->fr_data = NULL;
4315 
4316 	/*
4317 	 * Perform per-rule type sanity checks of their members.
4318 	 */
4319 	switch (fp->fr_type & ~FR_T_BUILTIN)
4320 	{
4321 #if defined(IPFILTER_BPF)
4322 	case FR_T_BPFOPC :
4323 		if (fp->fr_dsize == 0)
4324 			return EINVAL;
4325 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4326 			if (makecopy && fp->fr_data != NULL) {
4327 				KFREES(fp->fr_data, fp->fr_dsize);
4328 			}
4329 			return EINVAL;
4330 		}
4331 		break;
4332 #endif
4333 	case FR_T_IPF :
4334 		if (fp->fr_dsize != sizeof(fripf_t))
4335 			return EINVAL;
4336 
4337 		/*
4338 		 * Allowing a rule with both "keep state" and "with oow" is
4339 		 * pointless because adding a state entry to the table will
4340 		 * fail with the out of window (oow) flag set.
4341 		 */
4342 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW))
4343 			return EINVAL;
4344 
4345 		switch (fp->fr_satype)
4346 		{
4347 		case FRI_BROADCAST :
4348 		case FRI_DYNAMIC :
4349 		case FRI_NETWORK :
4350 		case FRI_NETMASKED :
4351 		case FRI_PEERADDR :
4352 			if (fp->fr_sifpidx < 0 || fp->fr_sifpidx > 3) {
4353 				if (makecopy && fp->fr_data != NULL) {
4354 					KFREES(fp->fr_data, fp->fr_dsize);
4355 				}
4356 				return EINVAL;
4357 			}
4358 			break;
4359 #ifdef	IPFILTER_LOOKUP
4360 		case FRI_LOOKUP :
4361 			fp->fr_srcptr = fr_resolvelookup(fp->fr_srctype,
4362 							 fp->fr_srcnum,
4363 							 &fp->fr_srcfunc, ifs);
4364 			break;
4365 #endif
4366 		default :
4367 			break;
4368 		}
4369 
4370 		switch (fp->fr_datype)
4371 		{
4372 		case FRI_BROADCAST :
4373 		case FRI_DYNAMIC :
4374 		case FRI_NETWORK :
4375 		case FRI_NETMASKED :
4376 		case FRI_PEERADDR :
4377 			if (fp->fr_difpidx < 0 || fp->fr_difpidx > 3) {
4378 				if (makecopy && fp->fr_data != NULL) {
4379 					KFREES(fp->fr_data, fp->fr_dsize);
4380 				}
4381 				return EINVAL;
4382 			}
4383 			break;
4384 #ifdef	IPFILTER_LOOKUP
4385 		case FRI_LOOKUP :
4386 			fp->fr_dstptr = fr_resolvelookup(fp->fr_dsttype,
4387 							 fp->fr_dstnum,
4388 							 &fp->fr_dstfunc, ifs);
4389 			break;
4390 #endif
4391 		default :
4392 			break;
4393 		}
4394 		break;
4395 	case FR_T_NONE :
4396 		break;
4397 	case FR_T_CALLFUNC :
4398 		break;
4399 	case FR_T_COMPIPF :
4400 		break;
4401 	default :
4402 		if (makecopy && fp->fr_data != NULL) {
4403 			KFREES(fp->fr_data, fp->fr_dsize);
4404 		}
4405 		return EINVAL;
4406 	}
4407 
4408 	/*
4409 	 * Lookup all the interface names that are part of the rule.
4410 	 */
4411 	frsynclist(0, 0, NULL, NULL, fp, ifs);
4412 	fp->fr_statecnt = 0;
4413 
4414 	/*
4415 	 * Look for an existing matching filter rule, but don't include the
4416 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4417 	 * This elminates rules which are indentical being loaded.  Checksum
4418 	 * the constant part of the filter rule to make comparisons quicker
4419 	 * (this meaning no pointers are included).
4420 	 */
4421 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4422 	     p < pp; p++)
4423 		fp->fr_cksum += *p;
4424 	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4425 	for (p = (u_int *)fp->fr_data; p < pp; p++)
4426 		fp->fr_cksum += *p;
4427 
4428 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
4429 
4430 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4431 		if ((fp->fr_cksum != f->fr_cksum) ||
4432 		    (f->fr_dsize != fp->fr_dsize))
4433 			continue;
4434 		if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func, FR_CMPSIZ))
4435 			continue;
4436 		if ((!ptr && !f->fr_data) ||
4437 		    (ptr && f->fr_data &&
4438 		     !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4439 			break;
4440 	}
4441 
4442 	/*
4443 	 * If zero'ing statistics, copy current to caller and zero.
4444 	 */
4445 	if (req == (ioctlcmd_t)SIOCZRLST) {
4446 		if (f == NULL)
4447 			error = ESRCH;
4448 		else {
4449 			/*
4450 			 * Copy and reduce lock because of impending copyout.
4451 			 * Well we should, but if we do then the atomicity of
4452 			 * this call and the correctness of fr_hits and
4453 			 * fr_bytes cannot be guaranteed.  As it is, this code
4454 			 * only resets them to 0 if they are successfully
4455 			 * copied out into user space.
4456 			 */
4457 			bcopy((char *)f, (char *)fp, sizeof(*f));
4458 
4459 			/*
4460 			 * When we copy this rule back out, set the data
4461 			 * pointer to be what it was in user space.
4462 			 */
4463 			fp->fr_data = uptr;
4464 			error = fr_outobj(data, fp, IPFOBJ_FRENTRY);
4465 
4466 			if (error == 0) {
4467 				if ((f->fr_dsize != 0) && (uptr != NULL))
4468 					error = COPYOUT(f->fr_data, uptr,
4469 							f->fr_dsize);
4470 				if (error == 0) {
4471 					f->fr_hits = 0;
4472 					f->fr_bytes = 0;
4473 				}
4474 			}
4475 		}
4476 
4477 		if ((ptr != NULL) && (makecopy != 0)) {
4478 			KFREES(ptr, fp->fr_dsize);
4479 		}
4480 		RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
4481 		return error;
4482 	}
4483 
4484 	if (!f) {
4485 		/*
4486 		 * At the end of this, ftail must point to the place where the
4487 		 * new rule is to be saved/inserted/added.
4488 		 * For SIOCAD*FR, this should be the last rule in the group of
4489 		 * rules that have equal fr_collect fields.
4490 		 * For SIOCIN*FR, ...
4491 		 */
4492 		if (req == (ioctlcmd_t)SIOCADAFR ||
4493 		    req == (ioctlcmd_t)SIOCADIFR) {
4494 
4495 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4496 				if (f->fr_collect > fp->fr_collect)
4497 					break;
4498 				ftail = &f->fr_next;
4499 			}
4500 			f = NULL;
4501 			ptr = NULL;
4502 			error = 0;
4503 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4504 			   req == (ioctlcmd_t)SIOCINIFR) {
4505 			while ((f = *fprev) != NULL) {
4506 				if (f->fr_collect >= fp->fr_collect)
4507 					break;
4508 				fprev = &f->fr_next;
4509 			}
4510 			ftail = fprev;
4511 			if (fp->fr_hits != 0) {
4512 				while (fp->fr_hits && (f = *ftail)) {
4513 					if (f->fr_collect != fp->fr_collect)
4514 						break;
4515 					fprev = ftail;
4516 					ftail = &f->fr_next;
4517 					fp->fr_hits--;
4518 				}
4519 			}
4520 			f = NULL;
4521 			ptr = NULL;
4522 			error = 0;
4523 		}
4524 	}
4525 
4526 	/*
4527 	 * Request to remove a rule.
4528 	 */
4529 	if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR) {
4530 		if (!f)
4531 			error = ESRCH;
4532 		else {
4533 			/*
4534 			 * Do not allow activity from user space to interfere
4535 			 * with rules not loaded that way.
4536 			 */
4537 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4538 				error = EPERM;
4539 				goto done;
4540 			}
4541 
4542 			/*
4543 			 * Return EBUSY if the rule is being reference by
4544 			 * something else (eg state information.
4545 			 */
4546 			if (f->fr_ref > 1) {
4547 				error = EBUSY;
4548 				goto done;
4549 			}
4550 #ifdef	IPFILTER_SCAN
4551 			if (f->fr_isctag[0] != '\0' &&
4552 			    (f->fr_isc != (struct ipscan *)-1))
4553 				ipsc_detachfr(f);
4554 #endif
4555 			if (unit == IPL_LOGAUTH) {
4556 				error = fr_preauthcmd(req, f, ftail, ifs);
4557 				goto done;
4558 			}
4559 			if (*f->fr_grhead != '\0')
4560 				fr_delgroup(f->fr_grhead, unit, set, ifs);
4561 			fr_fixskip(ftail, f, -1);
4562 			*ftail = f->fr_next;
4563 			f->fr_next = NULL;
4564 			(void)fr_derefrule(&f, ifs);
4565 		}
4566 	} else {
4567 		/*
4568 		 * Not removing, so we must be adding/inserting a rule.
4569 		 */
4570 		if (f)
4571 			error = EEXIST;
4572 		else {
4573 			if (unit == IPL_LOGAUTH) {
4574 				error = fr_preauthcmd(req, fp, ftail, ifs);
4575 				goto done;
4576 			}
4577 			if (makecopy) {
4578 				KMALLOC(f, frentry_t *);
4579 			} else
4580 				f = fp;
4581 			if (f != NULL) {
4582 				if (fp != f)
4583 					bcopy((char *)fp, (char *)f,
4584 					      sizeof(*f));
4585 				MUTEX_NUKE(&f->fr_lock);
4586 				MUTEX_INIT(&f->fr_lock, "filter rule lock");
4587 #ifdef	IPFILTER_SCAN
4588 				if (f->fr_isctag[0] != '\0' &&
4589 				    ipsc_attachfr(f))
4590 					f->fr_isc = (struct ipscan *)-1;
4591 #endif
4592 				f->fr_hits = 0;
4593 				if (makecopy != 0)
4594 					f->fr_ref = 1;
4595 				f->fr_next = *ftail;
4596 				*ftail = f;
4597 				if (req == (ioctlcmd_t)SIOCINIFR ||
4598 				    req == (ioctlcmd_t)SIOCINAFR)
4599 					fr_fixskip(ftail, f, 1);
4600 				f->fr_grp = NULL;
4601 				group = f->fr_grhead;
4602 				if (*group != '\0') {
4603 					fg = fr_addgroup(group, f, f->fr_flags,
4604 							 unit, set, ifs);
4605 					if (fg != NULL)
4606 						f->fr_grp = &fg->fg_start;
4607 				}
4608 			} else
4609 				error = ENOMEM;
4610 		}
4611 	}
4612 done:
4613 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
4614 	if ((ptr != NULL) && (error != 0) && (makecopy != 0)) {
4615 		KFREES(ptr, fp->fr_dsize);
4616 	}
4617 	return (error);
4618 }
4619 
4620 
4621 /* ------------------------------------------------------------------------ */
4622 /* Function:    fr_funcinit                                                 */
4623 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
4624 /* Parameters:  fr(I) - pointer to filter rule                              */
4625 /*                                                                          */
4626 /* If a rule is a call rule, then check if the function it points to needs  */
4627 /* an init function to be called now the rule has been loaded.              */
4628 /* ------------------------------------------------------------------------ */
4629 static int fr_funcinit(fr, ifs)
4630 frentry_t *fr;
4631 ipf_stack_t *ifs;
4632 {
4633 	ipfunc_resolve_t *ft;
4634 	int err;
4635 
4636 	err = ESRCH;
4637 
4638 	for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4639 		if (ft->ipfu_addr == fr->fr_func) {
4640 			err = 0;
4641 			if (ft->ipfu_init != NULL)
4642 				err = (*ft->ipfu_init)(fr, ifs);
4643 			break;
4644 		}
4645 	return err;
4646 }
4647 
4648 
4649 /* ------------------------------------------------------------------------ */
4650 /* Function:    fr_findfunc                                                 */
4651 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
4652 /* Parameters:  funcptr(I) - function pointer to lookup                     */
4653 /*                                                                          */
4654 /* Look for a function in the table of known functions.                     */
4655 /* ------------------------------------------------------------------------ */
4656 static ipfunc_t fr_findfunc(funcptr)
4657 ipfunc_t funcptr;
4658 {
4659 	ipfunc_resolve_t *ft;
4660 
4661 	for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4662 		if (ft->ipfu_addr == funcptr)
4663 			return funcptr;
4664 	return NULL;
4665 }
4666 
4667 
4668 /* ------------------------------------------------------------------------ */
4669 /* Function:    fr_resolvefunc                                              */
4670 /* Returns:     int - 0 == success, else error                              */
4671 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
4672 /*                                                                          */
4673 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
4674 /* This will either be the function name (if the pointer is set) or the     */
4675 /* function pointer if the name is set.  When found, fill in the other one  */
4676 /* so that the entire, complete, structure can be copied back to user space.*/
4677 /* ------------------------------------------------------------------------ */
4678 int fr_resolvefunc(data)
4679 void *data;
4680 {
4681 	ipfunc_resolve_t res, *ft;
4682 	int err;
4683 
4684 	err = BCOPYIN(data, &res, sizeof(res));
4685 	if (err != 0)
4686 		return EFAULT;
4687 
4688 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
4689 		for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4690 			if (strncmp(res.ipfu_name, ft->ipfu_name,
4691 				    sizeof(res.ipfu_name)) == 0) {
4692 				res.ipfu_addr = ft->ipfu_addr;
4693 				res.ipfu_init = ft->ipfu_init;
4694 				if (COPYOUT(&res, data, sizeof(res)) != 0)
4695 					return EFAULT;
4696 				return 0;
4697 			}
4698 	}
4699 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
4700 		for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4701 			if (ft->ipfu_addr == res.ipfu_addr) {
4702 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
4703 					       sizeof(res.ipfu_name));
4704 				res.ipfu_init = ft->ipfu_init;
4705 				if (COPYOUT(&res, data, sizeof(res)) != 0)
4706 					return EFAULT;
4707 				return 0;
4708 			}
4709 	}
4710 	return ESRCH;
4711 }
4712 
4713 
4714 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__FreeBSD__)) || \
4715     (defined(__FreeBSD__) && (__FreeBSD_version < 490000)) || \
4716     (defined(__NetBSD__) && (__NetBSD_Version__ < 105000000)) || \
4717     (defined(__OpenBSD__) && (OpenBSD < 200006))
4718 /*
4719  * From: NetBSD
4720  * ppsratecheck(): packets (or events) per second limitation.
4721  */
4722 int
4723 ppsratecheck(lasttime, curpps, maxpps)
4724 	struct timeval *lasttime;
4725 	int *curpps;
4726 	int maxpps;	/* maximum pps allowed */
4727 {
4728 	struct timeval tv, delta;
4729 	int rv;
4730 
4731 	GETKTIME(&tv);
4732 
4733 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
4734 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
4735 	if (delta.tv_usec < 0) {
4736 		delta.tv_sec--;
4737 		delta.tv_usec += 1000000;
4738 	}
4739 
4740 	/*
4741 	 * check for 0,0 is so that the message will be seen at least once.
4742 	 * if more than one second have passed since the last update of
4743 	 * lasttime, reset the counter.
4744 	 *
4745 	 * we do increment *curpps even in *curpps < maxpps case, as some may
4746 	 * try to use *curpps for stat purposes as well.
4747 	 */
4748 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
4749 	    delta.tv_sec >= 1) {
4750 		*lasttime = tv;
4751 		*curpps = 0;
4752 		rv = 1;
4753 	} else if (maxpps < 0)
4754 		rv = 1;
4755 	else if (*curpps < maxpps)
4756 		rv = 1;
4757 	else
4758 		rv = 0;
4759 	*curpps = *curpps + 1;
4760 
4761 	return (rv);
4762 }
4763 #endif
4764 
4765 
4766 /* ------------------------------------------------------------------------ */
4767 /* Function:    fr_derefrule                                                */
4768 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
4769 /* Parameters:  fr(I) - pointer to filter rule                              */
4770 /*                                                                          */
4771 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
4772 /* free it and any associated storage space being used by it.               */
4773 /* ------------------------------------------------------------------------ */
4774 int fr_derefrule(frp, ifs)
4775 frentry_t **frp;
4776 ipf_stack_t *ifs;
4777 {
4778 	frentry_t *fr;
4779 
4780 	fr = *frp;
4781 
4782 	MUTEX_ENTER(&fr->fr_lock);
4783 	fr->fr_ref--;
4784 	if (fr->fr_ref == 0) {
4785 		MUTEX_EXIT(&fr->fr_lock);
4786 		MUTEX_DESTROY(&fr->fr_lock);
4787 
4788 #ifdef IPFILTER_LOOKUP
4789 		if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP)
4790 		    ip_lookup_deref(fr->fr_srctype, fr->fr_srcptr, ifs);
4791 		if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP)
4792 		    ip_lookup_deref(fr->fr_dsttype, fr->fr_dstptr, ifs);
4793 #endif
4794 
4795 		if (fr->fr_dsize) {
4796 			KFREES(fr->fr_data, fr->fr_dsize);
4797 		}
4798 		if ((fr->fr_flags & FR_COPIED) != 0) {
4799 			KFREE(fr);
4800 			return 0;
4801 		}
4802 		return 1;
4803 	} else {
4804 		MUTEX_EXIT(&fr->fr_lock);
4805 	}
4806 	*frp = NULL;
4807 	return -1;
4808 }
4809 
4810 
4811 #ifdef	IPFILTER_LOOKUP
4812 /* ------------------------------------------------------------------------ */
4813 /* Function:    fr_grpmapinit                                               */
4814 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
4815 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
4816 /*                                                                          */
4817 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
4818 /* fr_ptr is later used by fr_srcgrpmap and fr_dstgrpmap.                   */
4819 /* ------------------------------------------------------------------------ */
4820 static int fr_grpmapinit(fr, ifs)
4821 frentry_t *fr;
4822 ipf_stack_t *ifs;
4823 {
4824 	char name[FR_GROUPLEN];
4825 	iphtable_t *iph;
4826 
4827 #if defined(SNPRINTF) && defined(_KERNEL)
4828 	(void) SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
4829 #else
4830 	(void) sprintf(name, "%d", fr->fr_arg);
4831 #endif
4832 	iph = fr_findhtable(IPL_LOGIPF, name, ifs);
4833 	if (iph == NULL)
4834 		return ESRCH;
4835 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT))
4836 		return ESRCH;
4837 	fr->fr_ptr = iph;
4838 	return 0;
4839 }
4840 
4841 
4842 /* ------------------------------------------------------------------------ */
4843 /* Function:    fr_srcgrpmap                                                */
4844 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
4845 /* Parameters:  fin(I)    - pointer to packet information                   */
4846 /*              passp(IO) - pointer to current/new filter decision (unused) */
4847 /*                                                                          */
4848 /* Look for a rule group head in a hash table, using the source address as  */
4849 /* the key, and descend into that group and continue matching rules against */
4850 /* the packet.                                                              */
4851 /* ------------------------------------------------------------------------ */
4852 frentry_t *fr_srcgrpmap(fin, passp)
4853 fr_info_t *fin;
4854 u_32_t *passp;
4855 {
4856 	frgroup_t *fg;
4857 	void *rval;
4858 	ipf_stack_t *ifs = fin->fin_ifs;
4859 
4860 	rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, fin->fin_v, &fin->fin_src, ifs);
4861 	if (rval == NULL)
4862 		return NULL;
4863 
4864 	fg = rval;
4865 	fin->fin_fr = fg->fg_start;
4866 	(void) fr_scanlist(fin, *passp);
4867 	return fin->fin_fr;
4868 }
4869 
4870 
4871 /* ------------------------------------------------------------------------ */
4872 /* Function:    fr_dstgrpmap                                                */
4873 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
4874 /* Parameters:  fin(I)    - pointer to packet information                   */
4875 /*              passp(IO) - pointer to current/new filter decision (unused) */
4876 /*                                                                          */
4877 /* Look for a rule group head in a hash table, using the destination        */
4878 /* address as the key, and descend into that group and continue matching    */
4879 /* rules against  the packet.                                               */
4880 /* ------------------------------------------------------------------------ */
4881 frentry_t *fr_dstgrpmap(fin, passp)
4882 fr_info_t *fin;
4883 u_32_t *passp;
4884 {
4885 	frgroup_t *fg;
4886 	void *rval;
4887 	ipf_stack_t *ifs = fin->fin_ifs;
4888 
4889 	rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, fin->fin_v, &fin->fin_dst, ifs);
4890 	if (rval == NULL)
4891 		return NULL;
4892 
4893 	fg = rval;
4894 	fin->fin_fr = fg->fg_start;
4895 	(void) fr_scanlist(fin, *passp);
4896 	return fin->fin_fr;
4897 }
4898 #endif /* IPFILTER_LOOKUP */
4899 
4900 /*
4901  * Queue functions
4902  * ===============
4903  * These functions manage objects on queues for efficient timeouts.  There are
4904  * a number of system defined queues as well as user defined timeouts.  It is
4905  * expected that a lock is held in the domain in which the queue belongs
4906  * (i.e. either state or NAT) when calling any of these functions that prevents
4907  * fr_freetimeoutqueue() from being called at the same time as any other.
4908  */
4909 
4910 
4911 /* ------------------------------------------------------------------------ */
4912 /* Function:    fr_addtimeoutqueue                                          */
4913 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
4914 /*                               timeout queue with given interval.         */
4915 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
4916 /*                           of interface queues.                           */
4917 /*              seconds(I) - timeout value in seconds for this queue.       */
4918 /*                                                                          */
4919 /* This routine first looks for a timeout queue that matches the interval   */
4920 /* being requested.  If it finds one, increments the reference counter and  */
4921 /* returns a pointer to it.  If none are found, it allocates a new one and  */
4922 /* inserts it at the top of the list.                                       */
4923 /*                                                                          */
4924 /* Locking.                                                                 */
4925 /* It is assumed that the caller of this function has an appropriate lock   */
4926 /* held (exclusively) in the domain that encompases 'parent'.               */
4927 /* ------------------------------------------------------------------------ */
4928 ipftq_t *fr_addtimeoutqueue(parent, seconds, ifs)
4929 ipftq_t **parent;
4930 u_int seconds;
4931 ipf_stack_t *ifs;
4932 {
4933 	ipftq_t *ifq;
4934 	u_int period;
4935 
4936 	period = seconds * IPF_HZ_DIVIDE;
4937 
4938 	MUTEX_ENTER(&ifs->ifs_ipf_timeoutlock);
4939 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
4940 		if (ifq->ifq_ttl == period) {
4941 			/*
4942 			 * Reset the delete flag, if set, so the structure
4943 			 * gets reused rather than freed and reallocated.
4944 			 */
4945 			MUTEX_ENTER(&ifq->ifq_lock);
4946 			ifq->ifq_flags &= ~IFQF_DELETE;
4947 			ifq->ifq_ref++;
4948 			MUTEX_EXIT(&ifq->ifq_lock);
4949 			MUTEX_EXIT(&ifs->ifs_ipf_timeoutlock);
4950 
4951 			return ifq;
4952 		}
4953 	}
4954 
4955 	KMALLOC(ifq, ipftq_t *);
4956 	if (ifq != NULL) {
4957 		ifq->ifq_ttl = period;
4958 		ifq->ifq_head = NULL;
4959 		ifq->ifq_tail = &ifq->ifq_head;
4960 		ifq->ifq_next = *parent;
4961 		ifq->ifq_pnext = parent;
4962 		ifq->ifq_ref = 1;
4963 		ifq->ifq_flags = IFQF_USER;
4964 		*parent = ifq;
4965 		ifs->ifs_fr_userifqs++;
4966 		MUTEX_NUKE(&ifq->ifq_lock);
4967 		MUTEX_INIT(&ifq->ifq_lock, "ipftq mutex");
4968 	}
4969 	MUTEX_EXIT(&ifs->ifs_ipf_timeoutlock);
4970 	return ifq;
4971 }
4972 
4973 
4974 /* ------------------------------------------------------------------------ */
4975 /* Function:    fr_deletetimeoutqueue                                       */
4976 /* Returns:     int    - new reference count value of the timeout queue     */
4977 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
4978 /* Locks:       ifq->ifq_lock                                               */
4979 /*                                                                          */
4980 /* This routine must be called when we're discarding a pointer to a timeout */
4981 /* queue object, taking care of the reference counter.                      */
4982 /*                                                                          */
4983 /* Now that this just sets a DELETE flag, it requires the expire code to    */
4984 /* check the list of user defined timeout queues and call the free function */
4985 /* below (currently commented out) to stop memory leaking.  It is done this */
4986 /* way because the locking may not be sufficient to safely do a free when   */
4987 /* this function is called.                                                 */
4988 /* ------------------------------------------------------------------------ */
4989 int fr_deletetimeoutqueue(ifq)
4990 ipftq_t *ifq;
4991 {
4992 
4993 	ifq->ifq_ref--;
4994 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
4995 		ifq->ifq_flags |= IFQF_DELETE;
4996 	}
4997 
4998 	return ifq->ifq_ref;
4999 }
5000 
5001 
5002 /* ------------------------------------------------------------------------ */
5003 /* Function:    fr_freetimeoutqueue                                         */
5004 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5005 /* Returns:     Nil                                                         */
5006 /*                                                                          */
5007 /* Locking:                                                                 */
5008 /* It is assumed that the caller of this function has an appropriate lock   */
5009 /* held (exclusively) in the domain that encompases the callers "domain".   */
5010 /* The ifq_lock for this structure should not be held.                      */
5011 /*                                                                          */
5012 /* Remove a user definde timeout queue from the list of queues it is in and */
5013 /* tidy up after this is done.                                              */
5014 /* ------------------------------------------------------------------------ */
5015 void fr_freetimeoutqueue(ifq, ifs)
5016 ipftq_t *ifq;
5017 ipf_stack_t *ifs;
5018 {
5019 
5020 
5021 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5022 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5023 		printf("fr_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5024 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5025 		       ifq->ifq_ref);
5026 		return;
5027 	}
5028 
5029 	/*
5030 	 * Remove from its position in the list.
5031 	 */
5032 	*ifq->ifq_pnext = ifq->ifq_next;
5033 	if (ifq->ifq_next != NULL)
5034 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5035 
5036 	MUTEX_DESTROY(&ifq->ifq_lock);
5037 	ifs->ifs_fr_userifqs--;
5038 	KFREE(ifq);
5039 }
5040 
5041 
5042 /* ------------------------------------------------------------------------ */
5043 /* Function:    fr_deletequeueentry                                         */
5044 /* Returns:     Nil                                                         */
5045 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5046 /*              ifq(I) - timeout queue to remove entry from                 */
5047 /*                                                                          */
5048 /* Remove a tail queue entry from its queue and make it an orphan.          */
5049 /* fr_deletetimeoutqueue is called to make sure the reference count on the  */
5050 /* queue is correct.  We can't, however, call fr_freetimeoutqueue because   */
5051 /* the correct lock(s) may not be held that would make it safe to do so.    */
5052 /* ------------------------------------------------------------------------ */
5053 void fr_deletequeueentry(tqe)
5054 ipftqent_t *tqe;
5055 {
5056 	ipftq_t *ifq;
5057 
5058 	ifq = tqe->tqe_ifq;
5059 	if (ifq == NULL)
5060 		return;
5061 
5062 	MUTEX_ENTER(&ifq->ifq_lock);
5063 
5064 	if (tqe->tqe_pnext != NULL) {
5065 		*tqe->tqe_pnext = tqe->tqe_next;
5066 		if (tqe->tqe_next != NULL)
5067 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5068 		else    /* we must be the tail anyway */
5069 			ifq->ifq_tail = tqe->tqe_pnext;
5070 
5071 		tqe->tqe_pnext = NULL;
5072 		tqe->tqe_ifq = NULL;
5073 	}
5074 
5075 	(void) fr_deletetimeoutqueue(ifq);
5076 
5077 	MUTEX_EXIT(&ifq->ifq_lock);
5078 }
5079 
5080 
5081 /* ------------------------------------------------------------------------ */
5082 /* Function:    fr_queuefront                                               */
5083 /* Returns:     Nil                                                         */
5084 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5085 /*                                                                          */
5086 /* Move a queue entry to the front of the queue, if it isn't already there. */
5087 /* ------------------------------------------------------------------------ */
5088 void fr_queuefront(tqe)
5089 ipftqent_t *tqe;
5090 {
5091 	ipftq_t *ifq;
5092 
5093 	ifq = tqe->tqe_ifq;
5094 	if (ifq == NULL)
5095 		return;
5096 
5097 	MUTEX_ENTER(&ifq->ifq_lock);
5098 	if (ifq->ifq_head != tqe) {
5099 		*tqe->tqe_pnext = tqe->tqe_next;
5100 		if (tqe->tqe_next)
5101 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5102 		else
5103 			ifq->ifq_tail = tqe->tqe_pnext;
5104 
5105 		tqe->tqe_next = ifq->ifq_head;
5106 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5107 		ifq->ifq_head = tqe;
5108 		tqe->tqe_pnext = &ifq->ifq_head;
5109 	}
5110 	MUTEX_EXIT(&ifq->ifq_lock);
5111 }
5112 
5113 
5114 /* ------------------------------------------------------------------------ */
5115 /* Function:    fr_queueback                                                */
5116 /* Returns:     Nil                                                         */
5117 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5118 /*                                                                          */
5119 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5120 /* ------------------------------------------------------------------------ */
5121 void fr_queueback(tqe, ifs)
5122 ipftqent_t *tqe;
5123 ipf_stack_t *ifs;
5124 {
5125 	ipftq_t *ifq;
5126 
5127 	ifq = tqe->tqe_ifq;
5128 	if (ifq == NULL)
5129 		return;
5130 	tqe->tqe_die = ifs->ifs_fr_ticks + ifq->ifq_ttl;
5131 
5132 	MUTEX_ENTER(&ifq->ifq_lock);
5133 	if (tqe->tqe_next == NULL) {		/* at the end already ? */
5134 		MUTEX_EXIT(&ifq->ifq_lock);
5135 		return;
5136 	}
5137 
5138 	/*
5139 	 * Remove from list
5140 	 */
5141 	*tqe->tqe_pnext = tqe->tqe_next;
5142 	tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5143 
5144 	/*
5145 	 * Make it the last entry.
5146 	 */
5147 	tqe->tqe_next = NULL;
5148 	tqe->tqe_pnext = ifq->ifq_tail;
5149 	*ifq->ifq_tail = tqe;
5150 	ifq->ifq_tail = &tqe->tqe_next;
5151 	MUTEX_EXIT(&ifq->ifq_lock);
5152 }
5153 
5154 
5155 /* ------------------------------------------------------------------------ */
5156 /* Function:    fr_queueappend                                              */
5157 /* Returns:     Nil                                                         */
5158 /* Parameters:  tqe(I)    - pointer to timeout queue entry                  */
5159 /*              ifq(I)    - pointer to timeout queue                        */
5160 /*              parent(I) - owing object pointer                            */
5161 /*                                                                          */
5162 /* Add a new item to this queue and put it on the very end.                 */
5163 /* ------------------------------------------------------------------------ */
5164 void fr_queueappend(tqe, ifq, parent, ifs)
5165 ipftqent_t *tqe;
5166 ipftq_t *ifq;
5167 void *parent;
5168 ipf_stack_t *ifs;
5169 {
5170 
5171 	MUTEX_ENTER(&ifq->ifq_lock);
5172 	tqe->tqe_parent = parent;
5173 	tqe->tqe_pnext = ifq->ifq_tail;
5174 	*ifq->ifq_tail = tqe;
5175 	ifq->ifq_tail = &tqe->tqe_next;
5176 	tqe->tqe_next = NULL;
5177 	tqe->tqe_ifq = ifq;
5178 	tqe->tqe_die = ifs->ifs_fr_ticks + ifq->ifq_ttl;
5179 	ifq->ifq_ref++;
5180 	MUTEX_EXIT(&ifq->ifq_lock);
5181 }
5182 
5183 
5184 /* ------------------------------------------------------------------------ */
5185 /* Function:    fr_movequeue                                                */
5186 /* Returns:     Nil                                                         */
5187 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5188 /*              oifp(I) - old timeout queue entry was on                    */
5189 /*              nifp(I) - new timeout queue to put entry on                 */
5190 /*		ifs	- ipf stack instance				    */
5191 /*                                                                          */
5192 /* Move a queue entry from one timeout queue to another timeout queue.      */
5193 /* If it notices that the current entry is already last and does not need   */
5194 /* to move queue, the return.                                               */
5195 /* ------------------------------------------------------------------------ */
5196 void fr_movequeue(tqe, oifq, nifq, ifs)
5197 ipftqent_t *tqe;
5198 ipftq_t *oifq, *nifq;
5199 ipf_stack_t *ifs;
5200 {
5201 	/*
5202 	 * If the queue isn't changing, and the clock hasn't ticked
5203 	 * since the last update, the operation will be a no-op.
5204 	 */
5205 	if (oifq == nifq && tqe->tqe_touched == ifs->ifs_fr_ticks)
5206 		return;
5207 
5208 	/*
5209 	 * Grab the lock and update the timers.
5210 	 */
5211 	MUTEX_ENTER(&oifq->ifq_lock);
5212 	tqe->tqe_touched = ifs->ifs_fr_ticks;
5213 	tqe->tqe_die = ifs->ifs_fr_ticks + nifq->ifq_ttl;
5214 
5215 	/*
5216 	 * The remainder of the operation can still be a no-op.
5217 	 *
5218 	 * If the queue isn't changing, check to see if
5219 	 * an update would be meaningless.
5220 	 */
5221 	if (oifq == nifq) {
5222 		if ((tqe->tqe_next == NULL) ||
5223 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5224 			MUTEX_EXIT(&oifq->ifq_lock);
5225 			return;
5226 		}
5227 	}
5228 
5229 	/*
5230 	 * Remove from the old queue
5231 	 */
5232 	*tqe->tqe_pnext = tqe->tqe_next;
5233 	if (tqe->tqe_next)
5234 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5235 	else
5236 		oifq->ifq_tail = tqe->tqe_pnext;
5237 	tqe->tqe_next = NULL;
5238 
5239 	/*
5240 	 * If we're moving from one queue to another, release the lock on the
5241 	 * old queue and get a lock on the new queue.  For user defined queues,
5242 	 * if we're moving off it, call delete in case it can now be freed.
5243 	 */
5244 	if (oifq != nifq) {
5245 		tqe->tqe_ifq = NULL;
5246 
5247 		(void) fr_deletetimeoutqueue(oifq);
5248 
5249 		MUTEX_EXIT(&oifq->ifq_lock);
5250 
5251 		MUTEX_ENTER(&nifq->ifq_lock);
5252 
5253 		tqe->tqe_ifq = nifq;
5254 		nifq->ifq_ref++;
5255 	}
5256 
5257 	/*
5258 	 * Add to the bottom of the new queue
5259 	 */
5260 	tqe->tqe_pnext = nifq->ifq_tail;
5261 	*nifq->ifq_tail = tqe;
5262 	nifq->ifq_tail = &tqe->tqe_next;
5263 	MUTEX_EXIT(&nifq->ifq_lock);
5264 }
5265 
5266 
5267 /* ------------------------------------------------------------------------ */
5268 /* Function:    fr_updateipid                                               */
5269 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
5270 /* Parameters:  fin(I) - pointer to packet information                      */
5271 /*                                                                          */
5272 /* When we are doing NAT, change the IP of every packet to represent a      */
5273 /* single sequence of packets coming from the host, hiding any host         */
5274 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5275 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5276 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5277 /* has no match in the cache, return an error.                              */
5278 /* ------------------------------------------------------------------------ */
5279 static INLINE int fr_updateipid(fin)
5280 fr_info_t *fin;
5281 {
5282 	u_short id, ido, sums;
5283 	u_32_t sumd, sum;
5284 	ip_t *ip;
5285 
5286 	if (fin->fin_off != 0) {
5287 		sum = fr_ipid_knownfrag(fin);
5288 		if (sum == 0xffffffff)
5289 			return -1;
5290 		sum &= 0xffff;
5291 		id = (u_short)sum;
5292 	} else {
5293 		id = fr_nextipid(fin);
5294 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5295 			(void) fr_ipid_newfrag(fin, (u_32_t)id);
5296 	}
5297 
5298 	ip = fin->fin_ip;
5299 	ido = ntohs(ip->ip_id);
5300 	if (id == ido)
5301 		return 0;
5302 	ip->ip_id = htons(id);
5303 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5304 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5305 	sum += sumd;
5306 	sum = (sum >> 16) + (sum & 0xffff);
5307 	sum = (sum >> 16) + (sum & 0xffff);
5308 	sums = ~(u_short)sum;
5309 	ip->ip_sum = htons(sums);
5310 	return 0;
5311 }
5312 
5313 
5314 #ifdef	NEED_FRGETIFNAME
5315 /* ------------------------------------------------------------------------ */
5316 /* Function:    fr_getifname                                                */
5317 /* Returns:     char *    - pointer to interface name                       */
5318 /* Parameters:  ifp(I)    - pointer to network interface                    */
5319 /*              buffer(O) - pointer to where to store interface name        */
5320 /*                                                                          */
5321 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5322 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
5323 /* as a NULL pointer then return a pointer to a static array.               */
5324 /* ------------------------------------------------------------------------ */
5325 char *fr_getifname(ifp, buffer)
5326 struct ifnet *ifp;
5327 char *buffer;
5328 {
5329 	static char namebuf[LIFNAMSIZ];
5330 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5331      defined(__sgi) || defined(linux) || defined(_AIX51) || \
5332      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5333 	int unit, space;
5334 	char temp[20];
5335 	char *s;
5336 # endif
5337 
5338 	ASSERT(buffer != NULL);
5339 #ifdef notdef
5340 	if (buffer == NULL)
5341 		buffer = namebuf;
5342 #endif
5343 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5344 	buffer[LIFNAMSIZ - 1] = '\0';
5345 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5346      defined(__sgi) || defined(_AIX51) || \
5347      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5348 	for (s = buffer; *s; s++)
5349 		;
5350 	unit = ifp->if_unit;
5351 	space = LIFNAMSIZ - (s - buffer);
5352 	if (space > 0) {
5353 #  if defined(SNPRINTF) && defined(_KERNEL)
5354 		(void) SNPRINTF(temp, sizeof(temp), "%d", unit);
5355 #  else
5356 		(void) sprintf(temp, "%d", unit);
5357 #  endif
5358 		(void) strncpy(s, temp, space);
5359 	}
5360 # endif
5361 	return buffer;
5362 }
5363 #endif
5364 
5365 
5366 /* ------------------------------------------------------------------------ */
5367 /* Function:    fr_ioctlswitch                                              */
5368 /* Returns:     int     - -1 continue processing, else ioctl return value   */
5369 /* Parameters:  unit(I) - device unit opened                                */
5370 /*              data(I) - pointer to ioctl data                             */
5371 /*              cmd(I)  - ioctl command                                     */
5372 /*              mode(I) - mode value                                        */
5373 /*                                                                          */
5374 /* Based on the value of unit, call the appropriate ioctl handler or return */
5375 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
5376 /* for the device in order to execute the ioctl.                            */
5377 /* ------------------------------------------------------------------------ */
5378 INLINE int fr_ioctlswitch(unit, data, cmd, mode, uid, ctx, ifs)
5379 int unit, mode, uid;
5380 ioctlcmd_t cmd;
5381 void *data, *ctx;
5382 ipf_stack_t *ifs;
5383 {
5384 	int error = 0;
5385 
5386 	switch (unit)
5387 	{
5388 	case IPL_LOGIPF :
5389 		error = -1;
5390 		break;
5391 	case IPL_LOGNAT :
5392 		if (ifs->ifs_fr_running > 0)
5393 			error = fr_nat_ioctl(data, cmd, mode, uid, ctx, ifs);
5394 		else
5395 			error = EIO;
5396 		break;
5397 	case IPL_LOGSTATE :
5398 		if (ifs->ifs_fr_running > 0)
5399 			error = fr_state_ioctl(data, cmd, mode, uid, ctx, ifs);
5400 		else
5401 			error = EIO;
5402 		break;
5403 	case IPL_LOGAUTH :
5404 		if (ifs->ifs_fr_running > 0) {
5405 			if ((cmd == (ioctlcmd_t)SIOCADAFR) ||
5406 			    (cmd == (ioctlcmd_t)SIOCRMAFR)) {
5407 				if (!(mode & FWRITE)) {
5408 					error = EPERM;
5409 				} else {
5410 					error = frrequest(unit, cmd, data,
5411 						  ifs->ifs_fr_active, 1, ifs);
5412 				}
5413 			} else {
5414 				error = fr_auth_ioctl(data, cmd, mode, uid, ctx, ifs);
5415 			}
5416 		} else
5417 			error = EIO;
5418 		break;
5419 	case IPL_LOGSYNC :
5420 #ifdef IPFILTER_SYNC
5421 		if (ifs->ifs_fr_running > 0)
5422 			error = fr_sync_ioctl(data, cmd, mode, ifs);
5423 		else
5424 #endif
5425 			error = EIO;
5426 		break;
5427 	case IPL_LOGSCAN :
5428 #ifdef IPFILTER_SCAN
5429 		if (ifs->ifs_fr_running > 0)
5430 			error = fr_scan_ioctl(data, cmd, mode, ifs);
5431 		else
5432 #endif
5433 			error = EIO;
5434 		break;
5435 	case IPL_LOGLOOKUP :
5436 #ifdef IPFILTER_LOOKUP
5437 		if (ifs->ifs_fr_running > 0)
5438 			error = ip_lookup_ioctl(data, cmd, mode, uid, ctx, ifs);
5439 		else
5440 #endif
5441 			error = EIO;
5442 		break;
5443 	default :
5444 		error = EIO;
5445 		break;
5446 	}
5447 
5448 	return error;
5449 }
5450 
5451 
5452 /*
5453  * This array defines the expected size of objects coming into the kernel
5454  * for the various recognised object types.
5455  */
5456 #define	NUM_OBJ_TYPES	19
5457 
5458 static	int	fr_objbytes[NUM_OBJ_TYPES][2] = {
5459 	{ 1,	sizeof(struct frentry) },		/* frentry */
5460 	{ 0,	sizeof(struct friostat) },
5461 	{ 0,	sizeof(struct fr_info) },
5462 	{ 0,	sizeof(struct fr_authstat) },
5463 	{ 0,	sizeof(struct ipfrstat) },
5464 	{ 0,	sizeof(struct ipnat) },
5465 	{ 0,	sizeof(struct natstat) },
5466 	{ 0,	sizeof(struct ipstate_save) },
5467 	{ 1,	sizeof(struct nat_save) },		/* nat_save */
5468 	{ 0,	sizeof(struct natlookup) },
5469 	{ 1,	sizeof(struct ipstate) },		/* ipstate */
5470 	{ 0,	sizeof(struct ips_stat) },
5471 	{ 0,	sizeof(struct frauth) },
5472 	{ 0,	sizeof(struct ipftune) },
5473 	{ 0,	sizeof(struct nat) },                   /* nat_t */
5474 	{ 0,	sizeof(struct ipfruleiter) },
5475 	{ 0,	sizeof(struct ipfgeniter) },
5476 	{ 0,	sizeof(struct ipftable) },
5477 	{ 0,	sizeof(struct ipflookupiter) }
5478 };
5479 
5480 
5481 /* ------------------------------------------------------------------------ */
5482 /* Function:    fr_inobj                                                    */
5483 /* Returns:     int     - 0 = success, else failure                         */
5484 /* Parameters:  data(I) - pointer to ioctl data                             */
5485 /*              ptr(I)  - pointer to store real data in                     */
5486 /*              type(I) - type of structure being moved                     */
5487 /*                                                                          */
5488 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
5489 /* add things to check for version numbers, sizes, etc, to make it backward */
5490 /* compatible at the ABI for user land.                                     */
5491 /* ------------------------------------------------------------------------ */
5492 int fr_inobj(data, ptr, type)
5493 void *data;
5494 void *ptr;
5495 int type;
5496 {
5497 	ipfobj_t obj;
5498 	int error = 0;
5499 
5500 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5501 		return EINVAL;
5502 
5503 	error = BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5504 	if (error != 0)
5505 		return EFAULT;
5506 
5507 	if (obj.ipfo_type != type)
5508 		return EINVAL;
5509 
5510 #ifndef	IPFILTER_COMPAT
5511 	if ((fr_objbytes[type][0] & 1) != 0) {
5512 		if (obj.ipfo_size < fr_objbytes[type][1])
5513 			return EINVAL;
5514 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5515 		return EINVAL;
5516 #else
5517 	if (obj.ipfo_rev != IPFILTER_VERSION) {
5518 		error = fr_incomptrans(&obj, ptr);
5519 		return error;
5520 	}
5521 
5522 	if ((fr_objbytes[type][0] & 1) != 0 &&
5523 	    obj.ipfo_size < fr_objbytes[type][1] ||
5524 	    obj.ipfo_size != fr_objbytes[type][1])
5525 		return EINVAL;
5526 #endif
5527 
5528 	if ((fr_objbytes[type][0] & 1) != 0) {
5529 		error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5530 				fr_objbytes[type][1]);
5531 	} else {
5532 		error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5533 				obj.ipfo_size);
5534 	}
5535 	return error;
5536 }
5537 
5538 
5539 /* ------------------------------------------------------------------------ */
5540 /* Function:    fr_inobjsz                                                  */
5541 /* Returns:     int     - 0 = success, else failure                         */
5542 /* Parameters:  data(I) - pointer to ioctl data                             */
5543 /*              ptr(I)  - pointer to store real data in                     */
5544 /*              type(I) - type of structure being moved                     */
5545 /*              sz(I)   - size of data to copy                              */
5546 /*                                                                          */
5547 /* As per fr_inobj, except the size of the object to copy in is passed in   */
5548 /* but it must not be smaller than the size defined for the type and the    */
5549 /* type must allow for varied sized objects.  The extra requirement here is */
5550 /* that sz must match the size of the object being passed in - this is not  */
5551 /* not possible nor required in fr_inobj().                                 */
5552 /* ------------------------------------------------------------------------ */
5553 int fr_inobjsz(data, ptr, type, sz)
5554 void *data;
5555 void *ptr;
5556 int type, sz;
5557 {
5558 	ipfobj_t obj;
5559 	int error;
5560 
5561 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5562 		return EINVAL;
5563 	if (((fr_objbytes[type][0] & 1) == 0) || (sz < fr_objbytes[type][1]))
5564 		return EINVAL;
5565 
5566 	error = BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5567 	if (error != 0)
5568 		return EFAULT;
5569 
5570 	if (obj.ipfo_type != type)
5571 		return EINVAL;
5572 
5573 #ifndef	IPFILTER_COMPAT
5574 	if (obj.ipfo_size != sz)
5575 		return EINVAL;
5576 #else
5577 	if (obj.ipfo_rev != IPFILTER_VERSION)
5578 		/*XXX compatibility hook here */
5579 		/*EMPTY*/;
5580 	if (obj.ipfo_size != sz)
5581 		/* XXX compatibility hook here */
5582 		return EINVAL;
5583 #endif
5584 
5585 	error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr, sz);
5586 	return error;
5587 }
5588 
5589 
5590 /* ------------------------------------------------------------------------ */
5591 /* Function:    fr_outobjsz                                                 */
5592 /* Returns:     int     - 0 = success, else failure                         */
5593 /* Parameters:  data(I) - pointer to ioctl data                             */
5594 /*              ptr(I)  - pointer to store real data in                     */
5595 /*              type(I) - type of structure being moved                     */
5596 /*              sz(I)   - size of data to copy                              */
5597 /*                                                                          */
5598 /* As per fr_outobj, except the size of the object to copy out is passed in */
5599 /* but it must not be smaller than the size defined for the type and the    */
5600 /* type must allow for varied sized objects.  The extra requirement here is */
5601 /* that sz must match the size of the object being passed in - this is not  */
5602 /* not possible nor required in fr_outobj().                                */
5603 /* ------------------------------------------------------------------------ */
5604 int fr_outobjsz(data, ptr, type, sz)
5605 void *data;
5606 void *ptr;
5607 int type, sz;
5608 {
5609 	ipfobj_t obj;
5610 	int error;
5611 
5612 	if ((type < 0) || (type > NUM_OBJ_TYPES-1) ||
5613 	    ((fr_objbytes[type][0] & 1) == 0) ||
5614 	    (sz < fr_objbytes[type][1]))
5615 		return EINVAL;
5616 
5617 	error = BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5618 	if (error != 0)
5619 		return EFAULT;
5620 
5621 	if (obj.ipfo_type != type)
5622 		return EINVAL;
5623 
5624 #ifndef	IPFILTER_COMPAT
5625 	if (obj.ipfo_size != sz)
5626 		return EINVAL;
5627 #else
5628 	if (obj.ipfo_rev != IPFILTER_VERSION)
5629 		/* XXX compatibility hook here */
5630 		/*EMPTY*/;
5631 	if (obj.ipfo_size != sz)
5632 		/* XXX compatibility hook here */
5633 		return EINVAL;
5634 #endif
5635 
5636 	error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, sz);
5637 	return error;
5638 }
5639 
5640 
5641 /* ------------------------------------------------------------------------ */
5642 /* Function:    fr_outobj                                                   */
5643 /* Returns:     int     - 0 = success, else failure                         */
5644 /* Parameters:  data(I) - pointer to ioctl data                             */
5645 /*              ptr(I)  - pointer to store real data in                     */
5646 /*              type(I) - type of structure being moved                     */
5647 /*                                                                          */
5648 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
5649 /* future, we add things to check for version numbers, sizes, etc, to make  */
5650 /* it backward  compatible at the ABI for user land.                        */
5651 /* ------------------------------------------------------------------------ */
5652 int fr_outobj(data, ptr, type)
5653 void *data;
5654 void *ptr;
5655 int type;
5656 {
5657 	ipfobj_t obj;
5658 	int error;
5659 
5660 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5661 		return EINVAL;
5662 
5663 	error = BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5664 	if (error != 0)
5665 		return EFAULT;
5666 
5667 	if (obj.ipfo_type != type)
5668 		return EINVAL;
5669 
5670 #ifndef	IPFILTER_COMPAT
5671 	if ((fr_objbytes[type][0] & 1) != 0) {
5672 		if (obj.ipfo_size < fr_objbytes[type][1])
5673 			return EINVAL;
5674 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5675 		return EINVAL;
5676 #else
5677 	if (obj.ipfo_rev != IPFILTER_VERSION) {
5678 		error = fr_outcomptrans(&obj, ptr);
5679 		return error;
5680 	}
5681 
5682 	if ((fr_objbytes[type][0] & 1) != 0 &&
5683 	    obj.ipfo_size < fr_objbytes[type][1] ||
5684 	    obj.ipfo_size != fr_objbytes[type][1])
5685 		return EINVAL;
5686 #endif
5687 
5688 	error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, obj.ipfo_size);
5689 	return error;
5690 }
5691 
5692 
5693 /* ------------------------------------------------------------------------ */
5694 /* Function:    fr_checkl4sum                                               */
5695 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
5696 /* Parameters:  fin(I) - pointer to packet information                      */
5697 /*                                                                          */
5698 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
5699 /* not possible, return without indicating a failure or success but in a    */
5700 /* way that is ditinguishable.                                              */
5701 /* ------------------------------------------------------------------------ */
5702 int fr_checkl4sum(fin)
5703 fr_info_t *fin;
5704 {
5705 	u_short sum, hdrsum, *csump;
5706 	udphdr_t *udp;
5707 	int dosum;
5708 	ipf_stack_t *ifs = fin->fin_ifs;
5709 
5710 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5711 	net_handle_t net_data_p;
5712 	if (fin->fin_v == 4)
5713 		net_data_p = ifs->ifs_ipf_ipv4;
5714 	else
5715 		net_data_p = ifs->ifs_ipf_ipv6;
5716 #endif
5717 
5718 	if ((fin->fin_flx & FI_NOCKSUM) != 0)
5719 		return 0;
5720 
5721 	/*
5722 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
5723 	 * isn't already considered "bad", then validate the checksum.  If
5724 	 * this check fails then considered the packet to be "bad".
5725 	 */
5726 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
5727 		return 1;
5728 
5729 	csump = NULL;
5730 	hdrsum = 0;
5731 	dosum = 0;
5732 	sum = 0;
5733 
5734 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5735 	ASSERT(fin->fin_m != NULL);
5736 	if (NET_IS_HCK_L4_FULL(net_data_p, fin->fin_m) ||
5737 	    NET_IS_HCK_L4_PART(net_data_p, fin->fin_m)) {
5738 			hdrsum = 0;
5739 			sum = 0;
5740 	} else {
5741 #endif
5742 		switch (fin->fin_p)
5743 		{
5744 		case IPPROTO_TCP :
5745 			csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
5746 			dosum = 1;
5747 			break;
5748 
5749 		case IPPROTO_UDP :
5750 			udp = fin->fin_dp;
5751 			if (udp->uh_sum != 0) {
5752 				csump = &udp->uh_sum;
5753 				dosum = 1;
5754 			}
5755 			break;
5756 
5757 		case IPPROTO_ICMP :
5758 			csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
5759 			dosum = 1;
5760 			break;
5761 
5762 		default :
5763 			return 1;
5764 			/*NOTREACHED*/
5765 		}
5766 
5767 		if (csump != NULL)
5768 			hdrsum = *csump;
5769 
5770 		if (dosum)
5771 			sum = fr_cksum(fin->fin_m, fin->fin_ip,
5772 				       fin->fin_p, fin->fin_dp);
5773 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5774 	}
5775 #endif
5776 #if !defined(_KERNEL)
5777 	if (sum == hdrsum) {
5778 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
5779 	} else {
5780 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
5781 	}
5782 #endif
5783 	if (hdrsum == sum)
5784 		return 0;
5785 	return -1;
5786 }
5787 
5788 
5789 /* ------------------------------------------------------------------------ */
5790 /* Function:    fr_ifpfillv4addr                                            */
5791 /* Returns:     int     - 0 = address update, -1 = address not updated      */
5792 /* Parameters:  atype(I)   - type of network address update to perform      */
5793 /*              sin(I)     - pointer to source of address information       */
5794 /*              mask(I)    - pointer to source of netmask information       */
5795 /*              inp(I)     - pointer to destination address store           */
5796 /*              inpmask(I) - pointer to destination netmask store           */
5797 /*                                                                          */
5798 /* Given a type of network address update (atype) to perform, copy          */
5799 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
5800 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
5801 /* which case the operation fails.  For all values of atype other than      */
5802 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
5803 /* value.                                                                   */
5804 /* ------------------------------------------------------------------------ */
5805 int fr_ifpfillv4addr(atype, sin, mask, inp, inpmask)
5806 int atype;
5807 struct sockaddr_in *sin, *mask;
5808 struct in_addr *inp, *inpmask;
5809 {
5810 	if (inpmask != NULL && atype != FRI_NETMASKED)
5811 		inpmask->s_addr = 0xffffffff;
5812 
5813 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5814 		if (atype == FRI_NETMASKED) {
5815 			if (inpmask == NULL)
5816 				return -1;
5817 			inpmask->s_addr = mask->sin_addr.s_addr;
5818 		}
5819 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
5820 	} else {
5821 		inp->s_addr = sin->sin_addr.s_addr;
5822 	}
5823 	return 0;
5824 }
5825 
5826 
5827 #ifdef	USE_INET6
5828 /* ------------------------------------------------------------------------ */
5829 /* Function:    fr_ifpfillv6addr                                            */
5830 /* Returns:     int     - 0 = address update, -1 = address not updated      */
5831 /* Parameters:  atype(I)   - type of network address update to perform      */
5832 /*              sin(I)     - pointer to source of address information       */
5833 /*              mask(I)    - pointer to source of netmask information       */
5834 /*              inp(I)     - pointer to destination address store           */
5835 /*              inpmask(I) - pointer to destination netmask store           */
5836 /*                                                                          */
5837 /* Given a type of network address update (atype) to perform, copy          */
5838 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
5839 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
5840 /* which case the operation fails.  For all values of atype other than      */
5841 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
5842 /* value.                                                                   */
5843 /* ------------------------------------------------------------------------ */
5844 int fr_ifpfillv6addr(atype, sin, mask, inp, inpmask)
5845 int atype;
5846 struct sockaddr_in6 *sin, *mask;
5847 struct in_addr *inp, *inpmask;
5848 {
5849 	i6addr_t *src, *dst, *and, *dmask;
5850 
5851 	src = (i6addr_t *)&sin->sin6_addr;
5852 	and = (i6addr_t *)&mask->sin6_addr;
5853 	dst = (i6addr_t *)inp;
5854 	dmask = (i6addr_t *)inpmask;
5855 
5856 	if (inpmask != NULL && atype != FRI_NETMASKED) {
5857 		dmask->i6[0] = 0xffffffff;
5858 		dmask->i6[1] = 0xffffffff;
5859 		dmask->i6[2] = 0xffffffff;
5860 		dmask->i6[3] = 0xffffffff;
5861 	}
5862 
5863 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5864 		if (atype == FRI_NETMASKED) {
5865 			if (inpmask == NULL)
5866 				return -1;
5867 			dmask->i6[0] = and->i6[0];
5868 			dmask->i6[1] = and->i6[1];
5869 			dmask->i6[2] = and->i6[2];
5870 			dmask->i6[3] = and->i6[3];
5871 		}
5872 
5873 		dst->i6[0] = src->i6[0] & and->i6[0];
5874 		dst->i6[1] = src->i6[1] & and->i6[1];
5875 		dst->i6[2] = src->i6[2] & and->i6[2];
5876 		dst->i6[3] = src->i6[3] & and->i6[3];
5877 	} else {
5878 		dst->i6[0] = src->i6[0];
5879 		dst->i6[1] = src->i6[1];
5880 		dst->i6[2] = src->i6[2];
5881 		dst->i6[3] = src->i6[3];
5882 	}
5883 	return 0;
5884 }
5885 #endif
5886 
5887 
5888 /* ------------------------------------------------------------------------ */
5889 /* Function:    fr_matchtag                                                 */
5890 /* Returns:     0 == mismatch, 1 == match.                                  */
5891 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
5892 /*              tag2(I) - pointer to second tag to compare                  */
5893 /*                                                                          */
5894 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
5895 /* considered to be a match or not match, respectively.  The tag is 16      */
5896 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
5897 /* compare the ints instead, for speed. tag1 is the master of the           */
5898 /* comparison.  This function should only be called with both tag1 and tag2 */
5899 /* as non-NULL pointers.                                                    */
5900 /* ------------------------------------------------------------------------ */
5901 int fr_matchtag(tag1, tag2)
5902 ipftag_t *tag1, *tag2;
5903 {
5904 	if (tag1 == tag2)
5905 		return 1;
5906 
5907 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
5908 		return 1;
5909 
5910 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
5911 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
5912 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
5913 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
5914 		return 1;
5915 	return 0;
5916 }
5917 
5918 
5919 /* ------------------------------------------------------------------------ */
5920 /* Function:    fr_coalesce                                                 */
5921 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
5922 /* Parameters:  fin(I) - pointer to packet information                      */
5923 /*                                                                          */
5924 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
5925 /* If this call returns a failure then the buffers have also been freed.    */
5926 /* ------------------------------------------------------------------------ */
5927 int fr_coalesce(fin)
5928 fr_info_t *fin;
5929 {
5930 	ipf_stack_t *ifs = fin->fin_ifs;
5931 	if ((fin->fin_flx & FI_COALESCE) != 0)
5932 		return 1;
5933 
5934 	/*
5935 	 * If the mbuf pointers indicate that there is no mbuf to work with,
5936 	 * return but do not indicate success or failure.
5937 	 */
5938 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
5939 		return 0;
5940 
5941 #if defined(_KERNEL)
5942 	if (fr_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
5943 		IPF_BUMP(ifs->ifs_fr_badcoalesces[fin->fin_out]);
5944 # ifdef MENTAT
5945 		FREE_MB_T(*fin->fin_mp);
5946 # endif
5947 		*fin->fin_mp = NULL;
5948 		fin->fin_m = NULL;
5949 		return -1;
5950 	}
5951 #else
5952 	fin = fin;	/* LINT */
5953 #endif
5954 	return 1;
5955 }
5956 
5957 
5958 /*
5959  * The following table lists all of the tunable variables that can be
5960  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXT.  The format of each row
5961  * in the table below is as follows:
5962  *
5963  * pointer to value, name of value, minimum, maximum, size of the value's
5964  *     container, value attribute flags
5965  *
5966  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
5967  * means the value can only be written to when IPFilter is loaded but disabled.
5968  * The obvious implication is if neither of these are set then the value can be
5969  * changed at any time without harm.
5970  */
5971 ipftuneable_t lcl_ipf_tuneables[] = {
5972 	/* filtering */
5973 	{ { NULL },	"fr_flags",		0,	0xffffffff,
5974 			0,		0 },
5975 	{ { NULL },	"fr_active",		0,	0,
5976 			0,		IPFT_RDONLY },
5977 	{ { NULL },	"fr_control_forwarding",	0, 1,
5978 			0,		0 },
5979 	{ { NULL },	"fr_update_ipid",	0,	1,
5980 			0,		0 },
5981 	{ { NULL },	"fr_chksrc",		0,	1,
5982 			0,		0 },
5983 	{ { NULL },	"fr_minttl",		0,	1,
5984 			0,		0 },
5985 	{ { NULL }, 	"fr_icmpminfragmtu",	0,	1,
5986 			0,		0 },
5987 	{ { NULL },		"fr_pass",		0,	0xffffffff,
5988 			0,		0 },
5989 #if SOLARIS2 >= 10
5990 	{ { NULL },	"ipf_loopback",		0,	1,
5991 			0,		IPFT_WRDISABLED },
5992 #endif
5993 	/* state */
5994 	{ { NULL }, "fr_tcpidletimeout",	1,	0x7fffffff,
5995 			0,	IPFT_WRDISABLED },
5996 	{ { NULL },	"fr_tcpclosewait",	1,	0x7fffffff,
5997 			0,	IPFT_WRDISABLED },
5998 	{ { NULL },	"fr_tcplastack",	1,	0x7fffffff,
5999 			0,		IPFT_WRDISABLED },
6000 	{ { NULL },	"fr_tcptimeout",	1,	0x7fffffff,
6001 			0,		IPFT_WRDISABLED },
6002 	{ { NULL },	"fr_tcpclosed",		1,	0x7fffffff,
6003 			0,		IPFT_WRDISABLED },
6004 	{ { NULL },	"fr_tcphalfclosed",	1,	0x7fffffff,
6005 			0,	IPFT_WRDISABLED },
6006 	{ { NULL },	"fr_udptimeout",	1,	0x7fffffff,
6007 			0,		IPFT_WRDISABLED },
6008 	{ { NULL }, "fr_udpacktimeout",	1,	0x7fffffff,
6009 			0,	IPFT_WRDISABLED },
6010 	{ { NULL },	"fr_icmptimeout",	1,	0x7fffffff,
6011 			0,		IPFT_WRDISABLED },
6012 	{ { NULL }, "fr_icmpacktimeout",	1,	0x7fffffff,
6013 			0,	IPFT_WRDISABLED },
6014 	{ { NULL }, "fr_iptimeout",		1,	0x7fffffff,
6015 			0,		IPFT_WRDISABLED },
6016 	{ { NULL },	"fr_statemax",		1,	0x7fffffff,
6017 			0,		0 },
6018 	{ { NULL },	"fr_statesize",		1,	0x7fffffff,
6019 			0,		IPFT_WRDISABLED },
6020 	{ { NULL },	"fr_state_lock",	0,	1,
6021 			0,		IPFT_RDONLY },
6022 	{ { NULL }, "fr_state_maxbucket", 1,	0x7fffffff,
6023 			0,	IPFT_WRDISABLED },
6024 	{ { NULL }, "fr_state_maxbucket_reset",	0, 1,
6025 			0, IPFT_WRDISABLED },
6026 	{ { NULL },	"ipstate_logging",	0,	1,
6027 			0,	0 },
6028 	/* nat */
6029 	{ { NULL },		"fr_nat_lock",		0,	1,
6030 			0,		IPFT_RDONLY },
6031 	{ { NULL },	"ipf_nattable_sz",	1,	0x7fffffff,
6032 			0,	IPFT_WRDISABLED },
6033 	{ { NULL }, "ipf_nattable_max",	1,	0x7fffffff,
6034 			0,	0 },
6035 	{ { NULL },	"ipf_natrules_sz",	1,	0x7fffffff,
6036 			0,	IPFT_WRDISABLED },
6037 	{ { NULL },	"ipf_rdrrules_sz",	1,	0x7fffffff,
6038 			0,	IPFT_WRDISABLED },
6039 	{ { NULL },	"ipf_hostmap_sz",	1,	0x7fffffff,
6040 			0,		IPFT_WRDISABLED },
6041 	{ { NULL }, "fr_nat_maxbucket",	1,	0x7fffffff,
6042 			0,	IPFT_WRDISABLED },
6043 	{ { NULL },	"fr_nat_maxbucket_reset",	0, 1,
6044 			0,	IPFT_WRDISABLED },
6045 	{ { NULL },		"nat_logging",		0,	1,
6046 			0,		0 },
6047 	{ { NULL },	"fr_defnatage",		1,	0x7fffffff,
6048 			0,		IPFT_WRDISABLED },
6049 	{ { NULL },	"fr_defnatipage",	1,	0x7fffffff,
6050 			0,		IPFT_WRDISABLED },
6051 	{ { NULL }, "fr_defnaticmpage",	1,	0x7fffffff,
6052 			0,	IPFT_WRDISABLED },
6053 	{ { NULL },	"nat_flush_lvl_hi",	1,	100,
6054 			0,		0 },
6055 	{ { NULL },	"nat_flush_lvl_lo",	1,	100,
6056 			0,		0 },
6057 	/* frag */
6058 	{ { NULL },	"ipfr_size",		1,	0x7fffffff,
6059 			0,		IPFT_WRDISABLED },
6060 	{ { NULL },	"fr_ipfrttl",		1,	0x7fffffff,
6061 			0,		IPFT_WRDISABLED },
6062 #ifdef IPFILTER_LOG
6063 	/* log */
6064 	{ { NULL },	"ipl_suppress",		0,	1,
6065 			0,		0 },
6066 	{ { NULL },	"ipl_buffer_sz",	0,	0,
6067 			0,		IPFT_RDONLY },
6068 	{ { NULL },	"ipl_logmax",		0,	0x7fffffff,
6069 			0,		IPFT_WRDISABLED },
6070 	{ { NULL },	"ipl_logall",		0,	1,
6071 			0,		0 },
6072 	{ { NULL },	"ipl_logsize",		0,	0x80000,
6073 			0,		0 },
6074 #endif
6075 	{ { NULL },		NULL,			0,	0 }
6076 };
6077 
6078 static ipftuneable_t *
6079 tune_lookup(ipf_stack_t *ifs, char *name)
6080 {
6081     int i;
6082 
6083     for (i = 0; ifs->ifs_ipf_tuneables[i].ipft_name != NULL; i++) {
6084 	if (strcmp(ifs->ifs_ipf_tuneables[i].ipft_name, name) == 0)
6085 	    return (&ifs->ifs_ipf_tuneables[i]);
6086     }
6087     return (NULL);
6088 }
6089 
6090 #ifdef _KERNEL
6091 extern dev_info_t *ipf_dev_info;
6092 extern int ipf_property_update __P((dev_info_t *, ipf_stack_t *));
6093 #endif
6094 
6095 /* -------------------------------------------------------------------- */
6096 /* Function:	ipftuneable_setdefs()					*/
6097 /* Returns:		void						*/
6098 /* Parameters:	ifs - pointer to newly allocated IPF instance		*/
6099 /*				assigned to	IP instance		*/
6100 /*									*/
6101 /* Function initializes IPF instance variables. Function is invoked	*/
6102 /* from	ipftuneable_alloc(). ipftuneable_alloc() is called only one	*/
6103 /* time during IP instance lifetime - at the time of IP instance	*/
6104 /* creation. Anytime IP	instance is being created new private IPF	*/
6105 /* instance is allocated and assigned to it. The moment of IP 		*/
6106 /* instance creation is the right time to initialize those IPF 		*/
6107 /* variables.								*/
6108 /*									*/
6109 /* -------------------------------------------------------------------- */
6110 static void ipftuneable_setdefs(ipf_stack_t *ifs)
6111 {
6112 	ifs->ifs_ipfr_size = IPFT_SIZE;
6113 	ifs->ifs_fr_ipfrttl = 120;	/* 60 seconds */
6114 
6115 	/* it comes from fr_authinit() in IPF auth */
6116 	ifs->ifs_fr_authsize = FR_NUMAUTH;
6117 	ifs->ifs_fr_defaultauthage = 600;
6118 
6119 	/* it comes from fr_stateinit() in IPF state */
6120 	ifs->ifs_fr_tcpidletimeout = IPF_TTLVAL(3600 * 24 * 5);	/* five days */
6121 	ifs->ifs_fr_tcpclosewait = IPF_TTLVAL(TCP_MSL);
6122 	ifs->ifs_fr_tcplastack = IPF_TTLVAL(TCP_MSL);
6123 	ifs->ifs_fr_tcptimeout = IPF_TTLVAL(TCP_MSL);
6124 	ifs->ifs_fr_tcpclosed = IPF_TTLVAL(60);
6125 	ifs->ifs_fr_tcphalfclosed = IPF_TTLVAL(2 * 3600);	/* 2 hours */
6126 	ifs->ifs_fr_udptimeout = IPF_TTLVAL(120);
6127 	ifs->ifs_fr_udpacktimeout = IPF_TTLVAL(12);
6128 	ifs->ifs_fr_icmptimeout = IPF_TTLVAL(60);
6129 	ifs->ifs_fr_icmpacktimeout = IPF_TTLVAL(6);
6130 	ifs->ifs_fr_iptimeout = IPF_TTLVAL(60);
6131 	ifs->ifs_fr_statemax = IPSTATE_MAX;
6132 	ifs->ifs_fr_statesize = IPSTATE_SIZE;
6133 	ifs->ifs_fr_state_maxbucket_reset = 1;
6134 
6135 	/* it comes from fr_natinit() in ipnat */
6136 	ifs->ifs_ipf_nattable_sz = NAT_TABLE_SZ;
6137 	ifs->ifs_ipf_nattable_max = NAT_TABLE_MAX;
6138 	ifs->ifs_ipf_natrules_sz = NAT_SIZE;
6139 	ifs->ifs_ipf_rdrrules_sz = RDR_SIZE;
6140 	ifs->ifs_ipf_hostmap_sz = HOSTMAP_SIZE;
6141 	ifs->ifs_fr_nat_maxbucket_reset = 1;
6142 	ifs->ifs_fr_defnatage = DEF_NAT_AGE;
6143 	ifs->ifs_fr_defnatipage = 120;		/* 60 seconds */
6144 	ifs->ifs_fr_defnaticmpage = 6;		/* 3 seconds */
6145 	ifs->ifs_nat_flush_lvl_hi = NAT_FLUSH_HI;
6146 	ifs->ifs_nat_flush_lvl_lo = NAT_FLUSH_LO;
6147 
6148 #ifdef IPFILTER_LOG
6149 	/* it comes from fr_loginit() in IPF log */
6150 	ifs->ifs_ipl_suppress = 1;
6151 	ifs->ifs_ipl_logmax = IPL_LOGMAX;
6152 	ifs->ifs_ipl_logsize = IPFILTER_LOGSIZE;
6153 
6154 	/* from fr_natinit() */
6155 	ifs->ifs_nat_logging = 1;
6156 
6157 	/* from fr_stateinit() */
6158 	ifs->ifs_ipstate_logging = 1;
6159 #else
6160 	/* from fr_natinit() */
6161 	ifs->ifs_nat_logging = 0;
6162 
6163 	/* from fr_stateinit() */
6164 	ifs->ifs_ipstate_logging = 0;
6165 #endif
6166 	ifs->ifs_ipf_loopback = 0;
6167 
6168 }
6169 /*
6170  * Allocate a per-stack tuneable and copy in the names. Then
6171  * set it to point to each of the per-stack tunables.
6172  */
6173 void
6174 ipftuneable_alloc(ipf_stack_t *ifs)
6175 {
6176     ipftuneable_t *item;
6177 
6178     KMALLOCS(ifs->ifs_ipf_tuneables, ipftuneable_t *,
6179 	sizeof (lcl_ipf_tuneables));
6180     bcopy(lcl_ipf_tuneables, ifs->ifs_ipf_tuneables,
6181 	sizeof (lcl_ipf_tuneables));
6182 
6183 #define TUNE_SET(_ifs, _name, _field)			\
6184     item = tune_lookup((_ifs), (_name));		\
6185     if (item != NULL) {					\
6186 	item->ipft_una.ipftp_int = (unsigned int *)&((_ifs)->_field);	\
6187 	item->ipft_sz = sizeof ((_ifs)->_field);	\
6188     }
6189 
6190     TUNE_SET(ifs, "fr_flags", ifs_fr_flags);
6191     TUNE_SET(ifs, "fr_active", ifs_fr_active);
6192     TUNE_SET(ifs, "fr_control_forwarding", ifs_fr_control_forwarding);
6193     TUNE_SET(ifs, "fr_update_ipid", ifs_fr_update_ipid);
6194     TUNE_SET(ifs, "fr_chksrc", ifs_fr_chksrc);
6195     TUNE_SET(ifs, "fr_minttl", ifs_fr_minttl);
6196     TUNE_SET(ifs, "fr_icmpminfragmtu", ifs_fr_icmpminfragmtu);
6197     TUNE_SET(ifs, "fr_pass", ifs_fr_pass);
6198     TUNE_SET(ifs, "fr_tcpidletimeout", ifs_fr_tcpidletimeout);
6199     TUNE_SET(ifs, "fr_tcpclosewait", ifs_fr_tcpclosewait);
6200     TUNE_SET(ifs, "fr_tcplastack", ifs_fr_tcplastack);
6201     TUNE_SET(ifs, "fr_tcptimeout", ifs_fr_tcptimeout);
6202     TUNE_SET(ifs, "fr_tcpclosed", ifs_fr_tcpclosed);
6203     TUNE_SET(ifs, "fr_tcphalfclosed", ifs_fr_tcphalfclosed);
6204     TUNE_SET(ifs, "fr_udptimeout", ifs_fr_udptimeout);
6205     TUNE_SET(ifs, "fr_udpacktimeout", ifs_fr_udpacktimeout);
6206     TUNE_SET(ifs, "fr_icmptimeout", ifs_fr_icmptimeout);
6207     TUNE_SET(ifs, "fr_icmpacktimeout", ifs_fr_icmpacktimeout);
6208     TUNE_SET(ifs, "fr_iptimeout", ifs_fr_iptimeout);
6209     TUNE_SET(ifs, "fr_statemax", ifs_fr_statemax);
6210     TUNE_SET(ifs, "fr_statesize", ifs_fr_statesize);
6211     TUNE_SET(ifs, "fr_state_lock", ifs_fr_state_lock);
6212     TUNE_SET(ifs, "fr_state_maxbucket", ifs_fr_state_maxbucket);
6213     TUNE_SET(ifs, "fr_state_maxbucket_reset", ifs_fr_state_maxbucket_reset);
6214     TUNE_SET(ifs, "ipstate_logging", ifs_ipstate_logging);
6215     TUNE_SET(ifs, "fr_nat_lock", ifs_fr_nat_lock);
6216     TUNE_SET(ifs, "ipf_nattable_sz", ifs_ipf_nattable_sz);
6217     TUNE_SET(ifs, "ipf_nattable_max", ifs_ipf_nattable_max);
6218     TUNE_SET(ifs, "ipf_natrules_sz", ifs_ipf_natrules_sz);
6219     TUNE_SET(ifs, "ipf_rdrrules_sz", ifs_ipf_rdrrules_sz);
6220     TUNE_SET(ifs, "ipf_hostmap_sz", ifs_ipf_hostmap_sz);
6221     TUNE_SET(ifs, "fr_nat_maxbucket", ifs_fr_nat_maxbucket);
6222     TUNE_SET(ifs, "fr_nat_maxbucket_reset", ifs_fr_nat_maxbucket_reset);
6223     TUNE_SET(ifs, "nat_logging", ifs_nat_logging);
6224     TUNE_SET(ifs, "fr_defnatage", ifs_fr_defnatage);
6225     TUNE_SET(ifs, "fr_defnatipage", ifs_fr_defnatipage);
6226     TUNE_SET(ifs, "fr_defnaticmpage", ifs_fr_defnaticmpage);
6227     TUNE_SET(ifs, "nat_flush_lvl_hi", ifs_nat_flush_lvl_hi);
6228     TUNE_SET(ifs, "nat_flush_lvl_lo", ifs_nat_flush_lvl_lo);
6229     TUNE_SET(ifs, "ipfr_size", ifs_ipfr_size);
6230     TUNE_SET(ifs, "fr_ipfrttl", ifs_fr_ipfrttl);
6231     TUNE_SET(ifs, "ipf_loopback", ifs_ipf_loopback);
6232 #ifdef IPFILTER_LOG
6233     TUNE_SET(ifs, "ipl_suppress", ifs_ipl_suppress);
6234     TUNE_SET(ifs, "ipl_buffer_sz", ifs_ipl_buffer_sz);
6235     TUNE_SET(ifs, "ipl_logmax", ifs_ipl_logmax);
6236     TUNE_SET(ifs, "ipl_logall", ifs_ipl_logall);
6237     TUNE_SET(ifs, "ipl_logsize", ifs_ipl_logsize);
6238 #endif
6239 #undef TUNE_SET
6240 
6241 	ipftuneable_setdefs(ifs);
6242 
6243 #ifdef _KERNEL
6244     (void) ipf_property_update(ipf_dev_info, ifs);
6245 #endif
6246 }
6247 
6248 void
6249 ipftuneable_free(ipf_stack_t *ifs)
6250 {
6251 	KFREES(ifs->ifs_ipf_tuneables, sizeof (lcl_ipf_tuneables));
6252 	ifs->ifs_ipf_tuneables = NULL;
6253 }
6254 
6255 /* ------------------------------------------------------------------------ */
6256 /* Function:    fr_findtunebycookie                                         */
6257 /* Returns:     NULL = search failed, else pointer to tune struct           */
6258 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6259 /*              next(O)   - pointer to place to store the cookie for the    */
6260 /*                          "next" tuneable, if it is desired.              */
6261 /*                                                                          */
6262 /* This function is used to walk through all of the existing tunables with  */
6263 /* successive calls.  It searches the known tunables for the one which has  */
6264 /* a matching value for "cookie" - ie its address.  When returning a match, */
6265 /* the next one to be found may be returned inside next.                    */
6266 /* ------------------------------------------------------------------------ */
6267 static ipftuneable_t *fr_findtunebycookie(cookie, next, ifs)
6268 void *cookie, **next;
6269 ipf_stack_t * ifs;
6270 {
6271 	ipftuneable_t *ta, **tap;
6272 
6273 	for (ta = ifs->ifs_ipf_tuneables; ta->ipft_name != NULL; ta++)
6274 		if (ta == cookie) {
6275 			if (next != NULL) {
6276 				/*
6277 				 * If the next entry in the array has a name
6278 				 * present, then return a pointer to it for
6279 				 * where to go next, else return a pointer to
6280 				 * the dynaminc list as a key to search there
6281 				 * next.  This facilitates a weak linking of
6282 				 * the two "lists" together.
6283 				 */
6284 				if ((ta + 1)->ipft_name != NULL)
6285 					*next = ta + 1;
6286 				else
6287 					*next = &ifs->ifs_ipf_tunelist;
6288 			}
6289 			return ta;
6290 		}
6291 
6292 	for (tap = &ifs->ifs_ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6293 		if (tap == cookie) {
6294 			if (next != NULL)
6295 				*next = &ta->ipft_next;
6296 			return ta;
6297 		}
6298 
6299 	if (next != NULL)
6300 		*next = NULL;
6301 	return NULL;
6302 }
6303 
6304 
6305 /* ------------------------------------------------------------------------ */
6306 /* Function:    fr_findtunebyname                                           */
6307 /* Returns:     NULL = search failed, else pointer to tune struct           */
6308 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6309 /*                                                                          */
6310 /* Search the static array of tuneables and the list of dynamic tuneables   */
6311 /* for an entry with a matching name.  If we can find one, return a pointer */
6312 /* to the matching structure.                                               */
6313 /* ------------------------------------------------------------------------ */
6314 static ipftuneable_t *fr_findtunebyname(name, ifs)
6315 const char *name;
6316 ipf_stack_t *ifs;
6317 {
6318 	ipftuneable_t *ta;
6319 
6320 	for (ta = ifs->ifs_ipf_tuneables; ta->ipft_name != NULL; ta++)
6321 		if (!strcmp(ta->ipft_name, name)) {
6322 			return ta;
6323 		}
6324 
6325 	for (ta = ifs->ifs_ipf_tunelist; ta != NULL; ta = ta->ipft_next)
6326 		if (!strcmp(ta->ipft_name, name)) {
6327 			return ta;
6328 		}
6329 
6330 	return NULL;
6331 }
6332 
6333 
6334 /* ------------------------------------------------------------------------ */
6335 /* Function:    fr_addipftune                                               */
6336 /* Returns:     int - 0 == success, else failure                            */
6337 /* Parameters:  newtune - pointer to new tune struct to add to tuneables    */
6338 /*                                                                          */
6339 /* Appends the tune structure pointer to by "newtune" to the end of the     */
6340 /* current list of "dynamic" tuneable parameters.  Once added, the owner    */
6341 /* of the object is not expected to ever change "ipft_next".                */
6342 /* ------------------------------------------------------------------------ */
6343 int fr_addipftune(newtune, ifs)
6344 ipftuneable_t *newtune;
6345 ipf_stack_t *ifs;
6346 {
6347 	ipftuneable_t *ta, **tap;
6348 
6349 	ta = fr_findtunebyname(newtune->ipft_name, ifs);
6350 	if (ta != NULL)
6351 		return EEXIST;
6352 
6353 	for (tap = &ifs->ifs_ipf_tunelist; *tap != NULL; tap = &(*tap)->ipft_next)
6354 		;
6355 
6356 	newtune->ipft_next = NULL;
6357 	*tap = newtune;
6358 	return 0;
6359 }
6360 
6361 
6362 /* ------------------------------------------------------------------------ */
6363 /* Function:    fr_delipftune                                               */
6364 /* Returns:     int - 0 == success, else failure                            */
6365 /* Parameters:  oldtune - pointer to tune struct to remove from the list of */
6366 /*                        current dynamic tuneables                         */
6367 /*                                                                          */
6368 /* Search for the tune structure, by pointer, in the list of those that are */
6369 /* dynamically added at run time.  If found, adjust the list so that this   */
6370 /* structure is no longer part of it.                                       */
6371 /* ------------------------------------------------------------------------ */
6372 int fr_delipftune(oldtune, ifs)
6373 ipftuneable_t *oldtune;
6374 ipf_stack_t *ifs;
6375 {
6376 	ipftuneable_t *ta, **tap;
6377 
6378 	for (tap = &ifs->ifs_ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6379 		if (ta == oldtune) {
6380 			*tap = oldtune->ipft_next;
6381 			oldtune->ipft_next = NULL;
6382 			return 0;
6383 		}
6384 
6385 	return ESRCH;
6386 }
6387 
6388 
6389 /* ------------------------------------------------------------------------ */
6390 /* Function:    fr_ipftune                                                  */
6391 /* Returns:     int - 0 == success, else failure                            */
6392 /* Parameters:  cmd(I)  - ioctl command number                              */
6393 /*              data(I) - pointer to ioctl data structure                   */
6394 /*                                                                          */
6395 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
6396 /* three ioctls provide the means to access and control global variables    */
6397 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
6398 /* changed without rebooting, reloading or recompiling.  The initialisation */
6399 /* and 'destruction' routines of the various components of ipfilter are all */
6400 /* each responsible for handling their own values being too big.            */
6401 /* ------------------------------------------------------------------------ */
6402 int fr_ipftune(cmd, data, ifs)
6403 ioctlcmd_t cmd;
6404 void *data;
6405 ipf_stack_t *ifs;
6406 {
6407 	ipftuneable_t *ta;
6408 	ipftune_t tu;
6409 	void *cookie;
6410 	int error;
6411 
6412 	error = fr_inobj(data, &tu, IPFOBJ_TUNEABLE);
6413 	if (error != 0)
6414 		return error;
6415 
6416 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
6417 	cookie = tu.ipft_cookie;
6418 	ta = NULL;
6419 
6420 	switch (cmd)
6421 	{
6422 	case SIOCIPFGETNEXT :
6423 		/*
6424 		 * If cookie is non-NULL, assume it to be a pointer to the last
6425 		 * entry we looked at, so find it (if possible) and return a
6426 		 * pointer to the next one after it.  The last entry in the
6427 		 * the table is a NULL entry, so when we get to it, set cookie
6428 		 * to NULL and return that, indicating end of list, erstwhile
6429 		 * if we come in with cookie set to NULL, we are starting anew
6430 		 * at the front of the list.
6431 		 */
6432 		if (cookie != NULL) {
6433 			ta = fr_findtunebycookie(cookie, &tu.ipft_cookie, ifs);
6434 		} else {
6435 			ta = ifs->ifs_ipf_tuneables;
6436 			tu.ipft_cookie = ta + 1;
6437 		}
6438 		if (ta != NULL) {
6439 			/*
6440 			 * Entry found, but does the data pointed to by that
6441 			 * row fit in what we can return?
6442 			 */
6443 			if (ta->ipft_sz > sizeof(tu.ipft_un))
6444 				return EINVAL;
6445 
6446 			tu.ipft_vlong = 0;
6447 			if (ta->ipft_sz == sizeof(u_long))
6448 				tu.ipft_vlong = *ta->ipft_plong;
6449 			else if (ta->ipft_sz == sizeof(u_int))
6450 				tu.ipft_vint = *ta->ipft_pint;
6451 			else if (ta->ipft_sz == sizeof(u_short))
6452 				tu.ipft_vshort = *ta->ipft_pshort;
6453 			else if (ta->ipft_sz == sizeof(u_char))
6454 				tu.ipft_vchar = *ta->ipft_pchar;
6455 
6456 			tu.ipft_sz = ta->ipft_sz;
6457 			tu.ipft_min = ta->ipft_min;
6458 			tu.ipft_max = ta->ipft_max;
6459 			tu.ipft_flags = ta->ipft_flags;
6460 			bcopy(ta->ipft_name, tu.ipft_name,
6461 			      MIN(sizeof(tu.ipft_name),
6462 				  strlen(ta->ipft_name) + 1));
6463 		}
6464 		error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6465 		break;
6466 
6467 	case SIOCIPFGET :
6468 	case SIOCIPFSET :
6469 		/*
6470 		 * Search by name or by cookie value for a particular entry
6471 		 * in the tuning paramter table.
6472 		 */
6473 		error = ESRCH;
6474 		if (cookie != NULL) {
6475 			ta = fr_findtunebycookie(cookie, NULL, ifs);
6476 			if (ta != NULL)
6477 				error = 0;
6478 		} else if (tu.ipft_name[0] != '\0') {
6479 			ta = fr_findtunebyname(tu.ipft_name, ifs);
6480 			if (ta != NULL)
6481 				error = 0;
6482 		}
6483 		if (error != 0)
6484 			break;
6485 
6486 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
6487 			/*
6488 			 * Fetch the tuning parameters for a particular value
6489 			 */
6490 			tu.ipft_vlong = 0;
6491 			if (ta->ipft_sz == sizeof(u_long))
6492 				tu.ipft_vlong = *ta->ipft_plong;
6493 			else if (ta->ipft_sz == sizeof(u_int))
6494 				tu.ipft_vint = *ta->ipft_pint;
6495 			else if (ta->ipft_sz == sizeof(u_short))
6496 				tu.ipft_vshort = *ta->ipft_pshort;
6497 			else if (ta->ipft_sz == sizeof(u_char))
6498 				tu.ipft_vchar = *ta->ipft_pchar;
6499 			tu.ipft_cookie = ta;
6500 			tu.ipft_sz = ta->ipft_sz;
6501 			tu.ipft_min = ta->ipft_min;
6502 			tu.ipft_max = ta->ipft_max;
6503 			tu.ipft_flags = ta->ipft_flags;
6504 			error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6505 
6506 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
6507 			/*
6508 			 * Set an internal parameter.  The hard part here is
6509 			 * getting the new value safely and correctly out of
6510 			 * the kernel (given we only know its size, not type.)
6511 			 */
6512 			u_long in;
6513 
6514 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
6515 			    (ifs->ifs_fr_running > 0)) {
6516 				error = EBUSY;
6517 				break;
6518 			}
6519 
6520 			in = tu.ipft_vlong;
6521 			if (in < ta->ipft_min || in > ta->ipft_max) {
6522 				error = EINVAL;
6523 				break;
6524 			}
6525 
6526 			if (ta->ipft_sz == sizeof(u_long)) {
6527 				tu.ipft_vlong = *ta->ipft_plong;
6528 				*ta->ipft_plong = in;
6529 			} else if (ta->ipft_sz == sizeof(u_int)) {
6530 				tu.ipft_vint = *ta->ipft_pint;
6531 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
6532 			} else if (ta->ipft_sz == sizeof(u_short)) {
6533 				tu.ipft_vshort = *ta->ipft_pshort;
6534 				*ta->ipft_pshort = (u_short)(in & 0xffff);
6535 			} else if (ta->ipft_sz == sizeof(u_char)) {
6536 				tu.ipft_vchar = *ta->ipft_pchar;
6537 				*ta->ipft_pchar = (u_char)(in & 0xff);
6538 			}
6539 			error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6540 		}
6541 		break;
6542 
6543 	default :
6544 		error = EINVAL;
6545 		break;
6546 	}
6547 
6548 	return error;
6549 }
6550 
6551 
6552 /* ------------------------------------------------------------------------ */
6553 /* Function:    fr_initialise                                               */
6554 /* Returns:     int - 0 == success,  < 0 == failure                         */
6555 /* Parameters:  None.                                                       */
6556 /*                                                                          */
6557 /* Call of the initialise functions for all the various subsystems inside   */
6558 /* of IPFilter.  If any of them should fail, return immeadiately a failure  */
6559 /* BUT do not try to recover from the error here.                           */
6560 /* ------------------------------------------------------------------------ */
6561 int fr_initialise(ifs)
6562 ipf_stack_t *ifs;
6563 {
6564 	int i;
6565 
6566 #ifdef IPFILTER_LOG
6567 	i = fr_loginit(ifs);
6568 	if (i < 0)
6569 		return -10 + i;
6570 #endif
6571 	i = fr_natinit(ifs);
6572 	if (i < 0)
6573 		return -20 + i;
6574 
6575 	i = fr_stateinit(ifs);
6576 	if (i < 0)
6577 		return -30 + i;
6578 
6579 	i = fr_authinit(ifs);
6580 	if (i < 0)
6581 		return -40 + i;
6582 
6583 	i = fr_fraginit(ifs);
6584 	if (i < 0)
6585 		return -50 + i;
6586 
6587 	i = appr_init(ifs);
6588 	if (i < 0)
6589 		return -60 + i;
6590 
6591 #ifdef IPFILTER_SYNC
6592 	i = ipfsync_init(ifs);
6593 	if (i < 0)
6594 		return -70 + i;
6595 #endif
6596 #ifdef IPFILTER_SCAN
6597 	i = ipsc_init(ifs);
6598 	if (i < 0)
6599 		return -80 + i;
6600 #endif
6601 #ifdef IPFILTER_LOOKUP
6602 	i = ip_lookup_init(ifs);
6603 	if (i < 0)
6604 		return -90 + i;
6605 #endif
6606 #ifdef IPFILTER_COMPILED
6607 	ipfrule_add(ifs);
6608 #endif
6609 	return 0;
6610 }
6611 
6612 
6613 /* ------------------------------------------------------------------------ */
6614 /* Function:    fr_deinitialise                                             */
6615 /* Returns:     None.                                                       */
6616 /* Parameters:  None.                                                       */
6617 /*                                                                          */
6618 /* Call all the various subsystem cleanup routines to deallocate memory or  */
6619 /* destroy locks or whatever they've done that they need to now undo.       */
6620 /* The order here IS important as there are some cross references of        */
6621 /* internal data structures.                                                */
6622 /* ------------------------------------------------------------------------ */
6623 void fr_deinitialise(ifs)
6624 ipf_stack_t *ifs;
6625 {
6626 	fr_fragunload(ifs);
6627 	fr_authunload(ifs);
6628 	fr_natunload(ifs);
6629 	fr_stateunload(ifs);
6630 #ifdef IPFILTER_SCAN
6631 	fr_scanunload(ifs);
6632 #endif
6633 	appr_unload(ifs);
6634 
6635 #ifdef IPFILTER_COMPILED
6636 	ipfrule_remove(ifs);
6637 #endif
6638 
6639 	(void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE, ifs);
6640 	(void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE, ifs);
6641 	(void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE, ifs);
6642 	(void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE, ifs);
6643 
6644 #ifdef IPFILTER_LOOKUP
6645 	ip_lookup_unload(ifs);
6646 #endif
6647 
6648 #ifdef IPFILTER_LOG
6649 	fr_logunload(ifs);
6650 #endif
6651 }
6652 
6653 
6654 /* ------------------------------------------------------------------------ */
6655 /* Function:    fr_zerostats                                                */
6656 /* Returns:     int - 0 = success, else failure                             */
6657 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
6658 /*                                                                          */
6659 /* Copies the current statistics out to userspace and then zero's the       */
6660 /* current ones in the kernel. The lock is only held across the bzero() as  */
6661 /* the copyout may result in paging (ie network activity.)                  */
6662 /* ------------------------------------------------------------------------ */
6663 int	fr_zerostats(data, ifs)
6664 caddr_t	data;
6665 ipf_stack_t *ifs;
6666 {
6667 	friostat_t fio;
6668 	int error;
6669 
6670 	fr_getstat(&fio, ifs);
6671 	error = copyoutptr(&fio, data, sizeof(fio));
6672 	if (error)
6673 		return EFAULT;
6674 
6675 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
6676 	bzero((char *)ifs->ifs_frstats, sizeof(*ifs->ifs_frstats) * 2);
6677 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
6678 
6679 	return 0;
6680 }
6681 
6682 
6683 #ifdef _KERNEL
6684 /* ------------------------------------------------------------------------ */
6685 /* Function:    fr_resolvedest                                              */
6686 /* Returns:     Nil                                                         */
6687 /* Parameters:  fdp(IO) - pointer to destination information to resolve     */
6688 /*              v(I)    - IP protocol version to match                      */
6689 /*                                                                          */
6690 /* Looks up an interface name in the frdest structure pointed to by fdp and */
6691 /* if a matching name can be found for the particular IP protocol version   */
6692 /* then store the interface pointer in the frdest struct.  If no match is   */
6693 /* found, then set the interface pointer to be -1 as NULL is considered to  */
6694 /* indicate there is no information at all in the structure.                */
6695 /* ------------------------------------------------------------------------ */
6696 void fr_resolvedest(fdp, v, ifs)
6697 frdest_t *fdp;
6698 int v;
6699 ipf_stack_t *ifs;
6700 {
6701 	fdp->fd_ifp = NULL;
6702 
6703   	if (*fdp->fd_ifname != '\0') {
6704  		fdp->fd_ifp = GETIFP(fdp->fd_ifname, v, ifs);
6705 		if (fdp->fd_ifp == NULL)
6706 			fdp->fd_ifp = (void *)-1;
6707 	}
6708 }
6709 #endif /* _KERNEL */
6710 
6711 
6712 /* ------------------------------------------------------------------------ */
6713 /* Function:    fr_resolvenic                                               */
6714 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
6715 /*                      pointer to interface structure for NIC              */
6716 /* Parameters:  name(I) - complete interface name                           */
6717 /*              v(I)    - IP protocol version                               */
6718 /*                                                                          */
6719 /* Look for a network interface structure that firstly has a matching name  */
6720 /* to that passed in and that is also being used for that IP protocol       */
6721 /* version (necessary on some platforms where there are separate listings   */
6722 /* for both IPv4 and IPv6 on the same physical NIC.                         */
6723 /*                                                                          */
6724 /* One might wonder why name gets terminated with a \0 byte in here.  The   */
6725 /* reason is an interface name could get into the kernel structures of ipf  */
6726 /* in any number of ways and so long as they all use the same sized array   */
6727 /* to put the name in, it makes sense to ensure it gets null terminated     */
6728 /* before it is used for its intended purpose - finding its match in the    */
6729 /* kernel's list of configured interfaces.                                  */
6730 /*                                                                          */
6731 /* NOTE: This SHOULD ONLY be used with IPFilter structures that have an     */
6732 /*       array for the name that is LIFNAMSIZ bytes (at least) in length.   */
6733 /* ------------------------------------------------------------------------ */
6734 void *fr_resolvenic(name, v, ifs)
6735 char *name;
6736 int v;
6737 ipf_stack_t *ifs;
6738 {
6739 	void *nic;
6740 
6741 	if (name[0] == '\0')
6742 		return NULL;
6743 
6744 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
6745 		return NULL;
6746 	}
6747 
6748 	name[LIFNAMSIZ - 1] = '\0';
6749 
6750 	nic = GETIFP(name, v, ifs);
6751 	if (nic == NULL)
6752 		nic = (void *)-1;
6753 	return nic;
6754 }
6755 
6756 
6757 /* ------------------------------------------------------------------------ */
6758 /* Function:    ipf_expiretokens                                            */
6759 /* Returns:     None.                                                       */
6760 /* Parameters:  ifs - ipf stack instance                                    */
6761 /*                                                                          */
6762 /* This function is run every ipf tick to see if there are any tokens that  */
6763 /* have been held for too long and need to be freed up.                     */
6764 /* ------------------------------------------------------------------------ */
6765 void ipf_expiretokens(ifs)
6766 ipf_stack_t *ifs;
6767 {
6768 	ipftoken_t *it;
6769 
6770 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6771 	while ((it = ifs->ifs_ipftokenhead) != NULL) {
6772 		if (it->ipt_die > ifs->ifs_fr_ticks)
6773 			break;
6774 
6775 		ipf_freetoken(it, ifs);
6776 	}
6777 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
6778 }
6779 
6780 
6781 /* ------------------------------------------------------------------------ */
6782 /* Function:    ipf_deltoken                                                */
6783 /* Returns:     int - 0 = success, else error                               */
6784 /* Parameters:  type(I) - the token type to match                           */
6785 /*              uid(I)  - uid owning the token                              */
6786 /*              ptr(I)  - context pointer for the token                     */
6787 /*              ifs - ipf stack instance                                    */
6788 /*                                                                          */
6789 /* This function looks for a a token in the current list that matches up    */
6790 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
6791 /* call ipf_freetoken() to remove it from the list.                         */
6792 /* ------------------------------------------------------------------------ */
6793 int ipf_deltoken(type, uid, ptr, ifs)
6794 int type, uid;
6795 void *ptr;
6796 ipf_stack_t *ifs;
6797 {
6798 	ipftoken_t *it;
6799 	int error = ESRCH;
6800 
6801 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6802 	for (it = ifs->ifs_ipftokenhead; it != NULL; it = it->ipt_next)
6803 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
6804 		    uid == it->ipt_uid) {
6805 			ipf_freetoken(it, ifs);
6806 			error = 0;
6807 			break;
6808 	}
6809 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
6810 
6811 	return error;
6812 }
6813 
6814 
6815 /* ------------------------------------------------------------------------ */
6816 /* Function:    ipf_unlinktoken                                             */
6817 /* Returns:     None.                                                       */
6818 /* Parameters:  token(I) - pointer to token structure                       */
6819 /*              ifs - ipf stack instance                                    */
6820 /*                                                                          */
6821 /* This function unlinks a token structure from the linked list of tokens   */
6822 /* that it belongs to.  The head pointer never needs to be explicitly       */
6823 /* adjusted, but the tail does due to the linked list implementation.       */
6824 /* ------------------------------------------------------------------------ */
6825 static void ipf_unlinktoken(token, ifs)
6826 ipftoken_t *token;
6827 ipf_stack_t *ifs;
6828 {
6829 
6830 	if (ifs->ifs_ipftokentail == &token->ipt_next)
6831 		ifs->ifs_ipftokentail = token->ipt_pnext;
6832 
6833 	*token->ipt_pnext = token->ipt_next;
6834 	if (token->ipt_next != NULL)
6835 		token->ipt_next->ipt_pnext = token->ipt_pnext;
6836 }
6837 
6838 
6839 /* ------------------------------------------------------------------------ */
6840 /* Function:    ipf_findtoken                                               */
6841 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
6842 /* Parameters:  type(I) - the token type to match                           */
6843 /*              uid(I) - uid owning the token                               */
6844 /*              ptr(I) - context pointer for the token                      */
6845 /*              ifs - ipf stack instance                                    */
6846 /*                                                                          */
6847 /* This function looks for a live token in the list of current tokens that  */
6848 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
6849 /* allocated.  If one is found then it is moved to the top of the list of   */
6850 /* currently active tokens.                                                 */
6851 /*                                                                          */
6852 /* NOTE: It is by design that this function returns holding a read lock on  */
6853 /*       ipf_tokens.  Callers must make sure they release it!               */
6854 /* ------------------------------------------------------------------------ */
6855 ipftoken_t *ipf_findtoken(type, uid, ptr, ifs)
6856 int type, uid;
6857 void *ptr;
6858 ipf_stack_t *ifs;
6859 {
6860 	ipftoken_t *it, *new;
6861 
6862 	KMALLOC(new, ipftoken_t *);
6863 
6864 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6865 	for (it = ifs->ifs_ipftokenhead; it != NULL; it = it->ipt_next) {
6866 		if (it->ipt_alive == 0)
6867 			continue;
6868 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
6869 		    uid == it->ipt_uid)
6870 			break;
6871 	}
6872 
6873 	if (it == NULL) {
6874 		it = new;
6875 		new = NULL;
6876 		if (it == NULL)
6877 			return NULL;
6878 		it->ipt_data = NULL;
6879 		it->ipt_ctx = ptr;
6880 		it->ipt_uid = uid;
6881 		it->ipt_type = type;
6882 		it->ipt_next = NULL;
6883 		it->ipt_alive = 1;
6884 	} else {
6885 		if (new != NULL) {
6886 			KFREE(new);
6887 			new = NULL;
6888 		}
6889 
6890 		ipf_unlinktoken(it, ifs);
6891 	}
6892 	it->ipt_pnext = ifs->ifs_ipftokentail;
6893 	*ifs->ifs_ipftokentail = it;
6894 	ifs->ifs_ipftokentail = &it->ipt_next;
6895 	it->ipt_next = NULL;
6896 
6897 	it->ipt_die = ifs->ifs_fr_ticks + 2;
6898 
6899 	MUTEX_DOWNGRADE(&ifs->ifs_ipf_tokens);
6900 
6901 	return it;
6902 }
6903 
6904 
6905 /* ------------------------------------------------------------------------ */
6906 /* Function:    ipf_freetoken                                               */
6907 /* Returns:     None.                                                       */
6908 /* Parameters:  token(I) - pointer to token structure                       */
6909 /*              ifs - ipf stack instance                                    */
6910 /*                                                                          */
6911 /* This function unlinks a token from the linked list and on the path to    */
6912 /* free'ing the data, it calls the dereference function that is associated  */
6913 /* with the type of data pointed to by the token as it is considered to     */
6914 /* hold a reference to it.                                                  */
6915 /* ------------------------------------------------------------------------ */
6916 void ipf_freetoken(token, ifs)
6917 ipftoken_t *token;
6918 ipf_stack_t *ifs;
6919 {
6920 	void *data, **datap;
6921 
6922 	ipf_unlinktoken(token, ifs);
6923 
6924 	data = token->ipt_data;
6925 	datap = &data;
6926 
6927 	if ((data != NULL) && (data != (void *)-1)) {
6928 		switch (token->ipt_type)
6929 		{
6930 		case IPFGENITER_IPF :
6931 			(void)fr_derefrule((frentry_t **)datap, ifs);
6932 			break;
6933 		case IPFGENITER_IPNAT :
6934 			WRITE_ENTER(&ifs->ifs_ipf_nat);
6935 			fr_ipnatderef((ipnat_t **)datap, ifs);
6936 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
6937 			break;
6938 		case IPFGENITER_NAT :
6939 			fr_natderef((nat_t **)datap, ifs);
6940 			break;
6941 		case IPFGENITER_STATE :
6942 			fr_statederef((ipstate_t **)datap, ifs);
6943 			break;
6944 		case IPFGENITER_FRAG :
6945 			fr_fragderef((ipfr_t **)datap, &ifs->ifs_ipf_frag, ifs);
6946 			break;
6947 		case IPFGENITER_NATFRAG :
6948  			fr_fragderef((ipfr_t **)datap,
6949 				     &ifs->ifs_ipf_natfrag, ifs);
6950 			break;
6951 		case IPFGENITER_HOSTMAP :
6952 			WRITE_ENTER(&ifs->ifs_ipf_nat);
6953 			fr_hostmapdel((hostmap_t **)datap);
6954 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
6955 			break;
6956 		default :
6957 			(void) ip_lookup_iterderef(token->ipt_type, data, ifs);
6958 			break;
6959 		}
6960 	}
6961 
6962 	KFREE(token);
6963 }
6964 
6965 
6966 /* ------------------------------------------------------------------------ */
6967 /* Function:    ipf_getnextrule                                             */
6968 /* Returns:     int - 0 = success, else error                               */
6969 /* Parameters:  t(I)   - pointer to destination information to resolve      */
6970 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
6971 /*              ifs - ipf stack instance                                    */
6972 /*                                                                          */
6973 /* This function's first job is to bring in the ipfruleiter_t structure via */
6974 /* the ipfobj_t structure to determine what should be the next rule to      */
6975 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
6976 /* find the 'next rule'.  This may include searching rule group lists or    */
6977 /* just be as simple as looking at the 'next' field in the rule structure.  */
6978 /* When we have found the rule to return, increase its reference count and  */
6979 /* if we used an existing rule to get here, decrease its reference count.   */
6980 /* ------------------------------------------------------------------------ */
6981 int ipf_getnextrule(t, ptr, ifs)
6982 ipftoken_t *t;
6983 void *ptr;
6984 ipf_stack_t *ifs;
6985 {
6986 	frentry_t *fr, *next, zero;
6987 	int error, out, count;
6988 	ipfruleiter_t it;
6989 	frgroup_t *fg;
6990 	char *dst;
6991 
6992 	if (t == NULL || ptr == NULL)
6993 		return EFAULT;
6994 	error = fr_inobj(ptr, &it, IPFOBJ_IPFITER);
6995 	if (error != 0)
6996 		return error;
6997 	if ((it.iri_ver != AF_INET) && (it.iri_ver != AF_INET6))
6998 		return EINVAL;
6999 	if ((it.iri_inout < 0) || (it.iri_inout > 3))
7000 		return EINVAL;
7001 	if (it.iri_nrules == 0)
7002 		return EINVAL;
7003 	if ((it.iri_active != 0) && (it.iri_active != 1))
7004 		return EINVAL;
7005 	if (it.iri_rule == NULL)
7006 		return EFAULT;
7007 
7008 	/*
7009 	 * Use bitmask on it.iri_inout to determine direction.
7010 	 * F_OUT (1) and F_ACOUT (3) mask to out = 1, while
7011 	 * F_IN (0) and F_ACIN (2) mask to out = 0.
7012 	 */
7013 	out = it.iri_inout & F_OUT;
7014 	READ_ENTER(&ifs->ifs_ipf_mutex);
7015 
7016 	/*
7017 	 * Retrieve "previous" entry from token and find the next entry.
7018 	 */
7019 	fr = t->ipt_data;
7020 	if (fr == NULL) {
7021 		if (*it.iri_group == '\0') {
7022 			/*
7023 			 * Use bitmask again to determine accounting or not.
7024 			 * F_ACIN will mask to accounting cases F_ACIN (2)
7025 			 * or F_ACOUT (3), but not F_IN or F_OUT.
7026 			 */
7027 			if ((it.iri_inout & F_ACIN) != 0) {
7028 				if (it.iri_ver == AF_INET)
7029 					next = ifs->ifs_ipacct
7030 					    [out][it.iri_active];
7031 				else
7032 					next = ifs->ifs_ipacct6
7033 					    [out][it.iri_active];
7034 			} else {
7035 				if (it.iri_ver == AF_INET)
7036 					next = ifs->ifs_ipfilter
7037 					    [out][it.iri_active];
7038 				else
7039 					next = ifs->ifs_ipfilter6
7040 					    [out][it.iri_active];
7041 			}
7042 		} else {
7043 			fg = fr_findgroup(it.iri_group, IPL_LOGIPF,
7044 					  it.iri_active, NULL, ifs);
7045 			if (fg != NULL)
7046 				next = fg->fg_start;
7047 			else
7048 				next = NULL;
7049 		}
7050 	} else {
7051 		next = fr->fr_next;
7052 	}
7053 
7054 	dst = (char *)it.iri_rule;
7055 	/*
7056 	 * The ipfruleiter may ask for more than 1 rule at a time to be
7057 	 * copied out, so long as that many exist in the list to start with!
7058 	 */
7059 	for (count = it.iri_nrules; count > 0; count--) {
7060 		/*
7061 		 * If we found an entry, add reference to it and update token.
7062 		 * Otherwise, zero out data to be returned and NULL out token.
7063 		 */
7064 		if (next != NULL) {
7065 			MUTEX_ENTER(&next->fr_lock);
7066 			next->fr_ref++;
7067 			MUTEX_EXIT(&next->fr_lock);
7068 			t->ipt_data = next;
7069 		} else {
7070 			bzero(&zero, sizeof(zero));
7071 			next = &zero;
7072 			t->ipt_data = NULL;
7073 		}
7074 
7075 		/*
7076 		 * Now that we have ref, it's save to give up lock.
7077 		 */
7078 		RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
7079 
7080 		/*
7081 		 * Copy out data and clean up references and token as needed.
7082 		 */
7083 		error = COPYOUT(next, dst, sizeof(*next));
7084 		if (error != 0)
7085 			error = EFAULT;
7086 		if (t->ipt_data == NULL) {
7087 			ipf_freetoken(t, ifs);
7088 			break;
7089 		} else {
7090 			if (fr != NULL)
7091 				(void) fr_derefrule(&fr, ifs);
7092 			if (next->fr_data != NULL) {
7093 				dst += sizeof(*next);
7094 				error = COPYOUT(next->fr_data, dst,
7095 						next->fr_dsize);
7096 				if (error != 0)
7097 					error = EFAULT;
7098 				else
7099 					dst += next->fr_dsize;
7100 			}
7101 			if (next->fr_next == NULL) {
7102 				ipf_freetoken(t, ifs);
7103 				break;
7104 			}
7105 		}
7106 
7107 		if ((count == 1) || (error != 0))
7108 			break;
7109 
7110 		READ_ENTER(&ifs->ifs_ipf_mutex);
7111 		fr = next;
7112 		next = fr->fr_next;
7113 	}
7114 
7115 	return error;
7116 }
7117 
7118 
7119 /* ------------------------------------------------------------------------ */
7120 /* Function:    fr_frruleiter                                               */
7121 /* Returns:     int - 0 = success, else error                               */
7122 /* Parameters:  data(I) - the token type to match                           */
7123 /*              uid(I) - uid owning the token                               */
7124 /*              ptr(I) - context pointer for the token                      */
7125 /*              ifs - ipf stack instance                                    */
7126 /*                                                                          */
7127 /* This function serves as a stepping stone between fr_ipf_ioctl and        */
7128 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7129 /* the process doing the ioctl and use that to ask for the next rule.       */
7130 /* ------------------------------------------------------------------------ */
7131 int ipf_frruleiter(data, uid, ctx, ifs)
7132 void *data, *ctx;
7133 int uid;
7134 ipf_stack_t *ifs;
7135 {
7136 	ipftoken_t *token;
7137 	int error;
7138 
7139 	token = ipf_findtoken(IPFGENITER_IPF, uid, ctx, ifs);
7140 	if (token != NULL)
7141 		error = ipf_getnextrule(token, data, ifs);
7142 	else
7143 		error = EFAULT;
7144 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
7145 
7146 	return error;
7147 }
7148 
7149 
7150 /* ------------------------------------------------------------------------ */
7151 /* Function:    ipf_geniter                                                 */
7152 /* Returns:     int - 0 = success, else error                               */
7153 /* Parameters:  token(I) - pointer to ipftoken structure                    */
7154 /*              itp(I) - pointer to ipfgeniter structure                    */
7155 /*              ifs - ipf stack instance                                    */
7156 /*                                                                          */
7157 /* Generic iterator called from ipf_genericiter.  Currently only used for   */
7158 /* walking through list of fragments.                                       */
7159 /* ------------------------------------------------------------------------ */
7160 int ipf_geniter(token, itp, ifs)
7161 ipftoken_t *token;
7162 ipfgeniter_t *itp;
7163 ipf_stack_t *ifs;
7164 {
7165 	int error;
7166 
7167 	switch (itp->igi_type)
7168 	{
7169 	case IPFGENITER_FRAG :
7170 		error = fr_nextfrag(token, itp, &ifs->ifs_ipfr_list,
7171 				    &ifs->ifs_ipfr_tail, &ifs->ifs_ipf_frag,
7172 				    ifs);
7173 		break;
7174 	default :
7175 		error = EINVAL;
7176 		break;
7177 	}
7178 
7179 	return error;
7180 }
7181 
7182 
7183 /* ------------------------------------------------------------------------ */
7184 /* Function:    ipf_genericiter                                             */
7185 /* Returns:     int - 0 = success, else error                               */
7186 /* Parameters:  data(I) - the token type to match                           */
7187 /*              uid(I) - uid owning the token                               */
7188 /*              ptr(I) - context pointer for the token                      */
7189 /*              ifs - ipf stack instance                                    */
7190 /*                                                                          */
7191 /* This function serves as a stepping stone between fr_ipf_ioctl and        */
7192 /* ipf_geniter when handling SIOCGENITER.  It's role is to find the right   */
7193 /* token in the kernel for the process using the ioctl, and to use that     */
7194 /* token when calling ipf_geniter.                                          */
7195 /* ------------------------------------------------------------------------ */
7196 int ipf_genericiter(data, uid, ctx, ifs)
7197 void *data, *ctx;
7198 int uid;
7199 ipf_stack_t *ifs;
7200 {
7201 	ipftoken_t *token;
7202 	ipfgeniter_t iter;
7203 	int error;
7204 
7205 	error = fr_inobj(data, &iter, IPFOBJ_GENITER);
7206 	if (error != 0)
7207 		return error;
7208 
7209 	token = ipf_findtoken(iter.igi_type, uid, ctx, ifs);
7210 	if (token != NULL) {
7211 		token->ipt_subtype = iter.igi_type;
7212 		error = ipf_geniter(token, &iter, ifs);
7213 	} else
7214 		error = EFAULT;
7215 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
7216 
7217 	return error;
7218 }
7219