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