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