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