fil.c revision 348820
1/*	$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 348820 2019-06-08 22:27:09Z cy $	*/
2
3/*
4 * Copyright (C) 2012 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Copyright 2008 Sun Microsystems.
9 *
10 * $Id$
11 *
12 */
13#if defined(KERNEL) || defined(_KERNEL)
14# undef KERNEL
15# undef _KERNEL
16# define        KERNEL	1
17# define        _KERNEL	1
18#endif
19#include <sys/errno.h>
20#include <sys/types.h>
21#include <sys/param.h>
22#include <sys/time.h>
23#if defined(_KERNEL) && defined(__FreeBSD_version)
24#  if !defined(IPFILTER_LKM)
25#   include "opt_inet6.h"
26#  endif
27# include <sys/filio.h>
28#else
29# include <sys/ioctl.h>
30#endif
31#if defined(__SVR4) || defined(sun) /* SOLARIS */
32# include <sys/filio.h>
33#endif
34# include <sys/fcntl.h>
35#if defined(_KERNEL)
36# include <sys/systm.h>
37# include <sys/file.h>
38#else
39# include <stdio.h>
40# include <string.h>
41# include <stdlib.h>
42# include <stddef.h>
43# include <sys/file.h>
44# define _KERNEL
45# include <sys/uio.h>
46# undef _KERNEL
47#endif
48#if !defined(__SVR4)
49# include <sys/mbuf.h>
50#else
51#  include <sys/byteorder.h>
52# if (SOLARIS2 < 5) && defined(sun)
53#  include <sys/dditypes.h>
54# endif
55#endif
56# include <sys/protosw.h>
57#include <sys/socket.h>
58#include <net/if.h>
59#ifdef sun
60# include <net/af.h>
61#endif
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/tcp.h>
66# include <netinet/udp.h>
67# include <netinet/ip_icmp.h>
68#include "netinet/ip_compat.h"
69#ifdef	USE_INET6
70# include <netinet/icmp6.h>
71# if !SOLARIS && defined(_KERNEL)
72#  include <netinet6/in6_var.h>
73# endif
74#endif
75#include "netinet/ip_fil.h"
76#include "netinet/ip_nat.h"
77#include "netinet/ip_frag.h"
78#include "netinet/ip_state.h"
79#include "netinet/ip_proxy.h"
80#include "netinet/ip_auth.h"
81#ifdef IPFILTER_SCAN
82# include "netinet/ip_scan.h"
83#endif
84#include "netinet/ip_sync.h"
85#include "netinet/ip_lookup.h"
86#include "netinet/ip_pool.h"
87#include "netinet/ip_htable.h"
88#ifdef IPFILTER_COMPILED
89# include "netinet/ip_rules.h"
90#endif
91#if defined(IPFILTER_BPF) && defined(_KERNEL)
92# include <net/bpf.h>
93#endif
94#if defined(__FreeBSD_version)
95# include <sys/malloc.h>
96#endif
97#include "netinet/ipl.h"
98
99#if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100# include <sys/callout.h>
101extern struct callout ipf_slowtimer_ch;
102#endif
103/* END OF INCLUDES */
104
105#if !defined(lint)
106static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
107static const char rcsid[] = "@(#)$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 348820 2019-06-08 22:27:09Z cy $";
108/* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
109#endif
110
111#ifndef	_KERNEL
112# include "ipf.h"
113# include "ipt.h"
114extern	int	opts;
115extern	int	blockreason;
116#endif /* _KERNEL */
117
118#define	LBUMP(x)	softc->x++
119#define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
120
121static	INLINE int	ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122static	u_32_t		ipf_checkcipso __P((fr_info_t *, u_char *, int));
123static	u_32_t		ipf_checkripso __P((u_char *));
124static	u_32_t		ipf_decaps __P((fr_info_t *, u_32_t, int));
125#ifdef IPFILTER_LOG
126static	frentry_t	*ipf_dolog __P((fr_info_t *, u_32_t *));
127#endif
128static	int		ipf_flushlist __P((ipf_main_softc_t *, int *,
129					   frentry_t **));
130static	int		ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
131					      int));
132static	ipfunc_t	ipf_findfunc __P((ipfunc_t));
133static	void		*ipf_findlookup __P((ipf_main_softc_t *, int,
134					     frentry_t *,
135					     i6addr_t *, i6addr_t *));
136static	frentry_t	*ipf_firewall __P((fr_info_t *, u_32_t *));
137static	int		ipf_fr_matcharray __P((fr_info_t *, int *));
138static	int		ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
139					    void *));
140static	void		ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141static	int		ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142static	int		ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
143					 ipfgeniter_t *));
144static	void		ipf_getstat __P((ipf_main_softc_t *,
145					 struct friostat *, int));
146static	int		ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147static	void		ipf_group_free __P((frgroup_t *));
148static	int		ipf_grpmapfini __P((struct ipf_main_softc_s *,
149					    frentry_t *));
150static	int		ipf_grpmapinit __P((struct ipf_main_softc_s *,
151					    frentry_t *));
152static	frentry_t	*ipf_nextrule __P((ipf_main_softc_t *, int, int,
153					   frentry_t *, int));
154static	int		ipf_portcheck __P((frpcmp_t *, u_32_t));
155static	INLINE int	ipf_pr_ah __P((fr_info_t *));
156static	INLINE void	ipf_pr_esp __P((fr_info_t *));
157static	INLINE void	ipf_pr_gre __P((fr_info_t *));
158static	INLINE void	ipf_pr_udp __P((fr_info_t *));
159static	INLINE void	ipf_pr_tcp __P((fr_info_t *));
160static	INLINE void	ipf_pr_icmp __P((fr_info_t *));
161static	INLINE void	ipf_pr_ipv4hdr __P((fr_info_t *));
162static	INLINE void	ipf_pr_short __P((fr_info_t *, int));
163static	INLINE int	ipf_pr_tcpcommon __P((fr_info_t *));
164static	INLINE int	ipf_pr_udpcommon __P((fr_info_t *));
165static	void		ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
166					     int, int));
167static	void		ipf_rule_expire_insert __P((ipf_main_softc_t *,
168						    frentry_t *, int));
169static	int		ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
170					  void *));
171static	void		ipf_token_flush __P((ipf_main_softc_t *));
172static	void		ipf_token_unlink __P((ipf_main_softc_t *,
173					      ipftoken_t *));
174static	ipftuneable_t	*ipf_tune_findbyname __P((ipftuneable_t *,
175						  const char *));
176static	ipftuneable_t	*ipf_tune_findbycookie __P((ipftuneable_t **, void *,
177						    void **));
178static	int		ipf_updateipid __P((fr_info_t *));
179static	int		ipf_settimeout __P((struct ipf_main_softc_s *,
180					    struct ipftuneable *,
181					    ipftuneval_t *));
182#if !defined(_KERNEL) || SOLARIS
183static	int		ppsratecheck(struct timeval *, int *, int);
184#endif
185
186
187/*
188 * bit values for identifying presence of individual IP options
189 * All of these tables should be ordered by increasing key value on the left
190 * hand side to allow for binary searching of the array and include a trailer
191 * with a 0 for the bitmask for linear searches to easily find the end with.
192 */
193static const	struct	optlist	ipopts[20] = {
194	{ IPOPT_NOP,	0x000001 },
195	{ IPOPT_RR,	0x000002 },
196	{ IPOPT_ZSU,	0x000004 },
197	{ IPOPT_MTUP,	0x000008 },
198	{ IPOPT_MTUR,	0x000010 },
199	{ IPOPT_ENCODE,	0x000020 },
200	{ IPOPT_TS,	0x000040 },
201	{ IPOPT_TR,	0x000080 },
202	{ IPOPT_SECURITY, 0x000100 },
203	{ IPOPT_LSRR,	0x000200 },
204	{ IPOPT_E_SEC,	0x000400 },
205	{ IPOPT_CIPSO,	0x000800 },
206	{ IPOPT_SATID,	0x001000 },
207	{ IPOPT_SSRR,	0x002000 },
208	{ IPOPT_ADDEXT,	0x004000 },
209	{ IPOPT_VISA,	0x008000 },
210	{ IPOPT_IMITD,	0x010000 },
211	{ IPOPT_EIP,	0x020000 },
212	{ IPOPT_FINN,	0x040000 },
213	{ 0,		0x000000 }
214};
215
216#ifdef USE_INET6
217static const struct optlist ip6exthdr[] = {
218	{ IPPROTO_HOPOPTS,		0x000001 },
219	{ IPPROTO_IPV6,			0x000002 },
220	{ IPPROTO_ROUTING,		0x000004 },
221	{ IPPROTO_FRAGMENT,		0x000008 },
222	{ IPPROTO_ESP,			0x000010 },
223	{ IPPROTO_AH,			0x000020 },
224	{ IPPROTO_NONE,			0x000040 },
225	{ IPPROTO_DSTOPTS,		0x000080 },
226	{ IPPROTO_MOBILITY,		0x000100 },
227	{ 0,				0 }
228};
229#endif
230
231/*
232 * bit values for identifying presence of individual IP security options
233 */
234static const	struct	optlist	secopt[8] = {
235	{ IPSO_CLASS_RES4,	0x01 },
236	{ IPSO_CLASS_TOPS,	0x02 },
237	{ IPSO_CLASS_SECR,	0x04 },
238	{ IPSO_CLASS_RES3,	0x08 },
239	{ IPSO_CLASS_CONF,	0x10 },
240	{ IPSO_CLASS_UNCL,	0x20 },
241	{ IPSO_CLASS_RES2,	0x40 },
242	{ IPSO_CLASS_RES1,	0x80 }
243};
244
245char	ipfilter_version[] = IPL_VERSION;
246
247int	ipf_features = 0
248#ifdef	IPFILTER_LKM
249		| IPF_FEAT_LKM
250#endif
251#ifdef	IPFILTER_LOG
252		| IPF_FEAT_LOG
253#endif
254		| IPF_FEAT_LOOKUP
255#ifdef	IPFILTER_BPF
256		| IPF_FEAT_BPF
257#endif
258#ifdef	IPFILTER_COMPILED
259		| IPF_FEAT_COMPILED
260#endif
261#ifdef	IPFILTER_CKSUM
262		| IPF_FEAT_CKSUM
263#endif
264		| IPF_FEAT_SYNC
265#ifdef	IPFILTER_SCAN
266		| IPF_FEAT_SCAN
267#endif
268#ifdef	USE_INET6
269		| IPF_FEAT_IPV6
270#endif
271	;
272
273
274/*
275 * Table of functions available for use with call rules.
276 */
277static ipfunc_resolve_t ipf_availfuncs[] = {
278	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280	{ "",	      NULL,	      NULL,	      NULL }
281};
282
283static ipftuneable_t ipf_main_tuneables[] = {
284	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285		"ipf_flags",		0,	0xffffffff,
286		stsizeof(ipf_main_softc_t, ipf_flags),
287		0,			NULL,	NULL },
288	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
289		"active",		0,	0,
290		stsizeof(ipf_main_softc_t, ipf_active),
291		IPFT_RDONLY,		NULL,	NULL },
292	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293		"control_forwarding",	0, 1,
294		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
295		0,			NULL,	NULL },
296	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
297		"update_ipid",		0,	1,
298		stsizeof(ipf_main_softc_t, ipf_update_ipid),
299		0,			NULL,	NULL },
300	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
301		"chksrc",		0,	1,
302		stsizeof(ipf_main_softc_t, ipf_chksrc),
303		0,			NULL,	NULL },
304	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
305		"min_ttl",		0,	1,
306		stsizeof(ipf_main_softc_t, ipf_minttl),
307		0,			NULL,	NULL },
308	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309		"icmp_minfragmtu",	0,	1,
310		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
311		0,			NULL,	NULL },
312	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313		"default_pass",		0,	0xffffffff,
314		stsizeof(ipf_main_softc_t, ipf_pass),
315		0,			NULL,	NULL },
316	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317		"tcp_idle_timeout",	1,	0x7fffffff,
318		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319		0,			NULL,	ipf_settimeout },
320	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321		"tcp_close_wait",	1,	0x7fffffff,
322		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323		0,			NULL,	ipf_settimeout },
324	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325		"tcp_last_ack",		1,	0x7fffffff,
326		stsizeof(ipf_main_softc_t, ipf_tcplastack),
327		0,			NULL,	ipf_settimeout },
328	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329		"tcp_timeout",		1,	0x7fffffff,
330		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331		0,			NULL,	ipf_settimeout },
332	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333		"tcp_syn_sent",		1,	0x7fffffff,
334		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335		0,			NULL,	ipf_settimeout },
336	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337		"tcp_syn_received",	1,	0x7fffffff,
338		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339		0,			NULL,	ipf_settimeout },
340	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341		"tcp_closed",		1,	0x7fffffff,
342		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343		0,			NULL,	ipf_settimeout },
344	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345		"tcp_half_closed",	1,	0x7fffffff,
346		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347		0,			NULL,	ipf_settimeout },
348	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349		"tcp_time_wait",	1,	0x7fffffff,
350		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351		0,			NULL,	ipf_settimeout },
352	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353		"udp_timeout",		1,	0x7fffffff,
354		stsizeof(ipf_main_softc_t, ipf_udptimeout),
355		0,			NULL,	ipf_settimeout },
356	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357		"udp_ack_timeout",	1,	0x7fffffff,
358		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359		0,			NULL,	ipf_settimeout },
360	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361		"icmp_timeout",		1,	0x7fffffff,
362		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363		0,			NULL,	ipf_settimeout },
364	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365		"icmp_ack_timeout",	1,	0x7fffffff,
366		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367		0,			NULL,	ipf_settimeout },
368	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369		"ip_timeout",		1,	0x7fffffff,
370		stsizeof(ipf_main_softc_t, ipf_iptimeout),
371		0,			NULL,	ipf_settimeout },
372#if defined(INSTANCES) && defined(_KERNEL)
373	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374		"intercept_loopback",	0,	1,
375		stsizeof(ipf_main_softc_t, ipf_get_loopback),
376		0,			NULL,	ipf_set_loopback },
377#endif
378	{ { 0 },
379		NULL,			0,	0,
380		0,
381		0,			NULL,	NULL }
382};
383
384
385/*
386 * The next section of code is a collection of small routines that set
387 * fields in the fr_info_t structure passed based on properties of the
388 * current packet.  There are different routines for the same protocol
389 * for each of IPv4 and IPv6.  Adding a new protocol, for which there
390 * will "special" inspection for setup, is now more easily done by adding
391 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392 * adding more code to a growing switch statement.
393 */
394#ifdef USE_INET6
395static	INLINE int	ipf_pr_ah6 __P((fr_info_t *));
396static	INLINE void	ipf_pr_esp6 __P((fr_info_t *));
397static	INLINE void	ipf_pr_gre6 __P((fr_info_t *));
398static	INLINE void	ipf_pr_udp6 __P((fr_info_t *));
399static	INLINE void	ipf_pr_tcp6 __P((fr_info_t *));
400static	INLINE void	ipf_pr_icmp6 __P((fr_info_t *));
401static	INLINE void	ipf_pr_ipv6hdr __P((fr_info_t *));
402static	INLINE void	ipf_pr_short6 __P((fr_info_t *, int));
403static	INLINE int	ipf_pr_hopopts6 __P((fr_info_t *));
404static	INLINE int	ipf_pr_mobility6 __P((fr_info_t *));
405static	INLINE int	ipf_pr_routing6 __P((fr_info_t *));
406static	INLINE int	ipf_pr_dstopts6 __P((fr_info_t *));
407static	INLINE int	ipf_pr_fragment6 __P((fr_info_t *));
408static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
409
410
411/* ------------------------------------------------------------------------ */
412/* Function:    ipf_pr_short6                                               */
413/* Returns:     void                                                        */
414/* Parameters:  fin(I)  - pointer to packet information                     */
415/*              xmin(I) - minimum header size                               */
416/*                                                                          */
417/* IPv6 Only                                                                */
418/* This is function enforces the 'is a packet too short to be legit' rule   */
419/* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
420/* for ipf_pr_short() for more details.                                     */
421/* ------------------------------------------------------------------------ */
422static INLINE void
423ipf_pr_short6(fin, xmin)
424	fr_info_t *fin;
425	int xmin;
426{
427
428	if (fin->fin_dlen < xmin)
429		fin->fin_flx |= FI_SHORT;
430}
431
432
433/* ------------------------------------------------------------------------ */
434/* Function:    ipf_pr_ipv6hdr                                              */
435/* Returns:     void                                                        */
436/* Parameters:  fin(I) - pointer to packet information                      */
437/*                                                                          */
438/* IPv6 Only                                                                */
439/* Copy values from the IPv6 header into the fr_info_t struct and call the  */
440/* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
441/* analyzer may pullup or free the packet itself so we need to be vigiliant */
442/* of that possibility arising.                                             */
443/* ------------------------------------------------------------------------ */
444static INLINE void
445ipf_pr_ipv6hdr(fin)
446	fr_info_t *fin;
447{
448	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449	int p, go = 1, i, hdrcount;
450	fr_ip_t *fi = &fin->fin_fi;
451
452	fin->fin_off = 0;
453
454	fi->fi_tos = 0;
455	fi->fi_optmsk = 0;
456	fi->fi_secmsk = 0;
457	fi->fi_auth = 0;
458
459	p = ip6->ip6_nxt;
460	fin->fin_crc = p;
461	fi->fi_ttl = ip6->ip6_hlim;
462	fi->fi_src.in6 = ip6->ip6_src;
463	fin->fin_crc += fi->fi_src.i6[0];
464	fin->fin_crc += fi->fi_src.i6[1];
465	fin->fin_crc += fi->fi_src.i6[2];
466	fin->fin_crc += fi->fi_src.i6[3];
467	fi->fi_dst.in6 = ip6->ip6_dst;
468	fin->fin_crc += fi->fi_dst.i6[0];
469	fin->fin_crc += fi->fi_dst.i6[1];
470	fin->fin_crc += fi->fi_dst.i6[2];
471	fin->fin_crc += fi->fi_dst.i6[3];
472	fin->fin_id = 0;
473	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
475
476	hdrcount = 0;
477	while (go && !(fin->fin_flx & FI_SHORT)) {
478		switch (p)
479		{
480		case IPPROTO_UDP :
481			ipf_pr_udp6(fin);
482			go = 0;
483			break;
484
485		case IPPROTO_TCP :
486			ipf_pr_tcp6(fin);
487			go = 0;
488			break;
489
490		case IPPROTO_ICMPV6 :
491			ipf_pr_icmp6(fin);
492			go = 0;
493			break;
494
495		case IPPROTO_GRE :
496			ipf_pr_gre6(fin);
497			go = 0;
498			break;
499
500		case IPPROTO_HOPOPTS :
501			p = ipf_pr_hopopts6(fin);
502			break;
503
504		case IPPROTO_MOBILITY :
505			p = ipf_pr_mobility6(fin);
506			break;
507
508		case IPPROTO_DSTOPTS :
509			p = ipf_pr_dstopts6(fin);
510			break;
511
512		case IPPROTO_ROUTING :
513			p = ipf_pr_routing6(fin);
514			break;
515
516		case IPPROTO_AH :
517			p = ipf_pr_ah6(fin);
518			break;
519
520		case IPPROTO_ESP :
521			ipf_pr_esp6(fin);
522			go = 0;
523			break;
524
525		case IPPROTO_IPV6 :
526			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527				if (ip6exthdr[i].ol_val == p) {
528					fin->fin_flx |= ip6exthdr[i].ol_bit;
529					break;
530				}
531			go = 0;
532			break;
533
534		case IPPROTO_NONE :
535			go = 0;
536			break;
537
538		case IPPROTO_FRAGMENT :
539			p = ipf_pr_fragment6(fin);
540			/*
541			 * Given that the only fragments we want to let through
542			 * (where fin_off != 0) are those where the non-first
543			 * fragments only have data, we can safely stop looking
544			 * at headers if this is a non-leading fragment.
545			 */
546			if (fin->fin_off != 0)
547				go = 0;
548			break;
549
550		default :
551			go = 0;
552			break;
553		}
554		hdrcount++;
555
556		/*
557		 * It is important to note that at this point, for the
558		 * extension headers (go != 0), the entire header may not have
559		 * been pulled up when the code gets to this point.  This is
560		 * only done for "go != 0" because the other header handlers
561		 * will all pullup their complete header.  The other indicator
562		 * of an incomplete packet is that this was just an extension
563		 * header.
564		 */
565		if ((go != 0) && (p != IPPROTO_NONE) &&
566		    (ipf_pr_pullup(fin, 0) == -1)) {
567			p = IPPROTO_NONE;
568			break;
569		}
570	}
571
572	/*
573	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574	 * and destroy whatever packet was here.  The caller of this function
575	 * expects us to return if there is a problem with ipf_pullup.
576	 */
577	if (fin->fin_m == NULL) {
578		ipf_main_softc_t *softc = fin->fin_main_soft;
579
580		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
581		return;
582	}
583
584	fi->fi_p = p;
585
586	/*
587	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
589	 */
590	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591		ipf_main_softc_t *softc = fin->fin_main_soft;
592
593		fin->fin_flx |= FI_BAD;
594		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
597	}
598}
599
600
601/* ------------------------------------------------------------------------ */
602/* Function:    ipf_pr_ipv6exthdr                                           */
603/* Returns:     struct ip6_ext * - pointer to the start of the next header  */
604/*                                 or NULL if there is a prolblem.          */
605/* Parameters:  fin(I)      - pointer to packet information                 */
606/*              multiple(I) - flag indicating yes/no if multiple occurances */
607/*                            of this extension header are allowed.         */
608/*              proto(I)    - protocol number for this extension header     */
609/*                                                                          */
610/* IPv6 Only                                                                */
611/* This function embodies a number of common checks that all IPv6 extension */
612/* headers must be subjected to.  For example, making sure the packet is    */
613/* big enough for it to be in, checking if it is repeated and setting a     */
614/* flag to indicate its presence.                                           */
615/* ------------------------------------------------------------------------ */
616static INLINE struct ip6_ext *
617ipf_pr_ipv6exthdr(fin, multiple, proto)
618	fr_info_t *fin;
619	int multiple, proto;
620{
621	ipf_main_softc_t *softc = fin->fin_main_soft;
622	struct ip6_ext *hdr;
623	u_short shift;
624	int i;
625
626	fin->fin_flx |= FI_V6EXTHDR;
627
628				/* 8 is default length of extension hdr */
629	if ((fin->fin_dlen - 8) < 0) {
630		fin->fin_flx |= FI_SHORT;
631		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
632		return NULL;
633	}
634
635	if (ipf_pr_pullup(fin, 8) == -1) {
636		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
637		return NULL;
638	}
639
640	hdr = fin->fin_dp;
641	switch (proto)
642	{
643	case IPPROTO_FRAGMENT :
644		shift = 8;
645		break;
646	default :
647		shift = 8 + (hdr->ip6e_len << 3);
648		break;
649	}
650
651	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
652		fin->fin_flx |= FI_BAD;
653		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
655		return NULL;
656	}
657
658	fin->fin_dp = (char *)fin->fin_dp + shift;
659	fin->fin_dlen -= shift;
660
661	/*
662	 * If we have seen a fragment header, do not set any flags to indicate
663	 * the presence of this extension header as it has no impact on the
664	 * end result until after it has been defragmented.
665	 */
666	if (fin->fin_flx & FI_FRAG)
667		return hdr;
668
669	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670		if (ip6exthdr[i].ol_val == proto) {
671			/*
672			 * Most IPv6 extension headers are only allowed once.
673			 */
674			if ((multiple == 0) &&
675			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676				fin->fin_flx |= FI_BAD;
677				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
678			} else
679				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
680			break;
681		}
682
683	return hdr;
684}
685
686
687/* ------------------------------------------------------------------------ */
688/* Function:    ipf_pr_hopopts6                                             */
689/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
690/* Parameters:  fin(I) - pointer to packet information                      */
691/*                                                                          */
692/* IPv6 Only                                                                */
693/* This is function checks pending hop by hop options extension header      */
694/* ------------------------------------------------------------------------ */
695static INLINE int
696ipf_pr_hopopts6(fin)
697	fr_info_t *fin;
698{
699	struct ip6_ext *hdr;
700
701	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
702	if (hdr == NULL)
703		return IPPROTO_NONE;
704	return hdr->ip6e_nxt;
705}
706
707
708/* ------------------------------------------------------------------------ */
709/* Function:    ipf_pr_mobility6                                            */
710/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
711/* Parameters:  fin(I) - pointer to packet information                      */
712/*                                                                          */
713/* IPv6 Only                                                                */
714/* This is function checks the IPv6 mobility extension header               */
715/* ------------------------------------------------------------------------ */
716static INLINE int
717ipf_pr_mobility6(fin)
718	fr_info_t *fin;
719{
720	struct ip6_ext *hdr;
721
722	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
723	if (hdr == NULL)
724		return IPPROTO_NONE;
725	return hdr->ip6e_nxt;
726}
727
728
729/* ------------------------------------------------------------------------ */
730/* Function:    ipf_pr_routing6                                             */
731/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
732/* Parameters:  fin(I) - pointer to packet information                      */
733/*                                                                          */
734/* IPv6 Only                                                                */
735/* This is function checks pending routing extension header                 */
736/* ------------------------------------------------------------------------ */
737static INLINE int
738ipf_pr_routing6(fin)
739	fr_info_t *fin;
740{
741	struct ip6_routing *hdr;
742
743	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
744	if (hdr == NULL)
745		return IPPROTO_NONE;
746
747	switch (hdr->ip6r_type)
748	{
749	case 0 :
750		/*
751		 * Nasty extension header length?
752		 */
753		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755			ipf_main_softc_t *softc = fin->fin_main_soft;
756
757			fin->fin_flx |= FI_BAD;
758			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
760			return IPPROTO_NONE;
761		}
762		break;
763
764	default :
765		break;
766	}
767
768	return hdr->ip6r_nxt;
769}
770
771
772/* ------------------------------------------------------------------------ */
773/* Function:    ipf_pr_fragment6                                            */
774/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
775/* Parameters:  fin(I) - pointer to packet information                      */
776/*                                                                          */
777/* IPv6 Only                                                                */
778/* Examine the IPv6 fragment header and extract fragment offset information.*/
779/*                                                                          */
780/* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781/* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
782/* packets with a fragment header can fit into.  They are as follows:       */
783/*                                                                          */
784/* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
785/* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
786/* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
787/* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
788/* 5.  [IPV6][0-n EH][FH][data]                                             */
789/*                                                                          */
790/* IPV6 = IPv6 header, FH = Fragment Header,                                */
791/* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
792/*                                                                          */
793/* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
794/* scenario in which they happen is in extreme circumstances that are most  */
795/* likely to be an indication of an attack rather than normal traffic.      */
796/* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
797/* are two rules that can be used to guard against type 3 packets: L4       */
798/* headers must always be in a packet that has the offset field set to 0    */
799/* and no packet is allowed to overlay that where offset = 0.               */
800/* ------------------------------------------------------------------------ */
801static INLINE int
802ipf_pr_fragment6(fin)
803	fr_info_t *fin;
804{
805	ipf_main_softc_t *softc = fin->fin_main_soft;
806	struct ip6_frag *frag;
807
808	fin->fin_flx |= FI_FRAG;
809
810	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
811	if (frag == NULL) {
812		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
813		return IPPROTO_NONE;
814	}
815
816	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
817		/*
818		 * Any fragment that isn't the last fragment must have its
819		 * length as a multiple of 8.
820		 */
821		if ((fin->fin_plen & 7) != 0) {
822			fin->fin_flx |= FI_BAD;
823			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
824		}
825	}
826
827	fin->fin_fraghdr = frag;
828	fin->fin_id = frag->ip6f_ident;
829	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830	if (fin->fin_off != 0)
831		fin->fin_flx |= FI_FRAGBODY;
832
833	/*
834	 * Jumbograms aren't handled, so the max. length is 64k
835	 */
836	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837		  fin->fin_flx |= FI_BAD;
838		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
839	}
840
841	/*
842	 * We don't know where the transport layer header (or whatever is next
843	 * is), as it could be behind destination options (amongst others) so
844	 * return the fragment header as the type of packet this is.  Note that
845	 * this effectively disables the fragment cache for > 1 protocol at a
846	 * time.
847	 */
848	return frag->ip6f_nxt;
849}
850
851
852/* ------------------------------------------------------------------------ */
853/* Function:    ipf_pr_dstopts6                                             */
854/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
855/* Parameters:  fin(I) - pointer to packet information                      */
856/*                                                                          */
857/* IPv6 Only                                                                */
858/* This is function checks pending destination options extension header     */
859/* ------------------------------------------------------------------------ */
860static INLINE int
861ipf_pr_dstopts6(fin)
862	fr_info_t *fin;
863{
864	ipf_main_softc_t *softc = fin->fin_main_soft;
865	struct ip6_ext *hdr;
866
867	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
868	if (hdr == NULL) {
869		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
870		return IPPROTO_NONE;
871	}
872	return hdr->ip6e_nxt;
873}
874
875
876/* ------------------------------------------------------------------------ */
877/* Function:    ipf_pr_icmp6                                                */
878/* Returns:     void                                                        */
879/* Parameters:  fin(I) - pointer to packet information                      */
880/*                                                                          */
881/* IPv6 Only                                                                */
882/* This routine is mainly concerned with determining the minimum valid size */
883/* for an ICMPv6 packet.                                                    */
884/* ------------------------------------------------------------------------ */
885static INLINE void
886ipf_pr_icmp6(fin)
887	fr_info_t *fin;
888{
889	int minicmpsz = sizeof(struct icmp6_hdr);
890	struct icmp6_hdr *icmp6;
891
892	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893		ipf_main_softc_t *softc = fin->fin_main_soft;
894
895		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
896		return;
897	}
898
899	if (fin->fin_dlen > 1) {
900		ip6_t *ip6;
901
902		icmp6 = fin->fin_dp;
903
904		fin->fin_data[0] = *(u_short *)icmp6;
905
906		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907			fin->fin_flx |= FI_ICMPQUERY;
908
909		switch (icmp6->icmp6_type)
910		{
911		case ICMP6_ECHO_REPLY :
912		case ICMP6_ECHO_REQUEST :
913			if (fin->fin_dlen >= 6)
914				fin->fin_data[1] = icmp6->icmp6_id;
915			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
916			break;
917
918		case ICMP6_DST_UNREACH :
919		case ICMP6_PACKET_TOO_BIG :
920		case ICMP6_TIME_EXCEEDED :
921		case ICMP6_PARAM_PROB :
922			fin->fin_flx |= FI_ICMPERR;
923			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
925				break;
926
927			if (M_LEN(fin->fin_m) < fin->fin_plen) {
928				if (ipf_coalesce(fin) != 1)
929					return;
930			}
931
932			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
933				return;
934
935			/*
936			 * If the destination of this packet doesn't match the
937			 * source of the original packet then this packet is
938			 * not correct.
939			 */
940			icmp6 = fin->fin_dp;
941			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942			if (IP6_NEQ(&fin->fin_fi.fi_dst,
943				    (i6addr_t *)&ip6->ip6_src)) {
944				fin->fin_flx |= FI_BAD;
945				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
946			}
947			break;
948		default :
949			break;
950		}
951	}
952
953	ipf_pr_short6(fin, minicmpsz);
954	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955		u_char p = fin->fin_p;
956
957		fin->fin_p = IPPROTO_ICMPV6;
958		ipf_checkv6sum(fin);
959		fin->fin_p = p;
960	}
961}
962
963
964/* ------------------------------------------------------------------------ */
965/* Function:    ipf_pr_udp6                                                 */
966/* Returns:     void                                                        */
967/* Parameters:  fin(I) - pointer to packet information                      */
968/*                                                                          */
969/* IPv6 Only                                                                */
970/* Analyse the packet for IPv6/UDP properties.                              */
971/* Is not expected to be called for fragmented packets.                     */
972/* ------------------------------------------------------------------------ */
973static INLINE void
974ipf_pr_udp6(fin)
975	fr_info_t *fin;
976{
977
978	if (ipf_pr_udpcommon(fin) == 0) {
979		u_char p = fin->fin_p;
980
981		fin->fin_p = IPPROTO_UDP;
982		ipf_checkv6sum(fin);
983		fin->fin_p = p;
984	}
985}
986
987
988/* ------------------------------------------------------------------------ */
989/* Function:    ipf_pr_tcp6                                                 */
990/* Returns:     void                                                        */
991/* Parameters:  fin(I) - pointer to packet information                      */
992/*                                                                          */
993/* IPv6 Only                                                                */
994/* Analyse the packet for IPv6/TCP properties.                              */
995/* Is not expected to be called for fragmented packets.                     */
996/* ------------------------------------------------------------------------ */
997static INLINE void
998ipf_pr_tcp6(fin)
999	fr_info_t *fin;
1000{
1001
1002	if (ipf_pr_tcpcommon(fin) == 0) {
1003		u_char p = fin->fin_p;
1004
1005		fin->fin_p = IPPROTO_TCP;
1006		ipf_checkv6sum(fin);
1007		fin->fin_p = p;
1008	}
1009}
1010
1011
1012/* ------------------------------------------------------------------------ */
1013/* Function:    ipf_pr_esp6                                                 */
1014/* Returns:     void                                                        */
1015/* Parameters:  fin(I) - pointer to packet information                      */
1016/*                                                                          */
1017/* IPv6 Only                                                                */
1018/* Analyse the packet for ESP properties.                                   */
1019/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1020/* even though the newer ESP packets must also have a sequence number that  */
1021/* is 32bits as well, it is not possible(?) to determine the version from a */
1022/* simple packet header.                                                    */
1023/* ------------------------------------------------------------------------ */
1024static INLINE void
1025ipf_pr_esp6(fin)
1026	fr_info_t *fin;
1027{
1028
1029	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030		ipf_main_softc_t *softc = fin->fin_main_soft;
1031
1032		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033		return;
1034	}
1035}
1036
1037
1038/* ------------------------------------------------------------------------ */
1039/* Function:    ipf_pr_ah6                                                  */
1040/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1041/* Parameters:  fin(I) - pointer to packet information                      */
1042/*                                                                          */
1043/* IPv6 Only                                                                */
1044/* Analyse the packet for AH properties.                                    */
1045/* The minimum length is taken to be the combination of all fields in the   */
1046/* header being present and no authentication data (null algorithm used.)   */
1047/* ------------------------------------------------------------------------ */
1048static INLINE int
1049ipf_pr_ah6(fin)
1050	fr_info_t *fin;
1051{
1052	authhdr_t *ah;
1053
1054	fin->fin_flx |= FI_AH;
1055
1056	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1057	if (ah == NULL) {
1058		ipf_main_softc_t *softc = fin->fin_main_soft;
1059
1060		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061		return IPPROTO_NONE;
1062	}
1063
1064	ipf_pr_short6(fin, sizeof(*ah));
1065
1066	/*
1067	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068	 * enough data to satisfy ah_next (the very first one.)
1069	 */
1070	return ah->ah_next;
1071}
1072
1073
1074/* ------------------------------------------------------------------------ */
1075/* Function:    ipf_pr_gre6                                                 */
1076/* Returns:     void                                                        */
1077/* Parameters:  fin(I) - pointer to packet information                      */
1078/*                                                                          */
1079/* Analyse the packet for GRE properties.                                   */
1080/* ------------------------------------------------------------------------ */
1081static INLINE void
1082ipf_pr_gre6(fin)
1083	fr_info_t *fin;
1084{
1085	grehdr_t *gre;
1086
1087	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088		ipf_main_softc_t *softc = fin->fin_main_soft;
1089
1090		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1091		return;
1092	}
1093
1094	gre = fin->fin_dp;
1095	if (GRE_REV(gre->gr_flags) == 1)
1096		fin->fin_data[0] = gre->gr_call;
1097}
1098#endif	/* USE_INET6 */
1099
1100
1101/* ------------------------------------------------------------------------ */
1102/* Function:    ipf_pr_pullup                                               */
1103/* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1104/* Parameters:  fin(I)  - pointer to packet information                     */
1105/*              plen(I) - length (excluding L3 header) to pullup            */
1106/*                                                                          */
1107/* Short inline function to cut down on code duplication to perform a call  */
1108/* to ipf_pullup to ensure there is the required amount of data,            */
1109/* consecutively in the packet buffer.                                      */
1110/*                                                                          */
1111/* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1112/* points to the first byte after the complete layer 3 header, which will   */
1113/* include all of the known extension headers for IPv6 or options for IPv4. */
1114/*                                                                          */
1115/* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1116/* is necessary to add those we can already assume to be pulled up (fin_dp  */
1117/* - fin_ip) to what is passed through.                                     */
1118/* ------------------------------------------------------------------------ */
1119int
1120ipf_pr_pullup(fin, plen)
1121	fr_info_t *fin;
1122	int plen;
1123{
1124	ipf_main_softc_t *softc = fin->fin_main_soft;
1125
1126	if (fin->fin_m != NULL) {
1127		if (fin->fin_dp != NULL)
1128			plen += (char *)fin->fin_dp -
1129				((char *)fin->fin_ip + fin->fin_hlen);
1130		plen += fin->fin_hlen;
1131		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132#if defined(_KERNEL)
1133			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134				DT(ipf_pullup_fail);
1135				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1136				return -1;
1137			}
1138			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1139#else
1140			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1141			/*
1142			 * Fake ipf_pullup failing
1143			 */
1144			fin->fin_reason = FRB_PULLUP;
1145			*fin->fin_mp = NULL;
1146			fin->fin_m = NULL;
1147			fin->fin_ip = NULL;
1148			return -1;
1149#endif
1150		}
1151	}
1152	return 0;
1153}
1154
1155
1156/* ------------------------------------------------------------------------ */
1157/* Function:    ipf_pr_short                                                */
1158/* Returns:     void                                                        */
1159/* Parameters:  fin(I)  - pointer to packet information                     */
1160/*              xmin(I) - minimum header size                               */
1161/*                                                                          */
1162/* Check if a packet is "short" as defined by xmin.  The rule we are        */
1163/* applying here is that the packet must not be fragmented within the layer */
1164/* 4 header.  That is, it must not be a fragment that has its offset set to */
1165/* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1166/* entire layer 4 header must be present (min).                             */
1167/* ------------------------------------------------------------------------ */
1168static INLINE void
1169ipf_pr_short(fin, xmin)
1170	fr_info_t *fin;
1171	int xmin;
1172{
1173
1174	if (fin->fin_off == 0) {
1175		if (fin->fin_dlen < xmin)
1176			fin->fin_flx |= FI_SHORT;
1177	} else if (fin->fin_off < xmin) {
1178		fin->fin_flx |= FI_SHORT;
1179	}
1180}
1181
1182
1183/* ------------------------------------------------------------------------ */
1184/* Function:    ipf_pr_icmp                                                 */
1185/* Returns:     void                                                        */
1186/* Parameters:  fin(I) - pointer to packet information                      */
1187/*                                                                          */
1188/* IPv4 Only                                                                */
1189/* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1190/* except extrememly bad packets, both type and code will be present.       */
1191/* The expected minimum size of an ICMP packet is very much dependent on    */
1192/* the type of it.                                                          */
1193/*                                                                          */
1194/* XXX - other ICMP sanity checks?                                          */
1195/* ------------------------------------------------------------------------ */
1196static INLINE void
1197ipf_pr_icmp(fin)
1198	fr_info_t *fin;
1199{
1200	ipf_main_softc_t *softc = fin->fin_main_soft;
1201	int minicmpsz = sizeof(struct icmp);
1202	icmphdr_t *icmp;
1203	ip_t *oip;
1204
1205	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1206
1207	if (fin->fin_off != 0) {
1208		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1209		return;
1210	}
1211
1212	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1214		return;
1215	}
1216
1217	icmp = fin->fin_dp;
1218
1219	fin->fin_data[0] = *(u_short *)icmp;
1220	fin->fin_data[1] = icmp->icmp_id;
1221
1222	switch (icmp->icmp_type)
1223	{
1224	case ICMP_ECHOREPLY :
1225	case ICMP_ECHO :
1226	/* Router discovery messaes - RFC 1256 */
1227	case ICMP_ROUTERADVERT :
1228	case ICMP_ROUTERSOLICIT :
1229		fin->fin_flx |= FI_ICMPQUERY;
1230		minicmpsz = ICMP_MINLEN;
1231		break;
1232	/*
1233	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234	 * 3 * timestamp(3 * 4)
1235	 */
1236	case ICMP_TSTAMP :
1237	case ICMP_TSTAMPREPLY :
1238		fin->fin_flx |= FI_ICMPQUERY;
1239		minicmpsz = 20;
1240		break;
1241	/*
1242	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1243	 * mask(4)
1244	 */
1245	case ICMP_IREQ :
1246	case ICMP_IREQREPLY :
1247	case ICMP_MASKREQ :
1248	case ICMP_MASKREPLY :
1249		fin->fin_flx |= FI_ICMPQUERY;
1250		minicmpsz = 12;
1251		break;
1252	/*
1253	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1254	 */
1255	case ICMP_UNREACH :
1256#ifdef icmp_nextmtu
1257		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259				fin->fin_flx |= FI_BAD;
1260				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1261			}
1262		}
1263#endif
1264		/* FALLTHROUGH */
1265	case ICMP_SOURCEQUENCH :
1266	case ICMP_REDIRECT :
1267	case ICMP_TIMXCEED :
1268	case ICMP_PARAMPROB :
1269		fin->fin_flx |= FI_ICMPERR;
1270		if (ipf_coalesce(fin) != 1) {
1271			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1272			return;
1273		}
1274
1275		/*
1276		 * ICMP error packets should not be generated for IP
1277		 * packets that are a fragment that isn't the first
1278		 * fragment.
1279		 */
1280		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282			fin->fin_flx |= FI_BAD;
1283			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1284		}
1285
1286		/*
1287		 * If the destination of this packet doesn't match the
1288		 * source of the original packet then this packet is
1289		 * not correct.
1290		 */
1291		if (oip->ip_src.s_addr != fin->fin_daddr) {
1292			fin->fin_flx |= FI_BAD;
1293			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1294		}
1295		break;
1296	default :
1297		break;
1298	}
1299
1300	ipf_pr_short(fin, minicmpsz);
1301
1302	ipf_checkv4sum(fin);
1303}
1304
1305
1306/* ------------------------------------------------------------------------ */
1307/* Function:    ipf_pr_tcpcommon                                            */
1308/* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1309/* Parameters:  fin(I) - pointer to packet information                      */
1310/*                                                                          */
1311/* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1312/* and make some checks with how they interact with other fields.           */
1313/* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1314/* valid and mark the packet as bad if not.                                 */
1315/* ------------------------------------------------------------------------ */
1316static INLINE int
1317ipf_pr_tcpcommon(fin)
1318	fr_info_t *fin;
1319{
1320	ipf_main_softc_t *softc = fin->fin_main_soft;
1321	int flags, tlen;
1322	tcphdr_t *tcp;
1323
1324	fin->fin_flx |= FI_TCPUDP;
1325	if (fin->fin_off != 0) {
1326		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1327		return 0;
1328	}
1329
1330	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1332		return -1;
1333	}
1334
1335	tcp = fin->fin_dp;
1336	if (fin->fin_dlen > 3) {
1337		fin->fin_sport = ntohs(tcp->th_sport);
1338		fin->fin_dport = ntohs(tcp->th_dport);
1339	}
1340
1341	if ((fin->fin_flx & FI_SHORT) != 0) {
1342		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1343		return 1;
1344	}
1345
1346	/*
1347	 * Use of the TCP data offset *must* result in a value that is at
1348	 * least the same size as the TCP header.
1349	 */
1350	tlen = TCP_OFF(tcp) << 2;
1351	if (tlen < sizeof(tcphdr_t)) {
1352		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353		fin->fin_flx |= FI_BAD;
1354		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1355		return 1;
1356	}
1357
1358	flags = tcp->th_flags;
1359	fin->fin_tcpf = tcp->th_flags;
1360
1361	/*
1362	 * If the urgent flag is set, then the urgent pointer must
1363	 * also be set and vice versa.  Good TCP packets do not have
1364	 * just one of these set.
1365	 */
1366	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367		fin->fin_flx |= FI_BAD;
1368		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1369#if 0
1370	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1371		/*
1372		 * Ignore this case (#if 0) as it shows up in "real"
1373		 * traffic with bogus values in the urgent pointer field.
1374		 */
1375		fin->fin_flx |= FI_BAD;
1376		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1377#endif
1378	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381		fin->fin_flx |= FI_BAD;
1382		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1383#if 1
1384	} else if (((flags & TH_SYN) != 0) &&
1385		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1386		/*
1387		 * SYN with URG and PUSH set is not for normal TCP but it is
1388		 * possible(?) with T/TCP...but who uses T/TCP?
1389		 */
1390		fin->fin_flx |= FI_BAD;
1391		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1392#endif
1393	} else if (!(flags & TH_ACK)) {
1394		/*
1395		 * If the ack bit isn't set, then either the SYN or
1396		 * RST bit must be set.  If the SYN bit is set, then
1397		 * we expect the ACK field to be 0.  If the ACK is
1398		 * not set and if URG, PSH or FIN are set, consdier
1399		 * that to indicate a bad TCP packet.
1400		 */
1401		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1402			/*
1403			 * Cisco PIX sets the ACK field to a random value.
1404			 * In light of this, do not set FI_BAD until a patch
1405			 * is available from Cisco to ensure that
1406			 * interoperability between existing systems is
1407			 * achieved.
1408			 */
1409			/*fin->fin_flx |= FI_BAD*/;
1410			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411		} else if (!(flags & (TH_RST|TH_SYN))) {
1412			fin->fin_flx |= FI_BAD;
1413			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415			fin->fin_flx |= FI_BAD;
1416			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1417		}
1418	}
1419	if (fin->fin_flx & FI_BAD) {
1420		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1421		return 1;
1422	}
1423
1424	/*
1425	 * At this point, it's not exactly clear what is to be gained by
1426	 * marking up which TCP options are and are not present.  The one we
1427	 * are most interested in is the TCP window scale.  This is only in
1428	 * a SYN packet [RFC1323] so we don't need this here...?
1429	 * Now if we were to analyse the header for passive fingerprinting,
1430	 * then that might add some weight to adding this...
1431	 */
1432	if (tlen == sizeof(tcphdr_t)) {
1433		return 0;
1434	}
1435
1436	if (ipf_pr_pullup(fin, tlen) == -1) {
1437		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1438		return -1;
1439	}
1440
1441#if 0
1442	tcp = fin->fin_dp;
1443	ip = fin->fin_ip;
1444	s = (u_char *)(tcp + 1);
1445	off = IP_HL(ip) << 2;
1446# ifdef _KERNEL
1447	if (fin->fin_mp != NULL) {
1448		mb_t *m = *fin->fin_mp;
1449
1450		if (off + tlen > M_LEN(m))
1451			return;
1452	}
1453# endif
1454	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1455		opt = *s;
1456		if (opt == '\0')
1457			break;
1458		else if (opt == TCPOPT_NOP)
1459			ol = 1;
1460		else {
1461			if (tlen < 2)
1462				break;
1463			ol = (int)*(s + 1);
1464			if (ol < 2 || ol > tlen)
1465				break;
1466		}
1467
1468		for (i = 9, mv = 4; mv >= 0; ) {
1469			op = ipopts + i;
1470			if (opt == (u_char)op->ol_val) {
1471				optmsk |= op->ol_bit;
1472				break;
1473			}
1474		}
1475		tlen -= ol;
1476		s += ol;
1477	}
1478#endif /* 0 */
1479
1480	return 0;
1481}
1482
1483
1484
1485/* ------------------------------------------------------------------------ */
1486/* Function:    ipf_pr_udpcommon                                            */
1487/* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1488/* Parameters:  fin(I) - pointer to packet information                      */
1489/*                                                                          */
1490/* Extract the UDP source and destination ports, if present.  If compiled   */
1491/* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1492/* ------------------------------------------------------------------------ */
1493static INLINE int
1494ipf_pr_udpcommon(fin)
1495	fr_info_t *fin;
1496{
1497	udphdr_t *udp;
1498
1499	fin->fin_flx |= FI_TCPUDP;
1500
1501	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503			ipf_main_softc_t *softc = fin->fin_main_soft;
1504
1505			fin->fin_flx |= FI_SHORT;
1506			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1507			return 1;
1508		}
1509
1510		udp = fin->fin_dp;
1511
1512		fin->fin_sport = ntohs(udp->uh_sport);
1513		fin->fin_dport = ntohs(udp->uh_dport);
1514	}
1515
1516	return 0;
1517}
1518
1519
1520/* ------------------------------------------------------------------------ */
1521/* Function:    ipf_pr_tcp                                                  */
1522/* Returns:     void                                                        */
1523/* Parameters:  fin(I) - pointer to packet information                      */
1524/*                                                                          */
1525/* IPv4 Only                                                                */
1526/* Analyse the packet for IPv4/TCP properties.                              */
1527/* ------------------------------------------------------------------------ */
1528static INLINE void
1529ipf_pr_tcp(fin)
1530	fr_info_t *fin;
1531{
1532
1533	ipf_pr_short(fin, sizeof(tcphdr_t));
1534
1535	if (ipf_pr_tcpcommon(fin) == 0)
1536		ipf_checkv4sum(fin);
1537}
1538
1539
1540/* ------------------------------------------------------------------------ */
1541/* Function:    ipf_pr_udp                                                  */
1542/* Returns:     void                                                        */
1543/* Parameters:  fin(I) - pointer to packet information                      */
1544/*                                                                          */
1545/* IPv4 Only                                                                */
1546/* Analyse the packet for IPv4/UDP properties.                              */
1547/* ------------------------------------------------------------------------ */
1548static INLINE void
1549ipf_pr_udp(fin)
1550	fr_info_t *fin;
1551{
1552
1553	ipf_pr_short(fin, sizeof(udphdr_t));
1554
1555	if (ipf_pr_udpcommon(fin) == 0)
1556		ipf_checkv4sum(fin);
1557}
1558
1559
1560/* ------------------------------------------------------------------------ */
1561/* Function:    ipf_pr_esp                                                  */
1562/* Returns:     void                                                        */
1563/* Parameters:  fin(I) - pointer to packet information                      */
1564/*                                                                          */
1565/* Analyse the packet for ESP properties.                                   */
1566/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1567/* even though the newer ESP packets must also have a sequence number that  */
1568/* is 32bits as well, it is not possible(?) to determine the version from a */
1569/* simple packet header.                                                    */
1570/* ------------------------------------------------------------------------ */
1571static INLINE void
1572ipf_pr_esp(fin)
1573	fr_info_t *fin;
1574{
1575
1576	if (fin->fin_off == 0) {
1577		ipf_pr_short(fin, 8);
1578		if (ipf_pr_pullup(fin, 8) == -1) {
1579			ipf_main_softc_t *softc = fin->fin_main_soft;
1580
1581			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1582		}
1583	}
1584}
1585
1586
1587/* ------------------------------------------------------------------------ */
1588/* Function:    ipf_pr_ah                                                   */
1589/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1590/* Parameters:  fin(I) - pointer to packet information                      */
1591/*                                                                          */
1592/* Analyse the packet for AH properties.                                    */
1593/* The minimum length is taken to be the combination of all fields in the   */
1594/* header being present and no authentication data (null algorithm used.)   */
1595/* ------------------------------------------------------------------------ */
1596static INLINE int
1597ipf_pr_ah(fin)
1598	fr_info_t *fin;
1599{
1600	ipf_main_softc_t *softc = fin->fin_main_soft;
1601	authhdr_t *ah;
1602	int len;
1603
1604	fin->fin_flx |= FI_AH;
1605	ipf_pr_short(fin, sizeof(*ah));
1606
1607	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609		return IPPROTO_NONE;
1610	}
1611
1612	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613		DT(fr_v4_ah_pullup_1);
1614		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615		return IPPROTO_NONE;
1616	}
1617
1618	ah = (authhdr_t *)fin->fin_dp;
1619
1620	len = (ah->ah_plen + 2) << 2;
1621	ipf_pr_short(fin, len);
1622	if (ipf_pr_pullup(fin, len) == -1) {
1623		DT(fr_v4_ah_pullup_2);
1624		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625		return IPPROTO_NONE;
1626	}
1627
1628	/*
1629	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1630	 * header.
1631	 */
1632	fin->fin_dp = (char *)fin->fin_dp + len;
1633	fin->fin_dlen -= len;
1634	return ah->ah_next;
1635}
1636
1637
1638/* ------------------------------------------------------------------------ */
1639/* Function:    ipf_pr_gre                                                  */
1640/* Returns:     void                                                        */
1641/* Parameters:  fin(I) - pointer to packet information                      */
1642/*                                                                          */
1643/* Analyse the packet for GRE properties.                                   */
1644/* ------------------------------------------------------------------------ */
1645static INLINE void
1646ipf_pr_gre(fin)
1647	fr_info_t *fin;
1648{
1649	ipf_main_softc_t *softc = fin->fin_main_soft;
1650	grehdr_t *gre;
1651
1652	ipf_pr_short(fin, sizeof(grehdr_t));
1653
1654	if (fin->fin_off != 0) {
1655		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1656		return;
1657	}
1658
1659	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1661		return;
1662	}
1663
1664	gre = fin->fin_dp;
1665	if (GRE_REV(gre->gr_flags) == 1)
1666		fin->fin_data[0] = gre->gr_call;
1667}
1668
1669
1670/* ------------------------------------------------------------------------ */
1671/* Function:    ipf_pr_ipv4hdr                                              */
1672/* Returns:     void                                                        */
1673/* Parameters:  fin(I) - pointer to packet information                      */
1674/*                                                                          */
1675/* IPv4 Only                                                                */
1676/* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1677/* Check all options present and flag their presence if any exist.          */
1678/* ------------------------------------------------------------------------ */
1679static INLINE void
1680ipf_pr_ipv4hdr(fin)
1681	fr_info_t *fin;
1682{
1683	u_short optmsk = 0, secmsk = 0, auth = 0;
1684	int hlen, ol, mv, p, i;
1685	const struct optlist *op;
1686	u_char *s, opt;
1687	u_short off;
1688	fr_ip_t *fi;
1689	ip_t *ip;
1690
1691	fi = &fin->fin_fi;
1692	hlen = fin->fin_hlen;
1693
1694	ip = fin->fin_ip;
1695	p = ip->ip_p;
1696	fi->fi_p = p;
1697	fin->fin_crc = p;
1698	fi->fi_tos = ip->ip_tos;
1699	fin->fin_id = ip->ip_id;
1700	off = ntohs(ip->ip_off);
1701
1702	/* Get both TTL and protocol */
1703	fi->fi_p = ip->ip_p;
1704	fi->fi_ttl = ip->ip_ttl;
1705
1706	/* Zero out bits not used in IPv6 address */
1707	fi->fi_src.i6[1] = 0;
1708	fi->fi_src.i6[2] = 0;
1709	fi->fi_src.i6[3] = 0;
1710	fi->fi_dst.i6[1] = 0;
1711	fi->fi_dst.i6[2] = 0;
1712	fi->fi_dst.i6[3] = 0;
1713
1714	fi->fi_saddr = ip->ip_src.s_addr;
1715	fin->fin_crc += fi->fi_saddr;
1716	fi->fi_daddr = ip->ip_dst.s_addr;
1717	fin->fin_crc += fi->fi_daddr;
1718	if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1720
1721	/*
1722	 * set packet attribute flags based on the offset and
1723	 * calculate the byte offset that it represents.
1724	 */
1725	off &= IP_MF|IP_OFFMASK;
1726	if (off != 0) {
1727		int morefrag = off & IP_MF;
1728
1729		fi->fi_flx |= FI_FRAG;
1730		off &= IP_OFFMASK;
1731		if (off != 0) {
1732			fin->fin_flx |= FI_FRAGBODY;
1733			off <<= 3;
1734			if ((off + fin->fin_dlen > 65535) ||
1735			    (fin->fin_dlen == 0) ||
1736			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1737				/*
1738				 * The length of the packet, starting at its
1739				 * offset cannot exceed 65535 (0xffff) as the
1740				 * length of an IP packet is only 16 bits.
1741				 *
1742				 * Any fragment that isn't the last fragment
1743				 * must have a length greater than 0 and it
1744				 * must be an even multiple of 8.
1745				 */
1746				fi->fi_flx |= FI_BAD;
1747				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1748			}
1749		}
1750	}
1751	fin->fin_off = off;
1752
1753	/*
1754	 * Call per-protocol setup and checking
1755	 */
1756	if (p == IPPROTO_AH) {
1757		/*
1758		 * Treat AH differently because we expect there to be another
1759		 * layer 4 header after it.
1760		 */
1761		p = ipf_pr_ah(fin);
1762	}
1763
1764	switch (p)
1765	{
1766	case IPPROTO_UDP :
1767		ipf_pr_udp(fin);
1768		break;
1769	case IPPROTO_TCP :
1770		ipf_pr_tcp(fin);
1771		break;
1772	case IPPROTO_ICMP :
1773		ipf_pr_icmp(fin);
1774		break;
1775	case IPPROTO_ESP :
1776		ipf_pr_esp(fin);
1777		break;
1778	case IPPROTO_GRE :
1779		ipf_pr_gre(fin);
1780		break;
1781	}
1782
1783	ip = fin->fin_ip;
1784	if (ip == NULL)
1785		return;
1786
1787	/*
1788	 * If it is a standard IP header (no options), set the flag fields
1789	 * which relate to options to 0.
1790	 */
1791	if (hlen == sizeof(*ip)) {
1792		fi->fi_optmsk = 0;
1793		fi->fi_secmsk = 0;
1794		fi->fi_auth = 0;
1795		return;
1796	}
1797
1798	/*
1799	 * So the IP header has some IP options attached.  Walk the entire
1800	 * list of options present with this packet and set flags to indicate
1801	 * which ones are here and which ones are not.  For the somewhat out
1802	 * of date and obscure security classification options, set a flag to
1803	 * represent which classification is present.
1804	 */
1805	fi->fi_flx |= FI_OPTIONS;
1806
1807	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1808		opt = *s;
1809		if (opt == '\0')
1810			break;
1811		else if (opt == IPOPT_NOP)
1812			ol = 1;
1813		else {
1814			if (hlen < 2)
1815				break;
1816			ol = (int)*(s + 1);
1817			if (ol < 2 || ol > hlen)
1818				break;
1819		}
1820		for (i = 9, mv = 4; mv >= 0; ) {
1821			op = ipopts + i;
1822
1823			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1824				u_32_t doi;
1825
1826				switch (opt)
1827				{
1828				case IPOPT_SECURITY :
1829					if (optmsk & op->ol_bit) {
1830						fin->fin_flx |= FI_BAD;
1831						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1832					} else {
1833						doi = ipf_checkripso(s);
1834						secmsk = doi >> 16;
1835						auth = doi & 0xffff;
1836					}
1837					break;
1838
1839				case IPOPT_CIPSO :
1840
1841					if (optmsk & op->ol_bit) {
1842						fin->fin_flx |= FI_BAD;
1843						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1844					} else {
1845						doi = ipf_checkcipso(fin,
1846								     s, ol);
1847						secmsk = doi >> 16;
1848						auth = doi & 0xffff;
1849					}
1850					break;
1851				}
1852				optmsk |= op->ol_bit;
1853			}
1854
1855			if (opt < op->ol_val)
1856				i -= mv;
1857			else
1858				i += mv;
1859			mv--;
1860		}
1861		hlen -= ol;
1862		s += ol;
1863	}
1864
1865	/*
1866	 *
1867	 */
1868	if (auth && !(auth & 0x0100))
1869		auth &= 0xff00;
1870	fi->fi_optmsk = optmsk;
1871	fi->fi_secmsk = secmsk;
1872	fi->fi_auth = auth;
1873}
1874
1875
1876/* ------------------------------------------------------------------------ */
1877/* Function:    ipf_checkripso                                              */
1878/* Returns:     void                                                        */
1879/* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1880/*                                                                          */
1881/* ------------------------------------------------------------------------ */
1882static u_32_t
1883ipf_checkripso(s)
1884	u_char *s;
1885{
1886	const struct optlist *sp;
1887	u_short secmsk = 0, auth = 0;
1888	u_char sec;
1889	int j, m;
1890
1891	sec = *(s + 2);	/* classification */
1892	for (j = 3, m = 2; m >= 0; ) {
1893		sp = secopt + j;
1894		if (sec == sp->ol_val) {
1895			secmsk |= sp->ol_bit;
1896			auth = *(s + 3);
1897			auth *= 256;
1898			auth += *(s + 4);
1899			break;
1900		}
1901		if (sec < sp->ol_val)
1902			j -= m;
1903		else
1904			j += m;
1905		m--;
1906	}
1907
1908	return (secmsk << 16) | auth;
1909}
1910
1911
1912/* ------------------------------------------------------------------------ */
1913/* Function:    ipf_checkcipso                                              */
1914/* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1915/* Parameters:  fin(IO) - pointer to packet information                     */
1916/*              s(I)    - pointer to start of CIPSO option                  */
1917/*              ol(I)   - length of CIPSO option field                      */
1918/*                                                                          */
1919/* This function returns the domain of integrity (DOI) field from the CIPSO */
1920/* header and returns that whilst also storing the highest sensitivity      */
1921/* value found in the fr_info_t structure.                                  */
1922/*                                                                          */
1923/* No attempt is made to extract the category bitmaps as these are defined  */
1924/* by the user (rather than the protocol) and can be rather numerous on the */
1925/* end nodes.                                                               */
1926/* ------------------------------------------------------------------------ */
1927static u_32_t
1928ipf_checkcipso(fin, s, ol)
1929	fr_info_t *fin;
1930	u_char *s;
1931	int ol;
1932{
1933	ipf_main_softc_t *softc = fin->fin_main_soft;
1934	fr_ip_t *fi;
1935	u_32_t doi;
1936	u_char *t, tag, tlen, sensitivity;
1937	int len;
1938
1939	if (ol < 6 || ol > 40) {
1940		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1941		fin->fin_flx |= FI_BAD;
1942		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1943		return 0;
1944	}
1945
1946	fi = &fin->fin_fi;
1947	fi->fi_sensitivity = 0;
1948	/*
1949	 * The DOI field MUST be there.
1950	 */
1951	bcopy(s + 2, &doi, sizeof(doi));
1952
1953	t = (u_char *)s + 6;
1954	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1955		tag = *t;
1956		tlen = *(t + 1);
1957		if (tlen > len || tlen < 4 || tlen > 34) {
1958			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1959			fin->fin_flx |= FI_BAD;
1960			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1961			return 0;
1962		}
1963
1964		sensitivity = 0;
1965		/*
1966		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1967		 * draft (16 July 1992) that has expired.
1968		 */
1969		if (tag == 0) {
1970			fin->fin_flx |= FI_BAD;
1971			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1972			continue;
1973		} else if (tag == 1) {
1974			if (*(t + 2) != 0) {
1975				fin->fin_flx |= FI_BAD;
1976				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1977				continue;
1978			}
1979			sensitivity = *(t + 3);
1980			/* Category bitmap for categories 0-239 */
1981
1982		} else if (tag == 4) {
1983			if (*(t + 2) != 0) {
1984				fin->fin_flx |= FI_BAD;
1985				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1986				continue;
1987			}
1988			sensitivity = *(t + 3);
1989			/* Enumerated categories, 16bits each, upto 15 */
1990
1991		} else if (tag == 5) {
1992			if (*(t + 2) != 0) {
1993				fin->fin_flx |= FI_BAD;
1994				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1995				continue;
1996			}
1997			sensitivity = *(t + 3);
1998			/* Range of categories (2*16bits), up to 7 pairs */
1999
2000		} else if (tag > 127) {
2001			/* Custom defined DOI */
2002			;
2003		} else {
2004			fin->fin_flx |= FI_BAD;
2005			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2006			continue;
2007		}
2008
2009		if (sensitivity > fi->fi_sensitivity)
2010			fi->fi_sensitivity = sensitivity;
2011	}
2012
2013	return doi;
2014}
2015
2016
2017/* ------------------------------------------------------------------------ */
2018/* Function:    ipf_makefrip                                                */
2019/* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2020/* Parameters:  hlen(I) - length of IP packet header                        */
2021/*              ip(I)   - pointer to the IP header                          */
2022/*              fin(IO) - pointer to packet information                     */
2023/*                                                                          */
2024/* Compact the IP header into a structure which contains just the info.     */
2025/* which is useful for comparing IP headers with and store this information */
2026/* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2027/* this function will be called with either an IPv4 or IPv6 packet.         */
2028/* ------------------------------------------------------------------------ */
2029int
2030ipf_makefrip(hlen, ip, fin)
2031	int hlen;
2032	ip_t *ip;
2033	fr_info_t *fin;
2034{
2035	ipf_main_softc_t *softc = fin->fin_main_soft;
2036	int v;
2037
2038	fin->fin_depth = 0;
2039	fin->fin_hlen = (u_short)hlen;
2040	fin->fin_ip = ip;
2041	fin->fin_rule = 0xffffffff;
2042	fin->fin_group[0] = -1;
2043	fin->fin_group[1] = '\0';
2044	fin->fin_dp = (char *)ip + hlen;
2045
2046	v = fin->fin_v;
2047	if (v == 4) {
2048		fin->fin_plen = ntohs(ip->ip_len);
2049		fin->fin_dlen = fin->fin_plen - hlen;
2050		ipf_pr_ipv4hdr(fin);
2051#ifdef	USE_INET6
2052	} else if (v == 6) {
2053		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2054		fin->fin_dlen = fin->fin_plen;
2055		fin->fin_plen += hlen;
2056
2057		ipf_pr_ipv6hdr(fin);
2058#endif
2059	}
2060	if (fin->fin_ip == NULL) {
2061		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2062		return -1;
2063	}
2064	return 0;
2065}
2066
2067
2068/* ------------------------------------------------------------------------ */
2069/* Function:    ipf_portcheck                                               */
2070/* Returns:     int - 1 == port matched, 0 == port match failed             */
2071/* Parameters:  frp(I) - pointer to port check `expression'                 */
2072/*              pop(I) - port number to evaluate                            */
2073/*                                                                          */
2074/* Perform a comparison of a port number against some other(s), using a     */
2075/* structure with compare information stored in it.                         */
2076/* ------------------------------------------------------------------------ */
2077static INLINE int
2078ipf_portcheck(frp, pop)
2079	frpcmp_t *frp;
2080	u_32_t pop;
2081{
2082	int err = 1;
2083	u_32_t po;
2084
2085	po = frp->frp_port;
2086
2087	/*
2088	 * Do opposite test to that required and continue if that succeeds.
2089	 */
2090	switch (frp->frp_cmp)
2091	{
2092	case FR_EQUAL :
2093		if (pop != po) /* EQUAL */
2094			err = 0;
2095		break;
2096	case FR_NEQUAL :
2097		if (pop == po) /* NOTEQUAL */
2098			err = 0;
2099		break;
2100	case FR_LESST :
2101		if (pop >= po) /* LESSTHAN */
2102			err = 0;
2103		break;
2104	case FR_GREATERT :
2105		if (pop <= po) /* GREATERTHAN */
2106			err = 0;
2107		break;
2108	case FR_LESSTE :
2109		if (pop > po) /* LT or EQ */
2110			err = 0;
2111		break;
2112	case FR_GREATERTE :
2113		if (pop < po) /* GT or EQ */
2114			err = 0;
2115		break;
2116	case FR_OUTRANGE :
2117		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2118			err = 0;
2119		break;
2120	case FR_INRANGE :
2121		if (pop <= po || pop >= frp->frp_top) /* In range */
2122			err = 0;
2123		break;
2124	case FR_INCRANGE :
2125		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2126			err = 0;
2127		break;
2128	default :
2129		break;
2130	}
2131	return err;
2132}
2133
2134
2135/* ------------------------------------------------------------------------ */
2136/* Function:    ipf_tcpudpchk                                               */
2137/* Returns:     int - 1 == protocol matched, 0 == check failed              */
2138/* Parameters:  fda(I) - pointer to packet information                      */
2139/*              ft(I)  - pointer to structure with comparison data          */
2140/*                                                                          */
2141/* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2142/* structure containing information that we want to match against.          */
2143/* ------------------------------------------------------------------------ */
2144int
2145ipf_tcpudpchk(fi, ft)
2146	fr_ip_t *fi;
2147	frtuc_t *ft;
2148{
2149	int err = 1;
2150
2151	/*
2152	 * Both ports should *always* be in the first fragment.
2153	 * So far, I cannot find any cases where they can not be.
2154	 *
2155	 * compare destination ports
2156	 */
2157	if (ft->ftu_dcmp)
2158		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2159
2160	/*
2161	 * compare source ports
2162	 */
2163	if (err && ft->ftu_scmp)
2164		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2165
2166	/*
2167	 * If we don't have all the TCP/UDP header, then how can we
2168	 * expect to do any sort of match on it ?  If we were looking for
2169	 * TCP flags, then NO match.  If not, then match (which should
2170	 * satisfy the "short" class too).
2171	 */
2172	if (err && (fi->fi_p == IPPROTO_TCP)) {
2173		if (fi->fi_flx & FI_SHORT)
2174			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2175		/*
2176		 * Match the flags ?  If not, abort this match.
2177		 */
2178		if (ft->ftu_tcpfm &&
2179		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2180			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2181				 ft->ftu_tcpfm, ft->ftu_tcpf));
2182			err = 0;
2183		}
2184	}
2185	return err;
2186}
2187
2188
2189/* ------------------------------------------------------------------------ */
2190/* Function:    ipf_check_ipf                                               */
2191/* Returns:     int - 0 == match, else no match                             */
2192/* Parameters:  fin(I)     - pointer to packet information                  */
2193/*              fr(I)      - pointer to filter rule                         */
2194/*              portcmp(I) - flag indicating whether to attempt matching on */
2195/*                           TCP/UDP port data.                             */
2196/*                                                                          */
2197/* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2198/* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2199/* this function.                                                           */
2200/* ------------------------------------------------------------------------ */
2201static INLINE int
2202ipf_check_ipf(fin, fr, portcmp)
2203	fr_info_t *fin;
2204	frentry_t *fr;
2205	int portcmp;
2206{
2207	u_32_t	*ld, *lm, *lip;
2208	fripf_t *fri;
2209	fr_ip_t *fi;
2210	int i;
2211
2212	fi = &fin->fin_fi;
2213	fri = fr->fr_ipf;
2214	lip = (u_32_t *)fi;
2215	lm = (u_32_t *)&fri->fri_mip;
2216	ld = (u_32_t *)&fri->fri_ip;
2217
2218	/*
2219	 * first 32 bits to check coversion:
2220	 * IP version, TOS, TTL, protocol
2221	 */
2222	i = ((*lip & *lm) != *ld);
2223	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2224		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2225	if (i)
2226		return 1;
2227
2228	/*
2229	 * Next 32 bits is a constructed bitmask indicating which IP options
2230	 * are present (if any) in this packet.
2231	 */
2232	lip++, lm++, ld++;
2233	i = ((*lip & *lm) != *ld);
2234	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2235		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2236	if (i != 0)
2237		return 1;
2238
2239	lip++, lm++, ld++;
2240	/*
2241	 * Unrolled loops (4 each, for 32 bits) for address checks.
2242	 */
2243	/*
2244	 * Check the source address.
2245	 */
2246	if (fr->fr_satype == FRI_LOOKUP) {
2247		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2248				      fi->fi_v, lip, fin->fin_plen);
2249		if (i == -1)
2250			return 1;
2251		lip += 3;
2252		lm += 3;
2253		ld += 3;
2254	} else {
2255		i = ((*lip & *lm) != *ld);
2256		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2257			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2258		if (fi->fi_v == 6) {
2259			lip++, lm++, ld++;
2260			i |= ((*lip & *lm) != *ld);
2261			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2262				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2263			lip++, lm++, ld++;
2264			i |= ((*lip & *lm) != *ld);
2265			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2266				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2267			lip++, lm++, ld++;
2268			i |= ((*lip & *lm) != *ld);
2269			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2270				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271		} else {
2272			lip += 3;
2273			lm += 3;
2274			ld += 3;
2275		}
2276	}
2277	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2278	if (i != 0)
2279		return 1;
2280
2281	/*
2282	 * Check the destination address.
2283	 */
2284	lip++, lm++, ld++;
2285	if (fr->fr_datype == FRI_LOOKUP) {
2286		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2287				      fi->fi_v, lip, fin->fin_plen);
2288		if (i == -1)
2289			return 1;
2290		lip += 3;
2291		lm += 3;
2292		ld += 3;
2293	} else {
2294		i = ((*lip & *lm) != *ld);
2295		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2296			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2297		if (fi->fi_v == 6) {
2298			lip++, lm++, ld++;
2299			i |= ((*lip & *lm) != *ld);
2300			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2301				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2302			lip++, lm++, ld++;
2303			i |= ((*lip & *lm) != *ld);
2304			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2305				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2306			lip++, lm++, ld++;
2307			i |= ((*lip & *lm) != *ld);
2308			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2309				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310		} else {
2311			lip += 3;
2312			lm += 3;
2313			ld += 3;
2314		}
2315	}
2316	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2317	if (i != 0)
2318		return 1;
2319	/*
2320	 * IP addresses matched.  The next 32bits contains:
2321	 * mast of old IP header security & authentication bits.
2322	 */
2323	lip++, lm++, ld++;
2324	i = (*ld - (*lip & *lm));
2325	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2326
2327	/*
2328	 * Next we have 32 bits of packet flags.
2329	 */
2330	lip++, lm++, ld++;
2331	i |= (*ld - (*lip & *lm));
2332	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2333
2334	if (i == 0) {
2335		/*
2336		 * If a fragment, then only the first has what we're
2337		 * looking for here...
2338		 */
2339		if (portcmp) {
2340			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2341				i = 1;
2342		} else {
2343			if (fr->fr_dcmp || fr->fr_scmp ||
2344			    fr->fr_tcpf || fr->fr_tcpfm)
2345				i = 1;
2346			if (fr->fr_icmpm || fr->fr_icmp) {
2347				if (((fi->fi_p != IPPROTO_ICMP) &&
2348				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2349				    fin->fin_off || (fin->fin_dlen < 2))
2350					i = 1;
2351				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2352					 fr->fr_icmp) {
2353					FR_DEBUG(("i. %#x & %#x != %#x\n",
2354						 fin->fin_data[0],
2355						 fr->fr_icmpm, fr->fr_icmp));
2356					i = 1;
2357				}
2358			}
2359		}
2360	}
2361	return i;
2362}
2363
2364
2365/* ------------------------------------------------------------------------ */
2366/* Function:    ipf_scanlist                                                */
2367/* Returns:     int - result flags of scanning filter list                  */
2368/* Parameters:  fin(I) - pointer to packet information                      */
2369/*              pass(I) - default result to return for filtering            */
2370/*                                                                          */
2371/* Check the input/output list of rules for a match to the current packet.  */
2372/* If a match is found, the value of fr_flags from the rule becomes the     */
2373/* return value and fin->fin_fr points to the matched rule.                 */
2374/*                                                                          */
2375/* This function may be called recusively upto 16 times (limit inbuilt.)    */
2376/* When unwinding, it should finish up with fin_depth as 0.                 */
2377/*                                                                          */
2378/* Could be per interface, but this gets real nasty when you don't have,    */
2379/* or can't easily change, the kernel source code to .                      */
2380/* ------------------------------------------------------------------------ */
2381int
2382ipf_scanlist(fin, pass)
2383	fr_info_t *fin;
2384	u_32_t pass;
2385{
2386	ipf_main_softc_t *softc = fin->fin_main_soft;
2387	int rulen, portcmp, off, skip;
2388	struct frentry *fr, *fnext;
2389	u_32_t passt, passo;
2390
2391	/*
2392	 * Do not allow nesting deeper than 16 levels.
2393	 */
2394	if (fin->fin_depth >= 16)
2395		return pass;
2396
2397	fr = fin->fin_fr;
2398
2399	/*
2400	 * If there are no rules in this list, return now.
2401	 */
2402	if (fr == NULL)
2403		return pass;
2404
2405	skip = 0;
2406	portcmp = 0;
2407	fin->fin_depth++;
2408	fin->fin_fr = NULL;
2409	off = fin->fin_off;
2410
2411	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2412		portcmp = 1;
2413
2414	for (rulen = 0; fr; fr = fnext, rulen++) {
2415		fnext = fr->fr_next;
2416		if (skip != 0) {
2417			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2418			skip--;
2419			continue;
2420		}
2421
2422		/*
2423		 * In all checks below, a null (zero) value in the
2424		 * filter struture is taken to mean a wildcard.
2425		 *
2426		 * check that we are working for the right interface
2427		 */
2428#ifdef	_KERNEL
2429		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2430			continue;
2431#else
2432		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2433			printf("\n");
2434		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2435				  FR_ISPASS(pass) ? 'p' :
2436				  FR_ISACCOUNT(pass) ? 'A' :
2437				  FR_ISAUTH(pass) ? 'a' :
2438				  (pass & FR_NOMATCH) ? 'n' :'b'));
2439		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2440			continue;
2441		FR_VERBOSE((":i"));
2442#endif
2443
2444		switch (fr->fr_type)
2445		{
2446		case FR_T_IPF :
2447		case FR_T_IPF_BUILTIN :
2448			if (ipf_check_ipf(fin, fr, portcmp))
2449				continue;
2450			break;
2451#if defined(IPFILTER_BPF)
2452		case FR_T_BPFOPC :
2453		case FR_T_BPFOPC_BUILTIN :
2454		    {
2455			u_char *mc;
2456			int wlen;
2457
2458			if (*fin->fin_mp == NULL)
2459				continue;
2460			if (fin->fin_family != fr->fr_family)
2461				continue;
2462			mc = (u_char *)fin->fin_m;
2463			wlen = fin->fin_dlen + fin->fin_hlen;
2464			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2465				continue;
2466			break;
2467		    }
2468#endif
2469		case FR_T_CALLFUNC_BUILTIN :
2470		    {
2471			frentry_t *f;
2472
2473			f = (*fr->fr_func)(fin, &pass);
2474			if (f != NULL)
2475				fr = f;
2476			else
2477				continue;
2478			break;
2479		    }
2480
2481		case FR_T_IPFEXPR :
2482		case FR_T_IPFEXPR_BUILTIN :
2483			if (fin->fin_family != fr->fr_family)
2484				continue;
2485			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2486				continue;
2487			break;
2488
2489		default :
2490			break;
2491		}
2492
2493		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2494			if (fin->fin_nattag == NULL)
2495				continue;
2496			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2497				continue;
2498		}
2499		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2500
2501		passt = fr->fr_flags;
2502
2503		/*
2504		 * If the rule is a "call now" rule, then call the function
2505		 * in the rule, if it exists and use the results from that.
2506		 * If the function pointer is bad, just make like we ignore
2507		 * it, except for increasing the hit counter.
2508		 */
2509		if ((passt & FR_CALLNOW) != 0) {
2510			frentry_t *frs;
2511
2512			ATOMIC_INC64(fr->fr_hits);
2513			if ((fr->fr_func == NULL) ||
2514			    (fr->fr_func == (ipfunc_t)-1))
2515				continue;
2516
2517			frs = fin->fin_fr;
2518			fin->fin_fr = fr;
2519			fr = (*fr->fr_func)(fin, &passt);
2520			if (fr == NULL) {
2521				fin->fin_fr = frs;
2522				continue;
2523			}
2524			passt = fr->fr_flags;
2525		}
2526		fin->fin_fr = fr;
2527
2528#ifdef  IPFILTER_LOG
2529		/*
2530		 * Just log this packet...
2531		 */
2532		if ((passt & FR_LOGMASK) == FR_LOG) {
2533			if (ipf_log_pkt(fin, passt) == -1) {
2534				if (passt & FR_LOGORBLOCK) {
2535					DT(frb_logfail);
2536					passt &= ~FR_CMDMASK;
2537					passt |= FR_BLOCK|FR_QUICK;
2538					fin->fin_reason = FRB_LOGFAIL;
2539				}
2540			}
2541		}
2542#endif /* IPFILTER_LOG */
2543
2544		MUTEX_ENTER(&fr->fr_lock);
2545		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2546		fr->fr_hits++;
2547		MUTEX_EXIT(&fr->fr_lock);
2548		fin->fin_rule = rulen;
2549
2550		passo = pass;
2551		if (FR_ISSKIP(passt)) {
2552			skip = fr->fr_arg;
2553			continue;
2554		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2555			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2556			pass = passt;
2557		}
2558
2559		if (passt & (FR_RETICMP|FR_FAKEICMP))
2560			fin->fin_icode = fr->fr_icode;
2561
2562		if (fr->fr_group != -1) {
2563			(void) strncpy(fin->fin_group,
2564				       FR_NAME(fr, fr_group),
2565				       strlen(FR_NAME(fr, fr_group)));
2566		} else {
2567			fin->fin_group[0] = '\0';
2568		}
2569
2570		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2571
2572		if (fr->fr_grphead != NULL) {
2573			fin->fin_fr = fr->fr_grphead->fg_start;
2574			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2575
2576			if (FR_ISDECAPS(passt))
2577				passt = ipf_decaps(fin, pass, fr->fr_icode);
2578			else
2579				passt = ipf_scanlist(fin, pass);
2580
2581			if (fin->fin_fr == NULL) {
2582				fin->fin_rule = rulen;
2583				if (fr->fr_group != -1)
2584					(void) strncpy(fin->fin_group,
2585						       fr->fr_names +
2586						       fr->fr_group,
2587						       strlen(fr->fr_names +
2588							      fr->fr_group));
2589				fin->fin_fr = fr;
2590				passt = pass;
2591			}
2592			pass = passt;
2593		}
2594
2595		if (pass & FR_QUICK) {
2596			/*
2597			 * Finally, if we've asked to track state for this
2598			 * packet, set it up.  Add state for "quick" rules
2599			 * here so that if the action fails we can consider
2600			 * the rule to "not match" and keep on processing
2601			 * filter rules.
2602			 */
2603			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2604			    !(fin->fin_flx & FI_STATE)) {
2605				int out = fin->fin_out;
2606
2607				fin->fin_fr = fr;
2608				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2609					LBUMPD(ipf_stats[out], fr_ads);
2610				} else {
2611					LBUMPD(ipf_stats[out], fr_bads);
2612					pass = passo;
2613					continue;
2614				}
2615			}
2616			break;
2617		}
2618	}
2619	fin->fin_depth--;
2620	return pass;
2621}
2622
2623
2624/* ------------------------------------------------------------------------ */
2625/* Function:    ipf_acctpkt                                                 */
2626/* Returns:     frentry_t* - always returns NULL                            */
2627/* Parameters:  fin(I) - pointer to packet information                      */
2628/*              passp(IO) - pointer to current/new filter decision (unused) */
2629/*                                                                          */
2630/* Checks a packet against accounting rules, if there are any for the given */
2631/* IP protocol version.                                                     */
2632/*                                                                          */
2633/* N.B.: this function returns NULL to match the prototype used by other    */
2634/* functions called from the IPFilter "mainline" in ipf_check().            */
2635/* ------------------------------------------------------------------------ */
2636frentry_t *
2637ipf_acctpkt(fin, passp)
2638	fr_info_t *fin;
2639	u_32_t *passp;
2640{
2641	ipf_main_softc_t *softc = fin->fin_main_soft;
2642	char group[FR_GROUPLEN];
2643	frentry_t *fr, *frsave;
2644	u_32_t pass, rulen;
2645
2646	passp = passp;
2647	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2648
2649	if (fr != NULL) {
2650		frsave = fin->fin_fr;
2651		bcopy(fin->fin_group, group, FR_GROUPLEN);
2652		rulen = fin->fin_rule;
2653		fin->fin_fr = fr;
2654		pass = ipf_scanlist(fin, FR_NOMATCH);
2655		if (FR_ISACCOUNT(pass)) {
2656			LBUMPD(ipf_stats[0], fr_acct);
2657		}
2658		fin->fin_fr = frsave;
2659		bcopy(group, fin->fin_group, FR_GROUPLEN);
2660		fin->fin_rule = rulen;
2661	}
2662	return NULL;
2663}
2664
2665
2666/* ------------------------------------------------------------------------ */
2667/* Function:    ipf_firewall                                                */
2668/* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2669/*                           were found, returns NULL.                      */
2670/* Parameters:  fin(I) - pointer to packet information                      */
2671/*              passp(IO) - pointer to current/new filter decision (unused) */
2672/*                                                                          */
2673/* Applies an appropriate set of firewall rules to the packet, to see if    */
2674/* there are any matches.  The first check is to see if a match can be seen */
2675/* in the cache.  If not, then search an appropriate list of rules.  Once a */
2676/* matching rule is found, take any appropriate actions as defined by the   */
2677/* rule - except logging.                                                   */
2678/* ------------------------------------------------------------------------ */
2679static frentry_t *
2680ipf_firewall(fin, passp)
2681	fr_info_t *fin;
2682	u_32_t *passp;
2683{
2684	ipf_main_softc_t *softc = fin->fin_main_soft;
2685	frentry_t *fr;
2686	u_32_t pass;
2687	int out;
2688
2689	out = fin->fin_out;
2690	pass = *passp;
2691
2692	/*
2693	 * This rule cache will only affect packets that are not being
2694	 * statefully filtered.
2695	 */
2696	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2697	if (fin->fin_fr != NULL)
2698		pass = ipf_scanlist(fin, softc->ipf_pass);
2699
2700	if ((pass & FR_NOMATCH)) {
2701		LBUMPD(ipf_stats[out], fr_nom);
2702	}
2703	fr = fin->fin_fr;
2704
2705	/*
2706	 * Apply packets per second rate-limiting to a rule as required.
2707	 */
2708	if ((fr != NULL) && (fr->fr_pps != 0) &&
2709	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2710		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2711		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2712		pass |= FR_BLOCK;
2713		LBUMPD(ipf_stats[out], fr_ppshit);
2714		fin->fin_reason = FRB_PPSRATE;
2715	}
2716
2717	/*
2718	 * If we fail to add a packet to the authorization queue, then we
2719	 * drop the packet later.  However, if it was added then pretend
2720	 * we've dropped it already.
2721	 */
2722	if (FR_ISAUTH(pass)) {
2723		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2724			DT1(frb_authnew, fr_info_t *, fin);
2725			fin->fin_m = *fin->fin_mp = NULL;
2726			fin->fin_reason = FRB_AUTHNEW;
2727			fin->fin_error = 0;
2728		} else {
2729			IPFERROR(1);
2730			fin->fin_error = ENOSPC;
2731		}
2732	}
2733
2734	if ((fr != NULL) && (fr->fr_func != NULL) &&
2735	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2736		(void) (*fr->fr_func)(fin, &pass);
2737
2738	/*
2739	 * If a rule is a pre-auth rule, check again in the list of rules
2740	 * loaded for authenticated use.  It does not particulary matter
2741	 * if this search fails because a "preauth" result, from a rule,
2742	 * is treated as "not a pass", hence the packet is blocked.
2743	 */
2744	if (FR_ISPREAUTH(pass)) {
2745		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2746	}
2747
2748	/*
2749	 * If the rule has "keep frag" and the packet is actually a fragment,
2750	 * then create a fragment state entry.
2751	 */
2752	if (pass & FR_KEEPFRAG) {
2753		if (fin->fin_flx & FI_FRAG) {
2754			if (ipf_frag_new(softc, fin, pass) == -1) {
2755				LBUMP(ipf_stats[out].fr_bnfr);
2756			} else {
2757				LBUMP(ipf_stats[out].fr_nfr);
2758			}
2759		} else {
2760			LBUMP(ipf_stats[out].fr_cfr);
2761		}
2762	}
2763
2764	fr = fin->fin_fr;
2765	*passp = pass;
2766
2767	return fr;
2768}
2769
2770
2771/* ------------------------------------------------------------------------ */
2772/* Function:    ipf_check                                                   */
2773/* Returns:     int -  0 == packet allowed through,                         */
2774/*              User space:                                                 */
2775/*                    -1 == packet blocked                                  */
2776/*                     1 == packet not matched                              */
2777/*                    -2 == requires authentication                         */
2778/*              Kernel:                                                     */
2779/*                   > 0 == filter error # for packet                       */
2780/* Parameters: ctx(I)  - pointer to the instance context                    */
2781/*             ip(I)   - pointer to start of IPv4/6 packet                  */
2782/*             hlen(I) - length of header                                   */
2783/*             ifp(I)  - pointer to interface this packet is on             */
2784/*             out(I)  - 0 == packet going in, 1 == packet going out        */
2785/*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2786/*                       IP packet.                                         */
2787/* Solaris:                                                                 */
2788/*             qpi(I)  - pointer to STREAMS queue information for this      */
2789/*                       interface & direction.                             */
2790/*                                                                          */
2791/* ipf_check() is the master function for all IPFilter packet processing.   */
2792/* It orchestrates: Network Address Translation (NAT), checking for packet  */
2793/* authorisation (or pre-authorisation), presence of related state info.,   */
2794/* generating log entries, IP packet accounting, routing of packets as      */
2795/* directed by firewall rules and of course whether or not to allow the     */
2796/* packet to be further processed by the kernel.                            */
2797/*                                                                          */
2798/* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2799/* freed.  Packets passed may be returned with the pointer pointed to by    */
2800/* by "mp" changed to a new buffer.                                         */
2801/* ------------------------------------------------------------------------ */
2802int
2803ipf_check(ctx, ip, hlen, ifp, out
2804#if defined(_KERNEL) && defined(MENTAT)
2805	, qif, mp)
2806	void *qif;
2807#else
2808	, mp)
2809#endif
2810	mb_t **mp;
2811	ip_t *ip;
2812	int hlen;
2813	void *ifp;
2814	int out;
2815	void *ctx;
2816{
2817	/*
2818	 * The above really sucks, but short of writing a diff
2819	 */
2820	ipf_main_softc_t *softc = ctx;
2821	fr_info_t frinfo;
2822	fr_info_t *fin = &frinfo;
2823	u_32_t pass = softc->ipf_pass;
2824	frentry_t *fr = NULL;
2825	int v = IP_V(ip);
2826	mb_t *mc = NULL;
2827	mb_t *m;
2828	/*
2829	 * The first part of ipf_check() deals with making sure that what goes
2830	 * into the filtering engine makes some sense.  Information about the
2831	 * the packet is distilled, collected into a fr_info_t structure and
2832	 * the an attempt to ensure the buffer the packet is in is big enough
2833	 * to hold all the required packet headers.
2834	 */
2835#ifdef	_KERNEL
2836# ifdef MENTAT
2837	qpktinfo_t *qpi = qif;
2838
2839#  ifdef __sparc
2840	if ((u_int)ip & 0x3)
2841		return 2;
2842#  endif
2843# else
2844	SPL_INT(s);
2845# endif
2846
2847	if (softc->ipf_running <= 0) {
2848		return 0;
2849	}
2850
2851	bzero((char *)fin, sizeof(*fin));
2852
2853# ifdef MENTAT
2854	if (qpi->qpi_flags & QF_BROADCAST)
2855		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2856	if (qpi->qpi_flags & QF_MULTICAST)
2857		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2858	m = qpi->qpi_m;
2859	fin->fin_qfm = m;
2860	fin->fin_qpi = qpi;
2861# else /* MENTAT */
2862
2863	m = *mp;
2864
2865#  if defined(M_MCAST)
2866	if ((m->m_flags & M_MCAST) != 0)
2867		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2868#  endif
2869#  if defined(M_MLOOP)
2870	if ((m->m_flags & M_MLOOP) != 0)
2871		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2872#  endif
2873#  if defined(M_BCAST)
2874	if ((m->m_flags & M_BCAST) != 0)
2875		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2876#  endif
2877#  ifdef M_CANFASTFWD
2878	/*
2879	 * XXX For now, IP Filter and fast-forwarding of cached flows
2880	 * XXX are mutually exclusive.  Eventually, IP Filter should
2881	 * XXX get a "can-fast-forward" filter rule.
2882	 */
2883	m->m_flags &= ~M_CANFASTFWD;
2884#  endif /* M_CANFASTFWD */
2885#  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2886				   (__FreeBSD_version < 501108))
2887	/*
2888	 * disable delayed checksums.
2889	 */
2890	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2891		in_delayed_cksum(m);
2892		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2893	}
2894#  endif /* CSUM_DELAY_DATA */
2895# endif /* MENTAT */
2896#else
2897	bzero((char *)fin, sizeof(*fin));
2898	m = *mp;
2899# if defined(M_MCAST)
2900	if ((m->m_flags & M_MCAST) != 0)
2901		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2902# endif
2903# if defined(M_MLOOP)
2904	if ((m->m_flags & M_MLOOP) != 0)
2905		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2906# endif
2907# if defined(M_BCAST)
2908	if ((m->m_flags & M_BCAST) != 0)
2909		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2910# endif
2911#endif /* _KERNEL */
2912
2913	fin->fin_v = v;
2914	fin->fin_m = m;
2915	fin->fin_ip = ip;
2916	fin->fin_mp = mp;
2917	fin->fin_out = out;
2918	fin->fin_ifp = ifp;
2919	fin->fin_error = ENETUNREACH;
2920	fin->fin_hlen = (u_short)hlen;
2921	fin->fin_dp = (char *)ip + hlen;
2922	fin->fin_main_soft = softc;
2923
2924	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2925
2926	SPL_NET(s);
2927
2928#ifdef	USE_INET6
2929	if (v == 6) {
2930		LBUMP(ipf_stats[out].fr_ipv6);
2931		/*
2932		 * Jumbo grams are quite likely too big for internal buffer
2933		 * structures to handle comfortably, for now, so just drop
2934		 * them.
2935		 */
2936		if (((ip6_t *)ip)->ip6_plen == 0) {
2937			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2938			pass = FR_BLOCK|FR_NOMATCH;
2939			fin->fin_reason = FRB_JUMBO;
2940			goto finished;
2941		}
2942		fin->fin_family = AF_INET6;
2943	} else
2944#endif
2945	{
2946		fin->fin_family = AF_INET;
2947	}
2948
2949	if (ipf_makefrip(hlen, ip, fin) == -1) {
2950		DT1(frb_makefrip, fr_info_t *, fin);
2951		pass = FR_BLOCK|FR_NOMATCH;
2952		fin->fin_reason = FRB_MAKEFRIP;
2953		goto finished;
2954	}
2955
2956	/*
2957	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2958	 * becomes NULL and so we have no packet to free.
2959	 */
2960	if (*fin->fin_mp == NULL)
2961		goto finished;
2962
2963	if (!out) {
2964		if (v == 4) {
2965			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2966				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2967				fin->fin_flx |= FI_BADSRC;
2968			}
2969			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2970				LBUMPD(ipf_stats[0], fr_v4_badttl);
2971				fin->fin_flx |= FI_LOWTTL;
2972			}
2973		}
2974#ifdef USE_INET6
2975		else  if (v == 6) {
2976			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2977				LBUMPD(ipf_stats[0], fr_v6_badttl);
2978				fin->fin_flx |= FI_LOWTTL;
2979			}
2980		}
2981#endif
2982	}
2983
2984	if (fin->fin_flx & FI_SHORT) {
2985		LBUMPD(ipf_stats[out], fr_short);
2986	}
2987
2988	READ_ENTER(&softc->ipf_mutex);
2989
2990	if (!out) {
2991		switch (fin->fin_v)
2992		{
2993		case 4 :
2994			if (ipf_nat_checkin(fin, &pass) == -1) {
2995				goto filterdone;
2996			}
2997			break;
2998#ifdef USE_INET6
2999		case 6 :
3000			if (ipf_nat6_checkin(fin, &pass) == -1) {
3001				goto filterdone;
3002			}
3003			break;
3004#endif
3005		default :
3006			break;
3007		}
3008	}
3009	/*
3010	 * Check auth now.
3011	 * If a packet is found in the auth table, then skip checking
3012	 * the access lists for permission but we do need to consider
3013	 * the result as if it were from the ACL's.  In addition, being
3014	 * found in the auth table means it has been seen before, so do
3015	 * not pass it through accounting (again), lest it be counted twice.
3016	 */
3017	fr = ipf_auth_check(fin, &pass);
3018	if (!out && (fr == NULL))
3019		(void) ipf_acctpkt(fin, NULL);
3020
3021	if (fr == NULL) {
3022		if ((fin->fin_flx & FI_FRAG) != 0)
3023			fr = ipf_frag_known(fin, &pass);
3024
3025		if (fr == NULL)
3026			fr = ipf_state_check(fin, &pass);
3027	}
3028
3029	if ((pass & FR_NOMATCH) || (fr == NULL))
3030		fr = ipf_firewall(fin, &pass);
3031
3032	/*
3033	 * If we've asked to track state for this packet, set it up.
3034	 * Here rather than ipf_firewall because ipf_checkauth may decide
3035	 * to return a packet for "keep state"
3036	 */
3037	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3038	    !(fin->fin_flx & FI_STATE)) {
3039		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3040			LBUMP(ipf_stats[out].fr_ads);
3041		} else {
3042			LBUMP(ipf_stats[out].fr_bads);
3043			if (FR_ISPASS(pass)) {
3044				DT(frb_stateadd);
3045				pass &= ~FR_CMDMASK;
3046				pass |= FR_BLOCK;
3047				fin->fin_reason = FRB_STATEADD;
3048			}
3049		}
3050	}
3051
3052	fin->fin_fr = fr;
3053	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3054		fin->fin_dif = &fr->fr_dif;
3055		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3056	}
3057
3058	/*
3059	 * Only count/translate packets which will be passed on, out the
3060	 * interface.
3061	 */
3062	if (out && FR_ISPASS(pass)) {
3063		(void) ipf_acctpkt(fin, NULL);
3064
3065		switch (fin->fin_v)
3066		{
3067		case 4 :
3068			if (ipf_nat_checkout(fin, &pass) == -1) {
3069				;
3070			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3071				if (ipf_updateipid(fin) == -1) {
3072					DT(frb_updateipid);
3073					LBUMP(ipf_stats[1].fr_ipud);
3074					pass &= ~FR_CMDMASK;
3075					pass |= FR_BLOCK;
3076					fin->fin_reason = FRB_UPDATEIPID;
3077				} else {
3078					LBUMP(ipf_stats[0].fr_ipud);
3079				}
3080			}
3081			break;
3082#ifdef USE_INET6
3083		case 6 :
3084			(void) ipf_nat6_checkout(fin, &pass);
3085			break;
3086#endif
3087		default :
3088			break;
3089		}
3090	}
3091
3092filterdone:
3093#ifdef	IPFILTER_LOG
3094	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3095		(void) ipf_dolog(fin, &pass);
3096	}
3097#endif
3098
3099	/*
3100	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3101	 * will work when called from inside of fr_fastroute.  Although
3102	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3103	 * impact on code execution.
3104	 */
3105	fin->fin_flx &= ~FI_STATE;
3106
3107#if defined(FASTROUTE_RECURSION)
3108	/*
3109	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3110	 * a packet below can sometimes cause a recursive call into IPFilter.
3111	 * On those platforms where that does happen, we need to hang onto
3112	 * the filter rule just in case someone decides to remove or flush it
3113	 * in the meantime.
3114	 */
3115	if (fr != NULL) {
3116		MUTEX_ENTER(&fr->fr_lock);
3117		fr->fr_ref++;
3118		MUTEX_EXIT(&fr->fr_lock);
3119	}
3120
3121	RWLOCK_EXIT(&softc->ipf_mutex);
3122#endif
3123
3124	if ((pass & FR_RETMASK) != 0) {
3125		/*
3126		 * Should we return an ICMP packet to indicate error
3127		 * status passing through the packet filter ?
3128		 * WARNING: ICMP error packets AND TCP RST packets should
3129		 * ONLY be sent in repsonse to incoming packets.  Sending
3130		 * them in response to outbound packets can result in a
3131		 * panic on some operating systems.
3132		 */
3133		if (!out) {
3134			if (pass & FR_RETICMP) {
3135				int dst;
3136
3137				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3138					dst = 1;
3139				else
3140					dst = 0;
3141				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3142							 dst);
3143				LBUMP(ipf_stats[0].fr_ret);
3144			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3145				   !(fin->fin_flx & FI_SHORT)) {
3146				if (((fin->fin_flx & FI_OOW) != 0) ||
3147				    (ipf_send_reset(fin) == 0)) {
3148					LBUMP(ipf_stats[1].fr_ret);
3149				}
3150			}
3151
3152			/*
3153			 * When using return-* with auth rules, the auth code
3154			 * takes over disposing of this packet.
3155			 */
3156			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3157				DT1(frb_authcapture, fr_info_t *, fin);
3158				fin->fin_m = *fin->fin_mp = NULL;
3159				fin->fin_reason = FRB_AUTHCAPTURE;
3160				m = NULL;
3161			}
3162		} else {
3163			if (pass & FR_RETRST) {
3164				fin->fin_error = ECONNRESET;
3165			}
3166		}
3167	}
3168
3169	/*
3170	 * After the above so that ICMP unreachables and TCP RSTs get
3171	 * created properly.
3172	 */
3173	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3174		ipf_nat_uncreate(fin);
3175
3176	/*
3177	 * If we didn't drop off the bottom of the list of rules (and thus
3178	 * the 'current' rule fr is not NULL), then we may have some extra
3179	 * instructions about what to do with a packet.
3180	 * Once we're finished return to our caller, freeing the packet if
3181	 * we are dropping it.
3182	 */
3183	if (fr != NULL) {
3184		frdest_t *fdp;
3185
3186		/*
3187		 * Generate a duplicated packet first because ipf_fastroute
3188		 * can lead to fin_m being free'd... not good.
3189		 */
3190		fdp = fin->fin_dif;
3191		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3192		    (fdp->fd_ptr != (void *)-1)) {
3193			mc = M_COPY(fin->fin_m);
3194			if (mc != NULL)
3195				ipf_fastroute(mc, &mc, fin, fdp);
3196		}
3197
3198		fdp = fin->fin_tif;
3199		if (!out && (pass & FR_FASTROUTE)) {
3200			/*
3201			 * For fastroute rule, no destination interface defined
3202			 * so pass NULL as the frdest_t parameter
3203			 */
3204			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3205			m = *mp = NULL;
3206		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3207			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3208			/* this is for to rules: */
3209			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3210			m = *mp = NULL;
3211		}
3212
3213#if defined(FASTROUTE_RECURSION)
3214		(void) ipf_derefrule(softc, &fr);
3215#endif
3216	}
3217#if !defined(FASTROUTE_RECURSION)
3218	RWLOCK_EXIT(&softc->ipf_mutex);
3219#endif
3220
3221finished:
3222	if (!FR_ISPASS(pass)) {
3223		LBUMP(ipf_stats[out].fr_block);
3224		if (*mp != NULL) {
3225#ifdef _KERNEL
3226			FREE_MB_T(*mp);
3227#endif
3228			m = *mp = NULL;
3229		}
3230	} else {
3231		LBUMP(ipf_stats[out].fr_pass);
3232	}
3233
3234	SPL_X(s);
3235
3236#ifdef _KERNEL
3237	if (FR_ISPASS(pass))
3238		return 0;
3239	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3240	return fin->fin_error;
3241#else /* _KERNEL */
3242	if (*mp != NULL)
3243		(*mp)->mb_ifp = fin->fin_ifp;
3244	blockreason = fin->fin_reason;
3245	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3246	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3247		if ((pass & FR_NOMATCH) != 0)
3248			return 1;
3249
3250	if ((pass & FR_RETMASK) != 0)
3251		switch (pass & FR_RETMASK)
3252		{
3253		case FR_RETRST :
3254			return 3;
3255		case FR_RETICMP :
3256			return 4;
3257		case FR_FAKEICMP :
3258			return 5;
3259		}
3260
3261	switch (pass & FR_CMDMASK)
3262	{
3263	case FR_PASS :
3264		return 0;
3265	case FR_BLOCK :
3266		return -1;
3267	case FR_AUTH :
3268		return -2;
3269	case FR_ACCOUNT :
3270		return -3;
3271	case FR_PREAUTH :
3272		return -4;
3273	}
3274	return 2;
3275#endif /* _KERNEL */
3276}
3277
3278
3279#ifdef	IPFILTER_LOG
3280/* ------------------------------------------------------------------------ */
3281/* Function:    ipf_dolog                                                   */
3282/* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3283/* Parameters:  fin(I) - pointer to packet information                      */
3284/*              passp(IO) - pointer to current/new filter decision (unused) */
3285/*                                                                          */
3286/* Checks flags set to see how a packet should be logged, if it is to be    */
3287/* logged.  Adjust statistics based on its success or not.                  */
3288/* ------------------------------------------------------------------------ */
3289frentry_t *
3290ipf_dolog(fin, passp)
3291	fr_info_t *fin;
3292	u_32_t *passp;
3293{
3294	ipf_main_softc_t *softc = fin->fin_main_soft;
3295	u_32_t pass;
3296	int out;
3297
3298	out = fin->fin_out;
3299	pass = *passp;
3300
3301	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3302		pass |= FF_LOGNOMATCH;
3303		LBUMPD(ipf_stats[out], fr_npkl);
3304		goto logit;
3305
3306	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3307	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3308		if ((pass & FR_LOGMASK) != FR_LOGP)
3309			pass |= FF_LOGPASS;
3310		LBUMPD(ipf_stats[out], fr_ppkl);
3311		goto logit;
3312
3313	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3314		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3315		if ((pass & FR_LOGMASK) != FR_LOGB)
3316			pass |= FF_LOGBLOCK;
3317		LBUMPD(ipf_stats[out], fr_bpkl);
3318
3319logit:
3320		if (ipf_log_pkt(fin, pass) == -1) {
3321			/*
3322			 * If the "or-block" option has been used then
3323			 * block the packet if we failed to log it.
3324			 */
3325			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3326				DT1(frb_logfail2, u_int, pass);
3327				pass &= ~FR_CMDMASK;
3328				pass |= FR_BLOCK;
3329				fin->fin_reason = FRB_LOGFAIL2;
3330			}
3331		}
3332		*passp = pass;
3333	}
3334
3335	return fin->fin_fr;
3336}
3337#endif /* IPFILTER_LOG */
3338
3339
3340/* ------------------------------------------------------------------------ */
3341/* Function:    ipf_cksum                                                   */
3342/* Returns:     u_short - IP header checksum                                */
3343/* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3344/*              len(I)  - length of buffer in bytes                         */
3345/*                                                                          */
3346/* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3347/*                                                                          */
3348/* N.B.: addr should be 16bit aligned.                                      */
3349/* ------------------------------------------------------------------------ */
3350u_short
3351ipf_cksum(addr, len)
3352	u_short *addr;
3353	int len;
3354{
3355	u_32_t sum = 0;
3356
3357	for (sum = 0; len > 1; len -= 2)
3358		sum += *addr++;
3359
3360	/* mop up an odd byte, if necessary */
3361	if (len == 1)
3362		sum += *(u_char *)addr;
3363
3364	/*
3365	 * add back carry outs from top 16 bits to low 16 bits
3366	 */
3367	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3368	sum += (sum >> 16);			/* add carry */
3369	return (u_short)(~sum);
3370}
3371
3372
3373/* ------------------------------------------------------------------------ */
3374/* Function:    fr_cksum                                                    */
3375/* Returns:     u_short - layer 4 checksum                                  */
3376/* Parameters:  fin(I)     - pointer to packet information                  */
3377/*              ip(I)      - pointer to IP header                           */
3378/*              l4proto(I) - protocol to caclulate checksum for             */
3379/*              l4hdr(I)   - pointer to layer 4 header                      */
3380/*                                                                          */
3381/* Calculates the TCP checksum for the packet held in "m", using the data   */
3382/* in the IP header "ip" to seed it.                                        */
3383/*                                                                          */
3384/* NB: This function assumes we've pullup'd enough for all of the IP header */
3385/* and the TCP header.  We also assume that data blocks aren't allocated in */
3386/* odd sizes.                                                               */
3387/*                                                                          */
3388/* Expects ip_len and ip_off to be in network byte order when called.       */
3389/* ------------------------------------------------------------------------ */
3390u_short
3391fr_cksum(fin, ip, l4proto, l4hdr)
3392	fr_info_t *fin;
3393	ip_t *ip;
3394	int l4proto;
3395	void *l4hdr;
3396{
3397	u_short *sp, slen, sumsave, *csump;
3398	u_int sum, sum2;
3399	int hlen;
3400	int off;
3401#ifdef	USE_INET6
3402	ip6_t *ip6;
3403#endif
3404
3405	csump = NULL;
3406	sumsave = 0;
3407	sp = NULL;
3408	slen = 0;
3409	hlen = 0;
3410	sum = 0;
3411
3412	sum = htons((u_short)l4proto);
3413	/*
3414	 * Add up IP Header portion
3415	 */
3416#ifdef	USE_INET6
3417	if (IP_V(ip) == 4) {
3418#endif
3419		hlen = IP_HL(ip) << 2;
3420		off = hlen;
3421		sp = (u_short *)&ip->ip_src;
3422		sum += *sp++;	/* ip_src */
3423		sum += *sp++;
3424		sum += *sp++;	/* ip_dst */
3425		sum += *sp++;
3426#ifdef	USE_INET6
3427	} else if (IP_V(ip) == 6) {
3428		ip6 = (ip6_t *)ip;
3429		hlen = sizeof(*ip6);
3430		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3431		sp = (u_short *)&ip6->ip6_src;
3432		sum += *sp++;	/* ip6_src */
3433		sum += *sp++;
3434		sum += *sp++;
3435		sum += *sp++;
3436		sum += *sp++;
3437		sum += *sp++;
3438		sum += *sp++;
3439		sum += *sp++;
3440		/* This needs to be routing header aware. */
3441		sum += *sp++;	/* ip6_dst */
3442		sum += *sp++;
3443		sum += *sp++;
3444		sum += *sp++;
3445		sum += *sp++;
3446		sum += *sp++;
3447		sum += *sp++;
3448		sum += *sp++;
3449	} else {
3450		return 0xffff;
3451	}
3452#endif
3453	slen = fin->fin_plen - off;
3454	sum += htons(slen);
3455
3456	switch (l4proto)
3457	{
3458	case IPPROTO_UDP :
3459		csump = &((udphdr_t *)l4hdr)->uh_sum;
3460		break;
3461
3462	case IPPROTO_TCP :
3463		csump = &((tcphdr_t *)l4hdr)->th_sum;
3464		break;
3465	case IPPROTO_ICMP :
3466		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3467		sum = 0;	/* Pseudo-checksum is not included */
3468		break;
3469#ifdef USE_INET6
3470	case IPPROTO_ICMPV6 :
3471		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3472		break;
3473#endif
3474	default :
3475		break;
3476	}
3477
3478	if (csump != NULL) {
3479		sumsave = *csump;
3480		*csump = 0;
3481	}
3482
3483	sum2 = ipf_pcksum(fin, off, sum);
3484	if (csump != NULL)
3485		*csump = sumsave;
3486	return sum2;
3487}
3488
3489
3490/* ------------------------------------------------------------------------ */
3491/* Function:    ipf_findgroup                                               */
3492/* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3493/* Parameters:  softc(I) - pointer to soft context main structure           */
3494/*              group(I) - group name to search for                         */
3495/*              unit(I)  - device to which this group belongs               */
3496/*              set(I)   - which set of rules (inactive/inactive) this is   */
3497/*              fgpp(O)  - pointer to place to store pointer to the pointer */
3498/*                         to where to add the next (last) group or where   */
3499/*                         to delete group from.                            */
3500/*                                                                          */
3501/* Search amongst the defined groups for a particular group number.         */
3502/* ------------------------------------------------------------------------ */
3503frgroup_t *
3504ipf_findgroup(softc, group, unit, set, fgpp)
3505	ipf_main_softc_t *softc;
3506	char *group;
3507	minor_t unit;
3508	int set;
3509	frgroup_t ***fgpp;
3510{
3511	frgroup_t *fg, **fgp;
3512
3513	/*
3514	 * Which list of groups to search in is dependent on which list of
3515	 * rules are being operated on.
3516	 */
3517	fgp = &softc->ipf_groups[unit][set];
3518
3519	while ((fg = *fgp) != NULL) {
3520		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3521			break;
3522		else
3523			fgp = &fg->fg_next;
3524	}
3525	if (fgpp != NULL)
3526		*fgpp = fgp;
3527	return fg;
3528}
3529
3530
3531/* ------------------------------------------------------------------------ */
3532/* Function:    ipf_group_add                                               */
3533/* Returns:     frgroup_t * - NULL == did not create group,                 */
3534/*                            != NULL == pointer to the group               */
3535/* Parameters:  softc(I) - pointer to soft context main structure           */
3536/*              num(I)   - group number to add                              */
3537/*              head(I)  - rule pointer that is using this as the head      */
3538/*              flags(I) - rule flags which describe the type of rule it is */
3539/*              unit(I)  - device to which this group will belong to        */
3540/*              set(I)   - which set of rules (inactive/inactive) this is   */
3541/* Write Locks: ipf_mutex                                                   */
3542/*                                                                          */
3543/* Add a new group head, or if it already exists, increase the reference    */
3544/* count to it.                                                             */
3545/* ------------------------------------------------------------------------ */
3546frgroup_t *
3547ipf_group_add(softc, group, head, flags, unit, set)
3548	ipf_main_softc_t *softc;
3549	char *group;
3550	void *head;
3551	u_32_t flags;
3552	minor_t unit;
3553	int set;
3554{
3555	frgroup_t *fg, **fgp;
3556	u_32_t gflags;
3557
3558	if (group == NULL)
3559		return NULL;
3560
3561	if (unit == IPL_LOGIPF && *group == '\0')
3562		return NULL;
3563
3564	fgp = NULL;
3565	gflags = flags & FR_INOUT;
3566
3567	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3568	if (fg != NULL) {
3569		if (fg->fg_head == NULL && head != NULL)
3570			fg->fg_head = head;
3571		if (fg->fg_flags == 0)
3572			fg->fg_flags = gflags;
3573		else if (gflags != fg->fg_flags)
3574			return NULL;
3575		fg->fg_ref++;
3576		return fg;
3577	}
3578
3579	KMALLOC(fg, frgroup_t *);
3580	if (fg != NULL) {
3581		fg->fg_head = head;
3582		fg->fg_start = NULL;
3583		fg->fg_next = *fgp;
3584		bcopy(group, fg->fg_name, strlen(group) + 1);
3585		fg->fg_flags = gflags;
3586		fg->fg_ref = 1;
3587		fg->fg_set = &softc->ipf_groups[unit][set];
3588		*fgp = fg;
3589	}
3590	return fg;
3591}
3592
3593
3594/* ------------------------------------------------------------------------ */
3595/* Function:    ipf_group_del                                               */
3596/* Returns:     int      - number of rules deleted                          */
3597/* Parameters:  softc(I) - pointer to soft context main structure           */
3598/*              group(I) - group name to delete                             */
3599/*              fr(I)    - filter rule from which group is referenced       */
3600/* Write Locks: ipf_mutex                                                   */
3601/*                                                                          */
3602/* This function is called whenever a reference to a group is to be dropped */
3603/* and thus its reference count needs to be lowered and the group free'd if */
3604/* the reference count reaches zero. Passing in fr is really for the sole   */
3605/* purpose of knowing when the head rule is being deleted.                  */
3606/* ------------------------------------------------------------------------ */
3607void
3608ipf_group_del(softc, group, fr)
3609	ipf_main_softc_t *softc;
3610	frgroup_t *group;
3611	frentry_t *fr;
3612{
3613
3614	if (group->fg_head == fr)
3615		group->fg_head = NULL;
3616
3617	group->fg_ref--;
3618	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3619		ipf_group_free(group);
3620}
3621
3622
3623/* ------------------------------------------------------------------------ */
3624/* Function:    ipf_group_free                                              */
3625/* Returns:     Nil                                                         */
3626/* Parameters:  group(I) - pointer to filter rule group                     */
3627/*                                                                          */
3628/* Remove the group from the list of groups and free it.                    */
3629/* ------------------------------------------------------------------------ */
3630static void
3631ipf_group_free(group)
3632	frgroup_t *group;
3633{
3634	frgroup_t **gp;
3635
3636	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3637		if (*gp == group) {
3638			*gp = group->fg_next;
3639			break;
3640		}
3641	}
3642	KFREE(group);
3643}
3644
3645
3646/* ------------------------------------------------------------------------ */
3647/* Function:    ipf_group_flush                                             */
3648/* Returns:     int      - number of rules flush from group                 */
3649/* Parameters:  softc(I) - pointer to soft context main structure           */
3650/* Parameters:  group(I) - pointer to filter rule group                     */
3651/*                                                                          */
3652/* Remove all of the rules that currently are listed under the given group. */
3653/* ------------------------------------------------------------------------ */
3654static int
3655ipf_group_flush(softc, group)
3656	ipf_main_softc_t *softc;
3657	frgroup_t *group;
3658{
3659	int gone = 0;
3660
3661	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3662
3663	return gone;
3664}
3665
3666
3667/* ------------------------------------------------------------------------ */
3668/* Function:    ipf_getrulen                                                */
3669/* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3670/* Parameters:  softc(I) - pointer to soft context main structure           */
3671/* Parameters:  unit(I)  - device for which to count the rule's number      */
3672/*              flags(I) - which set of rules to find the rule in           */
3673/*              group(I) - group name                                       */
3674/*              n(I)     - rule number to find                              */
3675/*                                                                          */
3676/* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3677/* group # g doesn't exist or there are less than n rules in the group.     */
3678/* ------------------------------------------------------------------------ */
3679frentry_t *
3680ipf_getrulen(softc, unit, group, n)
3681	ipf_main_softc_t *softc;
3682	int unit;
3683	char *group;
3684	u_32_t n;
3685{
3686	frentry_t *fr;
3687	frgroup_t *fg;
3688
3689	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3690	if (fg == NULL)
3691		return NULL;
3692	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3693		;
3694	if (n != 0)
3695		return NULL;
3696	return fr;
3697}
3698
3699
3700/* ------------------------------------------------------------------------ */
3701/* Function:    ipf_flushlist                                               */
3702/* Returns:     int - >= 0 - number of flushed rules                        */
3703/* Parameters:  softc(I)   - pointer to soft context main structure         */
3704/*              nfreedp(O) - pointer to int where flush count is stored     */
3705/*              listp(I)   - pointer to list to flush pointer               */
3706/* Write Locks: ipf_mutex                                                   */
3707/*                                                                          */
3708/* Recursively flush rules from the list, descending groups as they are     */
3709/* encountered.  if a rule is the head of a group and it has lost all its   */
3710/* group members, then also delete the group reference.  nfreedp is needed  */
3711/* to store the accumulating count of rules removed, whereas the returned   */
3712/* value is just the number removed from the current list.  The latter is   */
3713/* needed to correctly adjust reference counts on rules that define groups. */
3714/*                                                                          */
3715/* NOTE: Rules not loaded from user space cannot be flushed.                */
3716/* ------------------------------------------------------------------------ */
3717static int
3718ipf_flushlist(softc, nfreedp, listp)
3719	ipf_main_softc_t *softc;
3720	int *nfreedp;
3721	frentry_t **listp;
3722{
3723	int freed = 0;
3724	frentry_t *fp;
3725
3726	while ((fp = *listp) != NULL) {
3727		if ((fp->fr_type & FR_T_BUILTIN) ||
3728		    !(fp->fr_flags & FR_COPIED)) {
3729			listp = &fp->fr_next;
3730			continue;
3731		}
3732		*listp = fp->fr_next;
3733		if (fp->fr_next != NULL)
3734			fp->fr_next->fr_pnext = fp->fr_pnext;
3735		fp->fr_pnext = NULL;
3736
3737		if (fp->fr_grphead != NULL) {
3738			freed += ipf_group_flush(softc, fp->fr_grphead);
3739			fp->fr_names[fp->fr_grhead] = '\0';
3740		}
3741
3742		if (fp->fr_icmpgrp != NULL) {
3743			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3744			fp->fr_names[fp->fr_icmphead] = '\0';
3745		}
3746
3747		if (fp->fr_srctrack.ht_max_nodes)
3748			ipf_rb_ht_flush(&fp->fr_srctrack);
3749
3750		fp->fr_next = NULL;
3751
3752		ASSERT(fp->fr_ref > 0);
3753		if (ipf_derefrule(softc, &fp) == 0)
3754			freed++;
3755	}
3756	*nfreedp += freed;
3757	return freed;
3758}
3759
3760
3761/* ------------------------------------------------------------------------ */
3762/* Function:    ipf_flush                                                   */
3763/* Returns:     int - >= 0 - number of flushed rules                        */
3764/* Parameters:  softc(I) - pointer to soft context main structure           */
3765/*              unit(I)  - device for which to flush rules                  */
3766/*              flags(I) - which set of rules to flush                      */
3767/*                                                                          */
3768/* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3769/* and IPv6) as defined by the value of flags.                              */
3770/* ------------------------------------------------------------------------ */
3771int
3772ipf_flush(softc, unit, flags)
3773	ipf_main_softc_t *softc;
3774	minor_t unit;
3775	int flags;
3776{
3777	int flushed = 0, set;
3778
3779	WRITE_ENTER(&softc->ipf_mutex);
3780
3781	set = softc->ipf_active;
3782	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3783		set = 1 - set;
3784
3785	if (flags & FR_OUTQUE) {
3786		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3787		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3788	}
3789	if (flags & FR_INQUE) {
3790		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3791		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3792	}
3793
3794	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3795				    flags & (FR_INQUE|FR_OUTQUE));
3796
3797	RWLOCK_EXIT(&softc->ipf_mutex);
3798
3799	if (unit == IPL_LOGIPF) {
3800		int tmp;
3801
3802		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3803		if (tmp >= 0)
3804			flushed += tmp;
3805	}
3806	return flushed;
3807}
3808
3809
3810/* ------------------------------------------------------------------------ */
3811/* Function:    ipf_flush_groups                                            */
3812/* Returns:     int - >= 0 - number of flushed rules                        */
3813/* Parameters:  softc(I)  - soft context pointerto work with                */
3814/*              grhead(I) - pointer to the start of the group list to flush */
3815/*              flags(I)  - which set of rules to flush                     */
3816/*                                                                          */
3817/* Walk through all of the groups under the given group head and remove all */
3818/* of those that match the flags passed in. The for loop here is bit more   */
3819/* complicated than usual because the removal of a rule with ipf_derefrule  */
3820/* may end up removing not only the structure pointed to by "fg" but also   */
3821/* what is fg_next and fg_next after that. So if a filter rule is actually  */
3822/* removed from the group then it is necessary to start again.              */
3823/* ------------------------------------------------------------------------ */
3824static int
3825ipf_flush_groups(softc, grhead, flags)
3826	ipf_main_softc_t *softc;
3827	frgroup_t **grhead;
3828	int flags;
3829{
3830	frentry_t *fr, **frp;
3831	frgroup_t *fg, **fgp;
3832	int flushed = 0;
3833	int removed = 0;
3834
3835	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3836		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3837			fg = fg->fg_next;
3838		if (fg == NULL)
3839			break;
3840		removed = 0;
3841		frp = &fg->fg_start;
3842		while ((removed == 0) && ((fr = *frp) != NULL)) {
3843			if ((fr->fr_flags & flags) == 0) {
3844				frp = &fr->fr_next;
3845			} else {
3846				if (fr->fr_next != NULL)
3847					fr->fr_next->fr_pnext = fr->fr_pnext;
3848				*frp = fr->fr_next;
3849				fr->fr_pnext = NULL;
3850				fr->fr_next = NULL;
3851				(void) ipf_derefrule(softc, &fr);
3852				flushed++;
3853				removed++;
3854			}
3855		}
3856		if (removed == 0)
3857			fgp = &fg->fg_next;
3858	}
3859	return flushed;
3860}
3861
3862
3863/* ------------------------------------------------------------------------ */
3864/* Function:    memstr                                                      */
3865/* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3866/* Parameters:  src(I)  - pointer to byte sequence to match                 */
3867/*              dst(I)  - pointer to byte sequence to search                */
3868/*              slen(I) - match length                                      */
3869/*              dlen(I) - length available to search in                     */
3870/*                                                                          */
3871/* Search dst for a sequence of bytes matching those at src and extend for  */
3872/* slen bytes.                                                              */
3873/* ------------------------------------------------------------------------ */
3874char *
3875memstr(src, dst, slen, dlen)
3876	const char *src;
3877	char *dst;
3878	size_t slen, dlen;
3879{
3880	char *s = NULL;
3881
3882	while (dlen >= slen) {
3883		if (bcmp(src, dst, slen) == 0) {
3884			s = dst;
3885			break;
3886		}
3887		dst++;
3888		dlen--;
3889	}
3890	return s;
3891}
3892/* ------------------------------------------------------------------------ */
3893/* Function:    ipf_fixskip                                                 */
3894/* Returns:     Nil                                                         */
3895/* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3896/*              rp(I)        - rule added/removed with skip in it.          */
3897/*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3898/*                             depending on whether a rule was just added   */
3899/*                             or removed.                                  */
3900/*                                                                          */
3901/* Adjust all the rules in a list which would have skip'd past the position */
3902/* where we are inserting to skip to the right place given the change.      */
3903/* ------------------------------------------------------------------------ */
3904void
3905ipf_fixskip(listp, rp, addremove)
3906	frentry_t **listp, *rp;
3907	int addremove;
3908{
3909	int rules, rn;
3910	frentry_t *fp;
3911
3912	rules = 0;
3913	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3914		rules++;
3915
3916	if (!fp)
3917		return;
3918
3919	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3920		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3921			fp->fr_arg += addremove;
3922}
3923
3924
3925#ifdef	_KERNEL
3926/* ------------------------------------------------------------------------ */
3927/* Function:    count4bits                                                  */
3928/* Returns:     int - >= 0 - number of consecutive bits in input            */
3929/* Parameters:  ip(I) - 32bit IP address                                    */
3930/*                                                                          */
3931/* IPv4 ONLY                                                                */
3932/* count consecutive 1's in bit mask.  If the mask generated by counting    */
3933/* consecutive 1's is different to that passed, return -1, else return #    */
3934/* of bits.                                                                 */
3935/* ------------------------------------------------------------------------ */
3936int
3937count4bits(ip)
3938	u_32_t	ip;
3939{
3940	u_32_t	ipn;
3941	int	cnt = 0, i, j;
3942
3943	ip = ipn = ntohl(ip);
3944	for (i = 32; i; i--, ipn *= 2)
3945		if (ipn & 0x80000000)
3946			cnt++;
3947		else
3948			break;
3949	ipn = 0;
3950	for (i = 32, j = cnt; i; i--, j--) {
3951		ipn *= 2;
3952		if (j > 0)
3953			ipn++;
3954	}
3955	if (ipn == ip)
3956		return cnt;
3957	return -1;
3958}
3959
3960
3961/* ------------------------------------------------------------------------ */
3962/* Function:    count6bits                                                  */
3963/* Returns:     int - >= 0 - number of consecutive bits in input            */
3964/* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3965/*                                                                          */
3966/* IPv6 ONLY                                                                */
3967/* count consecutive 1's in bit mask.                                       */
3968/* ------------------------------------------------------------------------ */
3969# ifdef USE_INET6
3970int
3971count6bits(msk)
3972	u_32_t *msk;
3973{
3974	int i = 0, k;
3975	u_32_t j;
3976
3977	for (k = 3; k >= 0; k--)
3978		if (msk[k] == 0xffffffff)
3979			i += 32;
3980		else {
3981			for (j = msk[k]; j; j <<= 1)
3982				if (j & 0x80000000)
3983					i++;
3984		}
3985	return i;
3986}
3987# endif
3988#endif /* _KERNEL */
3989
3990
3991/* ------------------------------------------------------------------------ */
3992/* Function:    ipf_synclist                                                */
3993/* Returns:     int    - 0 = no failures, else indication of first failure  */
3994/* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3995/*              ifp(I) - interface pointer for limiting sync lookups        */
3996/* Write Locks: ipf_mutex                                                   */
3997/*                                                                          */
3998/* Walk through a list of filter rules and resolve any interface names into */
3999/* pointers.  Where dynamic addresses are used, also update the IP address  */
4000/* used in the rule.  The interface pointer is used to limit the lookups to */
4001/* a specific set of matching names if it is non-NULL.                      */
4002/* Errors can occur when resolving the destination name of to/dup-to fields */
4003/* when the name points to a pool and that pool doest not exist. If this    */
4004/* does happen then it is necessary to check if there are any lookup refs   */
4005/* that need to be dropped before returning with an error.                  */
4006/* ------------------------------------------------------------------------ */
4007static int
4008ipf_synclist(softc, fr, ifp)
4009	ipf_main_softc_t *softc;
4010	frentry_t *fr;
4011	void *ifp;
4012{
4013	frentry_t *frt, *start = fr;
4014	frdest_t *fdp;
4015	char *name;
4016	int error;
4017	void *ifa;
4018	int v, i;
4019
4020	error = 0;
4021
4022	for (; fr; fr = fr->fr_next) {
4023		if (fr->fr_family == AF_INET)
4024			v = 4;
4025		else if (fr->fr_family == AF_INET6)
4026			v = 6;
4027		else
4028			v = 0;
4029
4030		/*
4031		 * Lookup all the interface names that are part of the rule.
4032		 */
4033		for (i = 0; i < 4; i++) {
4034			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4035				continue;
4036			if (fr->fr_ifnames[i] == -1)
4037				continue;
4038			name = FR_NAME(fr, fr_ifnames[i]);
4039			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4040		}
4041
4042		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4043			if (fr->fr_satype != FRI_NORMAL &&
4044			    fr->fr_satype != FRI_LOOKUP) {
4045				ifa = ipf_resolvenic(softc, fr->fr_names +
4046						     fr->fr_sifpidx, v);
4047				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4048					    &fr->fr_src6, &fr->fr_smsk6);
4049			}
4050			if (fr->fr_datype != FRI_NORMAL &&
4051			    fr->fr_datype != FRI_LOOKUP) {
4052				ifa = ipf_resolvenic(softc, fr->fr_names +
4053						     fr->fr_sifpidx, v);
4054				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4055					    &fr->fr_dst6, &fr->fr_dmsk6);
4056			}
4057		}
4058
4059		fdp = &fr->fr_tifs[0];
4060		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4061			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4062			if (error != 0)
4063				goto unwind;
4064		}
4065
4066		fdp = &fr->fr_tifs[1];
4067		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4068			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4069			if (error != 0)
4070				goto unwind;
4071		}
4072
4073		fdp = &fr->fr_dif;
4074		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4075			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4076			if (error != 0)
4077				goto unwind;
4078		}
4079
4080		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4081		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4082			fr->fr_srcptr = ipf_lookup_res_num(softc,
4083							   fr->fr_srctype,
4084							   IPL_LOGIPF,
4085							   fr->fr_srcnum,
4086							   &fr->fr_srcfunc);
4087		}
4088		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4089		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4090			fr->fr_dstptr = ipf_lookup_res_num(softc,
4091							   fr->fr_dsttype,
4092							   IPL_LOGIPF,
4093							   fr->fr_dstnum,
4094							   &fr->fr_dstfunc);
4095		}
4096	}
4097	return 0;
4098
4099unwind:
4100	for (frt = start; frt != fr; fr = fr->fr_next) {
4101		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4102		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4103				ipf_lookup_deref(softc, frt->fr_srctype,
4104						 frt->fr_srcptr);
4105		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4106		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4107				ipf_lookup_deref(softc, frt->fr_dsttype,
4108						 frt->fr_dstptr);
4109	}
4110	return error;
4111}
4112
4113
4114/* ------------------------------------------------------------------------ */
4115/* Function:    ipf_sync                                                    */
4116/* Returns:     void                                                        */
4117/* Parameters:  Nil                                                         */
4118/*                                                                          */
4119/* ipf_sync() is called when we suspect that the interface list or          */
4120/* information about interfaces (like IP#) has changed.  Go through all     */
4121/* filter rules, NAT entries and the state table and check if anything      */
4122/* needs to be changed/updated.                                             */
4123/* ------------------------------------------------------------------------ */
4124int
4125ipf_sync(softc, ifp)
4126	ipf_main_softc_t *softc;
4127	void *ifp;
4128{
4129	int i;
4130
4131# if !SOLARIS
4132	ipf_nat_sync(softc, ifp);
4133	ipf_state_sync(softc, ifp);
4134	ipf_lookup_sync(softc, ifp);
4135# endif
4136
4137	WRITE_ENTER(&softc->ipf_mutex);
4138	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4139	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4140	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4141	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4142
4143	for (i = 0; i < IPL_LOGSIZE; i++) {
4144		frgroup_t *g;
4145
4146		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4147			(void) ipf_synclist(softc, g->fg_start, ifp);
4148		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4149			(void) ipf_synclist(softc, g->fg_start, ifp);
4150	}
4151	RWLOCK_EXIT(&softc->ipf_mutex);
4152
4153	return 0;
4154}
4155
4156
4157/*
4158 * In the functions below, bcopy() is called because the pointer being
4159 * copied _from_ in this instance is a pointer to a char buf (which could
4160 * end up being unaligned) and on the kernel's local stack.
4161 */
4162/* ------------------------------------------------------------------------ */
4163/* Function:    copyinptr                                                   */
4164/* Returns:     int - 0 = success, else failure                             */
4165/* Parameters:  src(I)  - pointer to the source address                     */
4166/*              dst(I)  - destination address                               */
4167/*              size(I) - number of bytes to copy                           */
4168/*                                                                          */
4169/* Copy a block of data in from user space, given a pointer to the pointer  */
4170/* to start copying from (src) and a pointer to where to store it (dst).    */
4171/* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4172/* ------------------------------------------------------------------------ */
4173int
4174copyinptr(softc, src, dst, size)
4175	ipf_main_softc_t *softc;
4176	void *src, *dst;
4177	size_t size;
4178{
4179	caddr_t ca;
4180	int error;
4181
4182# if SOLARIS
4183	error = COPYIN(src, &ca, sizeof(ca));
4184	if (error != 0)
4185		return error;
4186# else
4187	bcopy(src, (caddr_t)&ca, sizeof(ca));
4188# endif
4189	error = COPYIN(ca, dst, size);
4190	if (error != 0) {
4191		IPFERROR(3);
4192		error = EFAULT;
4193	}
4194	return error;
4195}
4196
4197
4198/* ------------------------------------------------------------------------ */
4199/* Function:    copyoutptr                                                  */
4200/* Returns:     int - 0 = success, else failure                             */
4201/* Parameters:  src(I)  - pointer to the source address                     */
4202/*              dst(I)  - destination address                               */
4203/*              size(I) - number of bytes to copy                           */
4204/*                                                                          */
4205/* Copy a block of data out to user space, given a pointer to the pointer   */
4206/* to start copying from (src) and a pointer to where to store it (dst).    */
4207/* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4208/* ------------------------------------------------------------------------ */
4209int
4210copyoutptr(softc, src, dst, size)
4211	ipf_main_softc_t *softc;
4212	void *src, *dst;
4213	size_t size;
4214{
4215	caddr_t ca;
4216	int error;
4217
4218	bcopy(dst, (caddr_t)&ca, sizeof(ca));
4219	error = COPYOUT(src, ca, size);
4220	if (error != 0) {
4221		IPFERROR(4);
4222		error = EFAULT;
4223	}
4224	return error;
4225}
4226
4227
4228/* ------------------------------------------------------------------------ */
4229/* Function:    ipf_lock                                                    */
4230/* Returns:     int      - 0 = success, else error                          */
4231/* Parameters:  data(I)  - pointer to lock value to set                     */
4232/*              lockp(O) - pointer to location to store old lock value      */
4233/*                                                                          */
4234/* Get the new value for the lock integer, set it and return the old value  */
4235/* in *lockp.                                                               */
4236/* ------------------------------------------------------------------------ */
4237int
4238ipf_lock(data, lockp)
4239	caddr_t data;
4240	int *lockp;
4241{
4242	int arg, err;
4243
4244	err = BCOPYIN(data, &arg, sizeof(arg));
4245	if (err != 0)
4246		return EFAULT;
4247	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4248	if (err != 0)
4249		return EFAULT;
4250	*lockp = arg;
4251	return 0;
4252}
4253
4254
4255/* ------------------------------------------------------------------------ */
4256/* Function:    ipf_getstat                                                 */
4257/* Returns:     Nil                                                         */
4258/* Parameters:  softc(I) - pointer to soft context main structure           */
4259/*              fiop(I)  - pointer to ipfilter stats structure              */
4260/*              rev(I)   - version claim by program doing ioctl             */
4261/*                                                                          */
4262/* Stores a copy of current pointers, counters, etc, in the friostat        */
4263/* structure.                                                               */
4264/* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4265/* program is looking for. This ensure that validation of the version it    */
4266/* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4267/* allow older binaries to work but kernels without it will not.            */
4268/* ------------------------------------------------------------------------ */
4269/*ARGSUSED*/
4270static void
4271ipf_getstat(softc, fiop, rev)
4272	ipf_main_softc_t *softc;
4273	friostat_t *fiop;
4274	int rev;
4275{
4276	int i;
4277
4278	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4279	      sizeof(ipf_statistics_t) * 2);
4280	fiop->f_locks[IPL_LOGSTATE] = -1;
4281	fiop->f_locks[IPL_LOGNAT] = -1;
4282	fiop->f_locks[IPL_LOGIPF] = -1;
4283	fiop->f_locks[IPL_LOGAUTH] = -1;
4284
4285	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4286	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4287	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4288	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4289	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4290	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4291	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4292	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4293
4294	fiop->f_ticks = softc->ipf_ticks;
4295	fiop->f_active = softc->ipf_active;
4296	fiop->f_froute[0] = softc->ipf_frouteok[0];
4297	fiop->f_froute[1] = softc->ipf_frouteok[1];
4298	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4299	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4300
4301	fiop->f_running = softc->ipf_running;
4302	for (i = 0; i < IPL_LOGSIZE; i++) {
4303		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4304		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4305	}
4306#ifdef  IPFILTER_LOG
4307	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4308	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4309	fiop->f_logging = 1;
4310#else
4311	fiop->f_log_ok = 0;
4312	fiop->f_log_fail = 0;
4313	fiop->f_logging = 0;
4314#endif
4315	fiop->f_defpass = softc->ipf_pass;
4316	fiop->f_features = ipf_features;
4317
4318#ifdef IPFILTER_COMPAT
4319	sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4320		(rev / 1000000) % 100,
4321		(rev / 10000) % 100,
4322		(rev / 100) % 100);
4323#else
4324	rev = rev;
4325	(void) strncpy(fiop->f_version, ipfilter_version,
4326		       sizeof(fiop->f_version));
4327#endif
4328}
4329
4330
4331#ifdef	USE_INET6
4332int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4333	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4334	-1,			/* 1: UNUSED */
4335	-1,			/* 2: UNUSED */
4336	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4337	-1,			/* 4: ICMP_SOURCEQUENCH */
4338	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4339	-1,			/* 6: UNUSED */
4340	-1,			/* 7: UNUSED */
4341	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4342	-1,			/* 9: UNUSED */
4343	-1,			/* 10: UNUSED */
4344	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4345	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4346	-1,			/* 13: ICMP_TSTAMP */
4347	-1,			/* 14: ICMP_TSTAMPREPLY */
4348	-1,			/* 15: ICMP_IREQ */
4349	-1,			/* 16: ICMP_IREQREPLY */
4350	-1,			/* 17: ICMP_MASKREQ */
4351	-1,			/* 18: ICMP_MASKREPLY */
4352};
4353
4354
4355int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4356	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4357	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4358	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4359	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4360	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4361	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4362	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4363	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4364	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4365	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4366	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4367	-1,				/* 11: ICMP_UNREACH_TOSNET */
4368	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4369	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4370};
4371int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4372#endif
4373
4374int	icmpreplytype4[ICMP_MAXTYPE + 1];
4375
4376
4377/* ------------------------------------------------------------------------ */
4378/* Function:    ipf_matchicmpqueryreply                                     */
4379/* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4380/* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4381/*              ic(I)   - ICMP information                                  */
4382/*              icmp(I) - ICMP packet header                                */
4383/*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4384/*                                                                          */
4385/* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4386/* reply to one as described by what's in ic.  If it is a match, return 1,  */
4387/* else return 0 for no match.                                              */
4388/* ------------------------------------------------------------------------ */
4389int
4390ipf_matchicmpqueryreply(v, ic, icmp, rev)
4391	int v;
4392	icmpinfo_t *ic;
4393	icmphdr_t *icmp;
4394	int rev;
4395{
4396	int ictype;
4397
4398	ictype = ic->ici_type;
4399
4400	if (v == 4) {
4401		/*
4402		 * If we matched its type on the way in, then when going out
4403		 * it will still be the same type.
4404		 */
4405		if ((!rev && (icmp->icmp_type == ictype)) ||
4406		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4407			if (icmp->icmp_type != ICMP_ECHOREPLY)
4408				return 1;
4409			if (icmp->icmp_id == ic->ici_id)
4410				return 1;
4411		}
4412	}
4413#ifdef	USE_INET6
4414	else if (v == 6) {
4415		if ((!rev && (icmp->icmp_type == ictype)) ||
4416		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4417			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4418				return 1;
4419			if (icmp->icmp_id == ic->ici_id)
4420				return 1;
4421		}
4422	}
4423#endif
4424	return 0;
4425}
4426
4427
4428/* ------------------------------------------------------------------------ */
4429/* Function:    ipf_rule_compare                                            */
4430/* Parameters:  fr1(I) - first rule structure to compare                    */
4431/*              fr2(I) - second rule structure to compare                   */
4432/* Returns:     int    - 0 == rules are the same, else mismatch             */
4433/*                                                                          */
4434/* Compare two rules and return 0 if they match or a number indicating      */
4435/* which of the individual checks failed.                                   */
4436/* ------------------------------------------------------------------------ */
4437static int
4438ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4439{
4440	if (fr1->fr_cksum != fr2->fr_cksum)
4441		return 1;
4442	if (fr1->fr_size != fr2->fr_size)
4443		return 2;
4444	if (fr1->fr_dsize != fr2->fr_dsize)
4445		return 3;
4446	if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4447		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4448		return 4;
4449	if (fr1->fr_data && !fr2->fr_data)
4450		return 5;
4451	if (!fr1->fr_data && fr2->fr_data)
4452		return 6;
4453	if (fr1->fr_data) {
4454		if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4455			return 7;
4456	}
4457	return 0;
4458}
4459
4460
4461/* ------------------------------------------------------------------------ */
4462/* Function:    frrequest                                                   */
4463/* Returns:     int - 0 == success, > 0 == errno value                      */
4464/* Parameters:  unit(I)     - device for which this is for                  */
4465/*              req(I)      - ioctl command (SIOC*)                         */
4466/*              data(I)     - pointr to ioctl data                          */
4467/*              set(I)      - 1 or 0 (filter set)                           */
4468/*              makecopy(I) - flag indicating whether data points to a rule */
4469/*                            in kernel space & hence doesn't need copying. */
4470/*                                                                          */
4471/* This function handles all the requests which operate on the list of      */
4472/* filter rules.  This includes adding, deleting, insertion.  It is also    */
4473/* responsible for creating groups when a "head" rule is loaded.  Interface */
4474/* names are resolved here and other sanity checks are made on the content  */
4475/* of the rule structure being loaded.  If a rule has user defined timeouts */
4476/* then make sure they are created and initialised before exiting.          */
4477/* ------------------------------------------------------------------------ */
4478int
4479frrequest(softc, unit, req, data, set, makecopy)
4480	ipf_main_softc_t *softc;
4481	int unit;
4482	ioctlcmd_t req;
4483	int set, makecopy;
4484	caddr_t data;
4485{
4486	int error = 0, in, family, addrem, need_free = 0;
4487	frentry_t frd, *fp, *f, **fprev, **ftail;
4488	void *ptr, *uptr, *cptr;
4489	u_int *p, *pp;
4490	frgroup_t *fg;
4491	char *group;
4492
4493	ptr = NULL;
4494	cptr = NULL;
4495	fg = NULL;
4496	fp = &frd;
4497	if (makecopy != 0) {
4498		bzero(fp, sizeof(frd));
4499		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4500		if (error) {
4501			return error;
4502		}
4503		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4504			IPFERROR(6);
4505			return EINVAL;
4506		}
4507		KMALLOCS(f, frentry_t *, fp->fr_size);
4508		if (f == NULL) {
4509			IPFERROR(131);
4510			return ENOMEM;
4511		}
4512		bzero(f, fp->fr_size);
4513		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4514				    fp->fr_size);
4515		if (error) {
4516			KFREES(f, fp->fr_size);
4517			return error;
4518		}
4519
4520		fp = f;
4521		f = NULL;
4522		fp->fr_next = NULL;
4523		fp->fr_dnext = NULL;
4524		fp->fr_pnext = NULL;
4525		fp->fr_pdnext = NULL;
4526		fp->fr_grp = NULL;
4527		fp->fr_grphead = NULL;
4528		fp->fr_icmpgrp = NULL;
4529		fp->fr_isc = (void *)-1;
4530		fp->fr_ptr = NULL;
4531		fp->fr_ref = 0;
4532		fp->fr_flags |= FR_COPIED;
4533	} else {
4534		fp = (frentry_t *)data;
4535		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4536			IPFERROR(7);
4537			return EINVAL;
4538		}
4539		fp->fr_flags &= ~FR_COPIED;
4540	}
4541
4542	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4543	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4544		IPFERROR(8);
4545		error = EINVAL;
4546		goto donenolock;
4547	}
4548
4549	family = fp->fr_family;
4550	uptr = fp->fr_data;
4551
4552	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4553	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4554		addrem = 0;
4555	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4556		addrem = 1;
4557	else if (req == (ioctlcmd_t)SIOCZRLST)
4558		addrem = 2;
4559	else {
4560		IPFERROR(9);
4561		error = EINVAL;
4562		goto donenolock;
4563	}
4564
4565	/*
4566	 * Only filter rules for IPv4 or IPv6 are accepted.
4567	 */
4568	if (family == AF_INET) {
4569		/*EMPTY*/;
4570#ifdef	USE_INET6
4571	} else if (family == AF_INET6) {
4572		/*EMPTY*/;
4573#endif
4574	} else if (family != 0) {
4575		IPFERROR(10);
4576		error = EINVAL;
4577		goto donenolock;
4578	}
4579
4580	/*
4581	 * If the rule is being loaded from user space, i.e. we had to copy it
4582	 * into kernel space, then do not trust the function pointer in the
4583	 * rule.
4584	 */
4585	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4586		if (ipf_findfunc(fp->fr_func) == NULL) {
4587			IPFERROR(11);
4588			error = ESRCH;
4589			goto donenolock;
4590		}
4591
4592		if (addrem == 0) {
4593			error = ipf_funcinit(softc, fp);
4594			if (error != 0)
4595				goto donenolock;
4596		}
4597	}
4598	if ((fp->fr_flags & FR_CALLNOW) &&
4599	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4600		IPFERROR(142);
4601		error = ESRCH;
4602		goto donenolock;
4603	}
4604	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4605	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4606		IPFERROR(143);
4607		error = ESRCH;
4608		goto donenolock;
4609	}
4610
4611	ptr = NULL;
4612	cptr = NULL;
4613
4614	if (FR_ISACCOUNT(fp->fr_flags))
4615		unit = IPL_LOGCOUNT;
4616
4617	/*
4618	 * Check that each group name in the rule has a start index that
4619	 * is valid.
4620	 */
4621	if (fp->fr_icmphead != -1) {
4622		if ((fp->fr_icmphead < 0) ||
4623		    (fp->fr_icmphead >= fp->fr_namelen)) {
4624			IPFERROR(136);
4625			error = EINVAL;
4626			goto donenolock;
4627		}
4628		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4629			fp->fr_names[fp->fr_icmphead] = '\0';
4630	}
4631
4632	if (fp->fr_grhead != -1) {
4633		if ((fp->fr_grhead < 0) ||
4634		    (fp->fr_grhead >= fp->fr_namelen)) {
4635			IPFERROR(137);
4636			error = EINVAL;
4637			goto donenolock;
4638		}
4639		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4640			fp->fr_names[fp->fr_grhead] = '\0';
4641	}
4642
4643	if (fp->fr_group != -1) {
4644		if ((fp->fr_group < 0) ||
4645		    (fp->fr_group >= fp->fr_namelen)) {
4646			IPFERROR(138);
4647			error = EINVAL;
4648			goto donenolock;
4649		}
4650		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4651			/*
4652			 * Allow loading rules that are in groups to cause
4653			 * them to be created if they don't already exit.
4654			 */
4655			group = FR_NAME(fp, fr_group);
4656			if (addrem == 0) {
4657				fg = ipf_group_add(softc, group, NULL,
4658						   fp->fr_flags, unit, set);
4659				fp->fr_grp = fg;
4660			} else {
4661				fg = ipf_findgroup(softc, group, unit,
4662						   set, NULL);
4663				if (fg == NULL) {
4664					IPFERROR(12);
4665					error = ESRCH;
4666					goto donenolock;
4667				}
4668			}
4669
4670			if (fg->fg_flags == 0) {
4671				fg->fg_flags = fp->fr_flags & FR_INOUT;
4672			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4673				IPFERROR(13);
4674				error = ESRCH;
4675				goto donenolock;
4676			}
4677		}
4678	} else {
4679		/*
4680		 * If a rule is going to be part of a group then it does
4681		 * not matter whether it is an in or out rule, but if it
4682		 * isn't in a group, then it does...
4683		 */
4684		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4685			IPFERROR(14);
4686			error = EINVAL;
4687			goto donenolock;
4688		}
4689	}
4690	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4691
4692	/*
4693	 * Work out which rule list this change is being applied to.
4694	 */
4695	ftail = NULL;
4696	fprev = NULL;
4697	if (unit == IPL_LOGAUTH) {
4698                if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4699		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4700		    (fp->fr_dif.fd_ptr != NULL) ||
4701		    (fp->fr_flags & FR_FASTROUTE)) {
4702			softc->ipf_interror = 145;
4703			error = EINVAL;
4704			goto donenolock;
4705		}
4706		fprev = ipf_auth_rulehead(softc);
4707	} else {
4708		if (FR_ISACCOUNT(fp->fr_flags))
4709			fprev = &softc->ipf_acct[in][set];
4710		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4711			fprev = &softc->ipf_rules[in][set];
4712	}
4713	if (fprev == NULL) {
4714		IPFERROR(15);
4715		error = ESRCH;
4716		goto donenolock;
4717	}
4718
4719	if (fg != NULL)
4720		fprev = &fg->fg_start;
4721
4722	/*
4723	 * Copy in extra data for the rule.
4724	 */
4725	if (fp->fr_dsize != 0) {
4726		if (makecopy != 0) {
4727			KMALLOCS(ptr, void *, fp->fr_dsize);
4728			if (ptr == NULL) {
4729				IPFERROR(16);
4730				error = ENOMEM;
4731				goto donenolock;
4732			}
4733
4734			/*
4735			 * The bcopy case is for when the data is appended
4736			 * to the rule by ipf_in_compat().
4737			 */
4738			if (uptr >= (void *)fp &&
4739			    uptr < (void *)((char *)fp + fp->fr_size)) {
4740				bcopy(uptr, ptr, fp->fr_dsize);
4741				error = 0;
4742			} else {
4743				error = COPYIN(uptr, ptr, fp->fr_dsize);
4744				if (error != 0) {
4745					IPFERROR(17);
4746					error = EFAULT;
4747					goto donenolock;
4748				}
4749			}
4750		} else {
4751			ptr = uptr;
4752		}
4753		fp->fr_data = ptr;
4754	} else {
4755		fp->fr_data = NULL;
4756	}
4757
4758	/*
4759	 * Perform per-rule type sanity checks of their members.
4760	 * All code after this needs to be aware that allocated memory
4761	 * may need to be free'd before exiting.
4762	 */
4763	switch (fp->fr_type & ~FR_T_BUILTIN)
4764	{
4765#if defined(IPFILTER_BPF)
4766	case FR_T_BPFOPC :
4767		if (fp->fr_dsize == 0) {
4768			IPFERROR(19);
4769			error = EINVAL;
4770			break;
4771		}
4772		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4773			IPFERROR(20);
4774			error = EINVAL;
4775			break;
4776		}
4777		break;
4778#endif
4779	case FR_T_IPF :
4780		/*
4781		 * Preparation for error case at the bottom of this function.
4782		 */
4783		if (fp->fr_datype == FRI_LOOKUP)
4784			fp->fr_dstptr = NULL;
4785		if (fp->fr_satype == FRI_LOOKUP)
4786			fp->fr_srcptr = NULL;
4787
4788		if (fp->fr_dsize != sizeof(fripf_t)) {
4789			IPFERROR(21);
4790			error = EINVAL;
4791			break;
4792		}
4793
4794		/*
4795		 * Allowing a rule with both "keep state" and "with oow" is
4796		 * pointless because adding a state entry to the table will
4797		 * fail with the out of window (oow) flag set.
4798		 */
4799		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4800			IPFERROR(22);
4801			error = EINVAL;
4802			break;
4803		}
4804
4805		switch (fp->fr_satype)
4806		{
4807		case FRI_BROADCAST :
4808		case FRI_DYNAMIC :
4809		case FRI_NETWORK :
4810		case FRI_NETMASKED :
4811		case FRI_PEERADDR :
4812			if (fp->fr_sifpidx < 0) {
4813				IPFERROR(23);
4814				error = EINVAL;
4815			}
4816			break;
4817		case FRI_LOOKUP :
4818			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4819						       &fp->fr_src6,
4820						       &fp->fr_smsk6);
4821			if (fp->fr_srcfunc == NULL) {
4822				IPFERROR(132);
4823				error = ESRCH;
4824				break;
4825			}
4826			break;
4827		case FRI_NORMAL :
4828			break;
4829		default :
4830			IPFERROR(133);
4831			error = EINVAL;
4832			break;
4833		}
4834		if (error != 0)
4835			break;
4836
4837		switch (fp->fr_datype)
4838		{
4839		case FRI_BROADCAST :
4840		case FRI_DYNAMIC :
4841		case FRI_NETWORK :
4842		case FRI_NETMASKED :
4843		case FRI_PEERADDR :
4844			if (fp->fr_difpidx < 0) {
4845				IPFERROR(24);
4846				error = EINVAL;
4847			}
4848			break;
4849		case FRI_LOOKUP :
4850			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4851						       &fp->fr_dst6,
4852						       &fp->fr_dmsk6);
4853			if (fp->fr_dstfunc == NULL) {
4854				IPFERROR(134);
4855				error = ESRCH;
4856			}
4857			break;
4858		case FRI_NORMAL :
4859			break;
4860		default :
4861			IPFERROR(135);
4862			error = EINVAL;
4863		}
4864		break;
4865
4866	case FR_T_NONE :
4867	case FR_T_CALLFUNC :
4868	case FR_T_COMPIPF :
4869		break;
4870
4871	case FR_T_IPFEXPR :
4872		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4873			IPFERROR(25);
4874			error = EINVAL;
4875		}
4876		break;
4877
4878	default :
4879		IPFERROR(26);
4880		error = EINVAL;
4881		break;
4882	}
4883	if (error != 0)
4884		goto donenolock;
4885
4886	if (fp->fr_tif.fd_name != -1) {
4887		if ((fp->fr_tif.fd_name < 0) ||
4888		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4889			IPFERROR(139);
4890			error = EINVAL;
4891			goto donenolock;
4892		}
4893	}
4894
4895	if (fp->fr_dif.fd_name != -1) {
4896		if ((fp->fr_dif.fd_name < 0) ||
4897		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4898			IPFERROR(140);
4899			error = EINVAL;
4900			goto donenolock;
4901		}
4902	}
4903
4904	if (fp->fr_rif.fd_name != -1) {
4905		if ((fp->fr_rif.fd_name < 0) ||
4906		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4907			IPFERROR(141);
4908			error = EINVAL;
4909			goto donenolock;
4910		}
4911	}
4912
4913	/*
4914	 * Lookup all the interface names that are part of the rule.
4915	 */
4916	error = ipf_synclist(softc, fp, NULL);
4917	if (error != 0)
4918		goto donenolock;
4919	fp->fr_statecnt = 0;
4920	if (fp->fr_srctrack.ht_max_nodes != 0)
4921		ipf_rb_ht_init(&fp->fr_srctrack);
4922
4923	/*
4924	 * Look for an existing matching filter rule, but don't include the
4925	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4926	 * This elminates rules which are indentical being loaded.  Checksum
4927	 * the constant part of the filter rule to make comparisons quicker
4928	 * (this meaning no pointers are included).
4929	 */
4930	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4931	     p < pp; p++)
4932		fp->fr_cksum += *p;
4933	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4934	for (p = (u_int *)fp->fr_data; p < pp; p++)
4935		fp->fr_cksum += *p;
4936
4937	WRITE_ENTER(&softc->ipf_mutex);
4938
4939	/*
4940	 * Now that the filter rule lists are locked, we can walk the
4941	 * chain of them without fear.
4942	 */
4943	ftail = fprev;
4944	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4945		if (fp->fr_collect <= f->fr_collect) {
4946			ftail = fprev;
4947			f = NULL;
4948			break;
4949		}
4950		fprev = ftail;
4951	}
4952
4953	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4954		if (ipf_rule_compare(fp, f) == 0)
4955			break;
4956	}
4957
4958	/*
4959	 * If zero'ing statistics, copy current to caller and zero.
4960	 */
4961	if (addrem == 2) {
4962		if (f == NULL) {
4963			IPFERROR(27);
4964			error = ESRCH;
4965		} else {
4966			/*
4967			 * Copy and reduce lock because of impending copyout.
4968			 * Well we should, but if we do then the atomicity of
4969			 * this call and the correctness of fr_hits and
4970			 * fr_bytes cannot be guaranteed.  As it is, this code
4971			 * only resets them to 0 if they are successfully
4972			 * copied out into user space.
4973			 */
4974			bcopy((char *)f, (char *)fp, f->fr_size);
4975			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4976
4977			/*
4978			 * When we copy this rule back out, set the data
4979			 * pointer to be what it was in user space.
4980			 */
4981			fp->fr_data = uptr;
4982			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4983
4984			if (error == 0) {
4985				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4986					error = COPYOUT(f->fr_data, uptr,
4987							f->fr_dsize);
4988					if (error == 0) {
4989						f->fr_hits = 0;
4990						f->fr_bytes = 0;
4991					} else {
4992						IPFERROR(28);
4993						error = EFAULT;
4994					}
4995				}
4996			}
4997		}
4998
4999		if (makecopy != 0) {
5000			if (ptr != NULL) {
5001				KFREES(ptr, fp->fr_dsize);
5002			}
5003			KFREES(fp, fp->fr_size);
5004		}
5005		RWLOCK_EXIT(&softc->ipf_mutex);
5006		return error;
5007	}
5008
5009  	if (!f) {
5010		/*
5011		 * At the end of this, ftail must point to the place where the
5012		 * new rule is to be saved/inserted/added.
5013		 * For SIOCAD*FR, this should be the last rule in the group of
5014		 * rules that have equal fr_collect fields.
5015		 * For SIOCIN*FR, ...
5016		 */
5017		if (req == (ioctlcmd_t)SIOCADAFR ||
5018		    req == (ioctlcmd_t)SIOCADIFR) {
5019
5020			for (ftail = fprev; (f = *ftail) != NULL; ) {
5021				if (f->fr_collect > fp->fr_collect)
5022					break;
5023				ftail = &f->fr_next;
5024				fprev = ftail;
5025			}
5026			ftail = fprev;
5027			f = NULL;
5028			ptr = NULL;
5029		} else if (req == (ioctlcmd_t)SIOCINAFR ||
5030			   req == (ioctlcmd_t)SIOCINIFR) {
5031			while ((f = *fprev) != NULL) {
5032				if (f->fr_collect >= fp->fr_collect)
5033					break;
5034				fprev = &f->fr_next;
5035			}
5036  			ftail = fprev;
5037  			if (fp->fr_hits != 0) {
5038				while (fp->fr_hits && (f = *ftail)) {
5039					if (f->fr_collect != fp->fr_collect)
5040						break;
5041					fprev = ftail;
5042  					ftail = &f->fr_next;
5043					fp->fr_hits--;
5044				}
5045  			}
5046  			f = NULL;
5047  			ptr = NULL;
5048		}
5049	}
5050
5051	/*
5052	 * Request to remove a rule.
5053	 */
5054	if (addrem == 1) {
5055		if (!f) {
5056			IPFERROR(29);
5057			error = ESRCH;
5058		} else {
5059			/*
5060			 * Do not allow activity from user space to interfere
5061			 * with rules not loaded that way.
5062			 */
5063			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5064				IPFERROR(30);
5065				error = EPERM;
5066				goto done;
5067			}
5068
5069			/*
5070			 * Return EBUSY if the rule is being reference by
5071			 * something else (eg state information.)
5072			 */
5073			if (f->fr_ref > 1) {
5074				IPFERROR(31);
5075				error = EBUSY;
5076				goto done;
5077			}
5078#ifdef	IPFILTER_SCAN
5079			if (f->fr_isctag != -1 &&
5080			    (f->fr_isc != (struct ipscan *)-1))
5081				ipf_scan_detachfr(f);
5082#endif
5083
5084			if (unit == IPL_LOGAUTH) {
5085				error = ipf_auth_precmd(softc, req, f, ftail);
5086				goto done;
5087			}
5088
5089			ipf_rule_delete(softc, f, unit, set);
5090
5091			need_free = makecopy;
5092		}
5093	} else {
5094		/*
5095		 * Not removing, so we must be adding/inserting a rule.
5096		 */
5097		if (f != NULL) {
5098			IPFERROR(32);
5099			error = EEXIST;
5100			goto done;
5101		}
5102		if (unit == IPL_LOGAUTH) {
5103			error = ipf_auth_precmd(softc, req, fp, ftail);
5104			goto done;
5105		}
5106
5107		MUTEX_NUKE(&fp->fr_lock);
5108		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5109		if (fp->fr_die != 0)
5110			ipf_rule_expire_insert(softc, fp, set);
5111
5112		fp->fr_hits = 0;
5113		if (makecopy != 0)
5114			fp->fr_ref = 1;
5115		fp->fr_pnext = ftail;
5116		fp->fr_next = *ftail;
5117		if (fp->fr_next != NULL)
5118			fp->fr_next->fr_pnext = &fp->fr_next;
5119		*ftail = fp;
5120		if (addrem == 0)
5121			ipf_fixskip(ftail, fp, 1);
5122
5123		fp->fr_icmpgrp = NULL;
5124		if (fp->fr_icmphead != -1) {
5125			group = FR_NAME(fp, fr_icmphead);
5126			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5127			fp->fr_icmpgrp = fg;
5128		}
5129
5130		fp->fr_grphead = NULL;
5131		if (fp->fr_grhead != -1) {
5132			group = FR_NAME(fp, fr_grhead);
5133			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5134					   unit, set);
5135			fp->fr_grphead = fg;
5136		}
5137	}
5138done:
5139	RWLOCK_EXIT(&softc->ipf_mutex);
5140donenolock:
5141	if (need_free || (error != 0)) {
5142		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5143			if ((fp->fr_satype == FRI_LOOKUP) &&
5144			    (fp->fr_srcptr != NULL))
5145				ipf_lookup_deref(softc, fp->fr_srctype,
5146						 fp->fr_srcptr);
5147			if ((fp->fr_datype == FRI_LOOKUP) &&
5148			    (fp->fr_dstptr != NULL))
5149				ipf_lookup_deref(softc, fp->fr_dsttype,
5150						 fp->fr_dstptr);
5151		}
5152		if (fp->fr_grp != NULL) {
5153			WRITE_ENTER(&softc->ipf_mutex);
5154			ipf_group_del(softc, fp->fr_grp, fp);
5155			RWLOCK_EXIT(&softc->ipf_mutex);
5156		}
5157		if ((ptr != NULL) && (makecopy != 0)) {
5158			KFREES(ptr, fp->fr_dsize);
5159		}
5160		KFREES(fp, fp->fr_size);
5161	}
5162	return (error);
5163}
5164
5165
5166/* ------------------------------------------------------------------------ */
5167/* Function:   ipf_rule_delete                                              */
5168/* Returns:    Nil                                                          */
5169/* Parameters: softc(I) - pointer to soft context main structure            */
5170/*             f(I)     - pointer to the rule being deleted                 */
5171/*             ftail(I) - pointer to the pointer to f                       */
5172/*             unit(I)  - device for which this is for                      */
5173/*             set(I)   - 1 or 0 (filter set)                               */
5174/*                                                                          */
5175/* This function attempts to do what it can to delete a filter rule: remove */
5176/* it from any linked lists and remove any groups it is responsible for.    */
5177/* But in the end, removing a rule can only drop the reference count - we   */
5178/* must use that as the guide for whether or not it can be freed.           */
5179/* ------------------------------------------------------------------------ */
5180static void
5181ipf_rule_delete(softc, f, unit, set)
5182	ipf_main_softc_t *softc;
5183	frentry_t *f;
5184	int unit, set;
5185{
5186
5187	/*
5188	 * If fr_pdnext is set, then the rule is on the expire list, so
5189	 * remove it from there.
5190	 */
5191	if (f->fr_pdnext != NULL) {
5192		*f->fr_pdnext = f->fr_dnext;
5193		if (f->fr_dnext != NULL)
5194			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5195		f->fr_pdnext = NULL;
5196		f->fr_dnext = NULL;
5197	}
5198
5199	ipf_fixskip(f->fr_pnext, f, -1);
5200	if (f->fr_pnext != NULL)
5201		*f->fr_pnext = f->fr_next;
5202	if (f->fr_next != NULL)
5203		f->fr_next->fr_pnext = f->fr_pnext;
5204	f->fr_pnext = NULL;
5205	f->fr_next = NULL;
5206
5207	(void) ipf_derefrule(softc, &f);
5208}
5209
5210/* ------------------------------------------------------------------------ */
5211/* Function:   ipf_rule_expire_insert                                       */
5212/* Returns:    Nil                                                          */
5213/* Parameters: softc(I) - pointer to soft context main structure            */
5214/*             f(I)     - pointer to rule to be added to expire list        */
5215/*             set(I)   - 1 or 0 (filter set)                               */
5216/*                                                                          */
5217/* If the new rule has a given expiration time, insert it into the list of  */
5218/* expiring rules with the ones to be removed first added to the front of   */
5219/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5220/* expiration interval checks.                                              */
5221/* ------------------------------------------------------------------------ */
5222static void
5223ipf_rule_expire_insert(softc, f, set)
5224	ipf_main_softc_t *softc;
5225	frentry_t *f;
5226	int set;
5227{
5228	frentry_t *fr;
5229
5230	/*
5231	 */
5232
5233	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5234	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5235	     fr = fr->fr_dnext) {
5236		if (f->fr_die < fr->fr_die)
5237			break;
5238		if (fr->fr_dnext == NULL) {
5239			/*
5240			 * We've got to the last rule and everything
5241			 * wanted to be expired before this new node,
5242			 * so we have to tack it on the end...
5243			 */
5244			fr->fr_dnext = f;
5245			f->fr_pdnext = &fr->fr_dnext;
5246			fr = NULL;
5247			break;
5248		}
5249	}
5250
5251	if (softc->ipf_rule_explist[set] == NULL) {
5252		softc->ipf_rule_explist[set] = f;
5253		f->fr_pdnext = &softc->ipf_rule_explist[set];
5254	} else if (fr != NULL) {
5255		f->fr_dnext = fr;
5256		f->fr_pdnext = fr->fr_pdnext;
5257		fr->fr_pdnext = &f->fr_dnext;
5258	}
5259}
5260
5261
5262/* ------------------------------------------------------------------------ */
5263/* Function:   ipf_findlookup                                               */
5264/* Returns:    NULL = failure, else success                                 */
5265/* Parameters: softc(I) - pointer to soft context main structure            */
5266/*             unit(I)  - ipf device we want to find match for              */
5267/*             fp(I)    - rule for which lookup is for                      */
5268/*             addrp(I) - pointer to lookup information in address struct   */
5269/*             maskp(O) - pointer to lookup information for storage         */
5270/*                                                                          */
5271/* When using pools and hash tables to store addresses for matching in      */
5272/* rules, it is necessary to resolve both the object referred to by the     */
5273/* name or address (and return that pointer) and also provide the means by  */
5274/* which to determine if an address belongs to that object to make the      */
5275/* packet matching quicker.                                                 */
5276/* ------------------------------------------------------------------------ */
5277static void *
5278ipf_findlookup(softc, unit, fr, addrp, maskp)
5279	ipf_main_softc_t *softc;
5280	int unit;
5281	frentry_t *fr;
5282	i6addr_t *addrp, *maskp;
5283{
5284	void *ptr = NULL;
5285
5286	switch (addrp->iplookupsubtype)
5287	{
5288	case 0 :
5289		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5290					 addrp->iplookupnum,
5291					 &maskp->iplookupfunc);
5292		break;
5293	case 1 :
5294		if (addrp->iplookupname < 0)
5295			break;
5296		if (addrp->iplookupname >= fr->fr_namelen)
5297			break;
5298		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5299					  fr->fr_names + addrp->iplookupname,
5300					  &maskp->iplookupfunc);
5301		break;
5302	default :
5303		break;
5304	}
5305
5306	return ptr;
5307}
5308
5309
5310/* ------------------------------------------------------------------------ */
5311/* Function:    ipf_funcinit                                                */
5312/* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5313/* Parameters:  softc(I) - pointer to soft context main structure           */
5314/*              fr(I)    - pointer to filter rule                           */
5315/*                                                                          */
5316/* If a rule is a call rule, then check if the function it points to needs  */
5317/* an init function to be called now the rule has been loaded.              */
5318/* ------------------------------------------------------------------------ */
5319static int
5320ipf_funcinit(softc, fr)
5321	ipf_main_softc_t *softc;
5322	frentry_t *fr;
5323{
5324	ipfunc_resolve_t *ft;
5325	int err;
5326
5327	IPFERROR(34);
5328	err = ESRCH;
5329
5330	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5331		if (ft->ipfu_addr == fr->fr_func) {
5332			err = 0;
5333			if (ft->ipfu_init != NULL)
5334				err = (*ft->ipfu_init)(softc, fr);
5335			break;
5336		}
5337	return err;
5338}
5339
5340
5341/* ------------------------------------------------------------------------ */
5342/* Function:    ipf_funcfini                                                */
5343/* Returns:     Nil                                                         */
5344/* Parameters:  softc(I) - pointer to soft context main structure           */
5345/*              fr(I)    - pointer to filter rule                           */
5346/*                                                                          */
5347/* For a given filter rule, call the matching "fini" function if the rule   */
5348/* is using a known function that would have resulted in the "init" being   */
5349/* called for ealier.                                                       */
5350/* ------------------------------------------------------------------------ */
5351static void
5352ipf_funcfini(softc, fr)
5353	ipf_main_softc_t *softc;
5354	frentry_t *fr;
5355{
5356	ipfunc_resolve_t *ft;
5357
5358	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5359		if (ft->ipfu_addr == fr->fr_func) {
5360			if (ft->ipfu_fini != NULL)
5361				(void) (*ft->ipfu_fini)(softc, fr);
5362			break;
5363		}
5364}
5365
5366
5367/* ------------------------------------------------------------------------ */
5368/* Function:    ipf_findfunc                                                */
5369/* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5370/* Parameters:  funcptr(I) - function pointer to lookup                     */
5371/*                                                                          */
5372/* Look for a function in the table of known functions.                     */
5373/* ------------------------------------------------------------------------ */
5374static ipfunc_t
5375ipf_findfunc(funcptr)
5376	ipfunc_t funcptr;
5377{
5378	ipfunc_resolve_t *ft;
5379
5380	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5381		if (ft->ipfu_addr == funcptr)
5382			return funcptr;
5383	return NULL;
5384}
5385
5386
5387/* ------------------------------------------------------------------------ */
5388/* Function:    ipf_resolvefunc                                             */
5389/* Returns:     int - 0 == success, else error                              */
5390/* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5391/*                                                                          */
5392/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5393/* This will either be the function name (if the pointer is set) or the     */
5394/* function pointer if the name is set.  When found, fill in the other one  */
5395/* so that the entire, complete, structure can be copied back to user space.*/
5396/* ------------------------------------------------------------------------ */
5397int
5398ipf_resolvefunc(softc, data)
5399	ipf_main_softc_t *softc;
5400	void *data;
5401{
5402	ipfunc_resolve_t res, *ft;
5403	int error;
5404
5405	error = BCOPYIN(data, &res, sizeof(res));
5406	if (error != 0) {
5407		IPFERROR(123);
5408		return EFAULT;
5409	}
5410
5411	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5412		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5413			if (strncmp(res.ipfu_name, ft->ipfu_name,
5414				    sizeof(res.ipfu_name)) == 0) {
5415				res.ipfu_addr = ft->ipfu_addr;
5416				res.ipfu_init = ft->ipfu_init;
5417				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5418					IPFERROR(35);
5419					return EFAULT;
5420				}
5421				return 0;
5422			}
5423	}
5424	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5425		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5426			if (ft->ipfu_addr == res.ipfu_addr) {
5427				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5428					       sizeof(res.ipfu_name));
5429				res.ipfu_init = ft->ipfu_init;
5430				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5431					IPFERROR(36);
5432					return EFAULT;
5433				}
5434				return 0;
5435			}
5436	}
5437	IPFERROR(37);
5438	return ESRCH;
5439}
5440
5441
5442#if !defined(_KERNEL) || SOLARIS
5443/*
5444 * From: NetBSD
5445 * ppsratecheck(): packets (or events) per second limitation.
5446 */
5447int
5448ppsratecheck(lasttime, curpps, maxpps)
5449	struct timeval *lasttime;
5450	int *curpps;
5451	int maxpps;	/* maximum pps allowed */
5452{
5453	struct timeval tv, delta;
5454	int rv;
5455
5456	GETKTIME(&tv);
5457
5458	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5459	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5460	if (delta.tv_usec < 0) {
5461		delta.tv_sec--;
5462		delta.tv_usec += 1000000;
5463	}
5464
5465	/*
5466	 * check for 0,0 is so that the message will be seen at least once.
5467	 * if more than one second have passed since the last update of
5468	 * lasttime, reset the counter.
5469	 *
5470	 * we do increment *curpps even in *curpps < maxpps case, as some may
5471	 * try to use *curpps for stat purposes as well.
5472	 */
5473	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5474	    delta.tv_sec >= 1) {
5475		*lasttime = tv;
5476		*curpps = 0;
5477		rv = 1;
5478	} else if (maxpps < 0)
5479		rv = 1;
5480	else if (*curpps < maxpps)
5481		rv = 1;
5482	else
5483		rv = 0;
5484	*curpps = *curpps + 1;
5485
5486	return (rv);
5487}
5488#endif
5489
5490
5491/* ------------------------------------------------------------------------ */
5492/* Function:    ipf_derefrule                                               */
5493/* Returns:     int   - 0 == rule freed up, else rule not freed             */
5494/* Parameters:  fr(I) - pointer to filter rule                              */
5495/*                                                                          */
5496/* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5497/* free it and any associated storage space being used by it.               */
5498/* ------------------------------------------------------------------------ */
5499int
5500ipf_derefrule(softc, frp)
5501	ipf_main_softc_t *softc;
5502	frentry_t **frp;
5503{
5504	frentry_t *fr;
5505	frdest_t *fdp;
5506
5507	fr = *frp;
5508	*frp = NULL;
5509
5510	MUTEX_ENTER(&fr->fr_lock);
5511	fr->fr_ref--;
5512	if (fr->fr_ref == 0) {
5513		MUTEX_EXIT(&fr->fr_lock);
5514		MUTEX_DESTROY(&fr->fr_lock);
5515
5516		ipf_funcfini(softc, fr);
5517
5518		fdp = &fr->fr_tif;
5519		if (fdp->fd_type == FRD_DSTLIST)
5520			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5521
5522		fdp = &fr->fr_rif;
5523		if (fdp->fd_type == FRD_DSTLIST)
5524			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5525
5526		fdp = &fr->fr_dif;
5527		if (fdp->fd_type == FRD_DSTLIST)
5528			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5529
5530		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5531		    fr->fr_satype == FRI_LOOKUP)
5532			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5533		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5534		    fr->fr_datype == FRI_LOOKUP)
5535			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5536
5537		if (fr->fr_grp != NULL)
5538			ipf_group_del(softc, fr->fr_grp, fr);
5539
5540		if (fr->fr_grphead != NULL)
5541			ipf_group_del(softc, fr->fr_grphead, fr);
5542
5543		if (fr->fr_icmpgrp != NULL)
5544			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5545
5546		if ((fr->fr_flags & FR_COPIED) != 0) {
5547			if (fr->fr_dsize) {
5548				KFREES(fr->fr_data, fr->fr_dsize);
5549			}
5550			KFREES(fr, fr->fr_size);
5551			return 0;
5552		}
5553		return 1;
5554	} else {
5555		MUTEX_EXIT(&fr->fr_lock);
5556	}
5557	return -1;
5558}
5559
5560
5561/* ------------------------------------------------------------------------ */
5562/* Function:    ipf_grpmapinit                                              */
5563/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5564/* Parameters:  fr(I) - pointer to rule to find hash table for              */
5565/*                                                                          */
5566/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5567/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5568/* ------------------------------------------------------------------------ */
5569static int
5570ipf_grpmapinit(softc, fr)
5571	ipf_main_softc_t *softc;
5572	frentry_t *fr;
5573{
5574	char name[FR_GROUPLEN];
5575	iphtable_t *iph;
5576
5577#if defined(SNPRINTF) && defined(_KERNEL)
5578	SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5579#else
5580	(void) sprintf(name, "%d", fr->fr_arg);
5581#endif
5582	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5583	if (iph == NULL) {
5584		IPFERROR(38);
5585		return ESRCH;
5586	}
5587	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5588		IPFERROR(39);
5589		return ESRCH;
5590	}
5591	iph->iph_ref++;
5592	fr->fr_ptr = iph;
5593	return 0;
5594}
5595
5596
5597/* ------------------------------------------------------------------------ */
5598/* Function:    ipf_grpmapfini                                              */
5599/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5600/* Parameters:  softc(I) - pointer to soft context main structure           */
5601/*              fr(I)    - pointer to rule to release hash table for        */
5602/*                                                                          */
5603/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5604/* be called to undo what ipf_grpmapinit caused to be done.                 */
5605/* ------------------------------------------------------------------------ */
5606static int
5607ipf_grpmapfini(softc, fr)
5608	ipf_main_softc_t *softc;
5609	frentry_t *fr;
5610{
5611	iphtable_t *iph;
5612	iph = fr->fr_ptr;
5613	if (iph != NULL)
5614		ipf_lookup_deref(softc, IPLT_HASH, iph);
5615	return 0;
5616}
5617
5618
5619/* ------------------------------------------------------------------------ */
5620/* Function:    ipf_srcgrpmap                                               */
5621/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5622/* Parameters:  fin(I)    - pointer to packet information                   */
5623/*              passp(IO) - pointer to current/new filter decision (unused) */
5624/*                                                                          */
5625/* Look for a rule group head in a hash table, using the source address as  */
5626/* the key, and descend into that group and continue matching rules against */
5627/* the packet.                                                              */
5628/* ------------------------------------------------------------------------ */
5629frentry_t *
5630ipf_srcgrpmap(fin, passp)
5631	fr_info_t *fin;
5632	u_32_t *passp;
5633{
5634	frgroup_t *fg;
5635	void *rval;
5636
5637	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5638				 &fin->fin_src);
5639	if (rval == NULL)
5640		return NULL;
5641
5642	fg = rval;
5643	fin->fin_fr = fg->fg_start;
5644	(void) ipf_scanlist(fin, *passp);
5645	return fin->fin_fr;
5646}
5647
5648
5649/* ------------------------------------------------------------------------ */
5650/* Function:    ipf_dstgrpmap                                               */
5651/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5652/* Parameters:  fin(I)    - pointer to packet information                   */
5653/*              passp(IO) - pointer to current/new filter decision (unused) */
5654/*                                                                          */
5655/* Look for a rule group head in a hash table, using the destination        */
5656/* address as the key, and descend into that group and continue matching    */
5657/* rules against  the packet.                                               */
5658/* ------------------------------------------------------------------------ */
5659frentry_t *
5660ipf_dstgrpmap(fin, passp)
5661	fr_info_t *fin;
5662	u_32_t *passp;
5663{
5664	frgroup_t *fg;
5665	void *rval;
5666
5667	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5668				 &fin->fin_dst);
5669	if (rval == NULL)
5670		return NULL;
5671
5672	fg = rval;
5673	fin->fin_fr = fg->fg_start;
5674	(void) ipf_scanlist(fin, *passp);
5675	return fin->fin_fr;
5676}
5677
5678/*
5679 * Queue functions
5680 * ===============
5681 * These functions manage objects on queues for efficient timeouts.  There
5682 * are a number of system defined queues as well as user defined timeouts.
5683 * It is expected that a lock is held in the domain in which the queue
5684 * belongs (i.e. either state or NAT) when calling any of these functions
5685 * that prevents ipf_freetimeoutqueue() from being called at the same time
5686 * as any other.
5687 */
5688
5689
5690/* ------------------------------------------------------------------------ */
5691/* Function:    ipf_addtimeoutqueue                                         */
5692/* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5693/*                               timeout queue with given interval.         */
5694/* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5695/*                           of interface queues.                           */
5696/*              seconds(I) - timeout value in seconds for this queue.       */
5697/*                                                                          */
5698/* This routine first looks for a timeout queue that matches the interval   */
5699/* being requested.  If it finds one, increments the reference counter and  */
5700/* returns a pointer to it.  If none are found, it allocates a new one and  */
5701/* inserts it at the top of the list.                                       */
5702/*                                                                          */
5703/* Locking.                                                                 */
5704/* It is assumed that the caller of this function has an appropriate lock   */
5705/* held (exclusively) in the domain that encompases 'parent'.               */
5706/* ------------------------------------------------------------------------ */
5707ipftq_t *
5708ipf_addtimeoutqueue(softc, parent, seconds)
5709	ipf_main_softc_t *softc;
5710	ipftq_t **parent;
5711	u_int seconds;
5712{
5713	ipftq_t *ifq;
5714	u_int period;
5715
5716	period = seconds * IPF_HZ_DIVIDE;
5717
5718	MUTEX_ENTER(&softc->ipf_timeoutlock);
5719	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5720		if (ifq->ifq_ttl == period) {
5721			/*
5722			 * Reset the delete flag, if set, so the structure
5723			 * gets reused rather than freed and reallocated.
5724			 */
5725			MUTEX_ENTER(&ifq->ifq_lock);
5726			ifq->ifq_flags &= ~IFQF_DELETE;
5727			ifq->ifq_ref++;
5728			MUTEX_EXIT(&ifq->ifq_lock);
5729			MUTEX_EXIT(&softc->ipf_timeoutlock);
5730
5731			return ifq;
5732		}
5733	}
5734
5735	KMALLOC(ifq, ipftq_t *);
5736	if (ifq != NULL) {
5737		MUTEX_NUKE(&ifq->ifq_lock);
5738		IPFTQ_INIT(ifq, period, "ipftq mutex");
5739		ifq->ifq_next = *parent;
5740		ifq->ifq_pnext = parent;
5741		ifq->ifq_flags = IFQF_USER;
5742		ifq->ifq_ref++;
5743		*parent = ifq;
5744		softc->ipf_userifqs++;
5745	}
5746	MUTEX_EXIT(&softc->ipf_timeoutlock);
5747	return ifq;
5748}
5749
5750
5751/* ------------------------------------------------------------------------ */
5752/* Function:    ipf_deletetimeoutqueue                                      */
5753/* Returns:     int    - new reference count value of the timeout queue     */
5754/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5755/* Locks:       ifq->ifq_lock                                               */
5756/*                                                                          */
5757/* This routine must be called when we're discarding a pointer to a timeout */
5758/* queue object, taking care of the reference counter.                      */
5759/*                                                                          */
5760/* Now that this just sets a DELETE flag, it requires the expire code to    */
5761/* check the list of user defined timeout queues and call the free function */
5762/* below (currently commented out) to stop memory leaking.  It is done this */
5763/* way because the locking may not be sufficient to safely do a free when   */
5764/* this function is called.                                                 */
5765/* ------------------------------------------------------------------------ */
5766int
5767ipf_deletetimeoutqueue(ifq)
5768	ipftq_t *ifq;
5769{
5770
5771	ifq->ifq_ref--;
5772	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5773		ifq->ifq_flags |= IFQF_DELETE;
5774	}
5775
5776	return ifq->ifq_ref;
5777}
5778
5779
5780/* ------------------------------------------------------------------------ */
5781/* Function:    ipf_freetimeoutqueue                                        */
5782/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5783/* Returns:     Nil                                                         */
5784/*                                                                          */
5785/* Locking:                                                                 */
5786/* It is assumed that the caller of this function has an appropriate lock   */
5787/* held (exclusively) in the domain that encompases the callers "domain".   */
5788/* The ifq_lock for this structure should not be held.                      */
5789/*                                                                          */
5790/* Remove a user defined timeout queue from the list of queues it is in and */
5791/* tidy up after this is done.                                              */
5792/* ------------------------------------------------------------------------ */
5793void
5794ipf_freetimeoutqueue(softc, ifq)
5795	ipf_main_softc_t *softc;
5796	ipftq_t *ifq;
5797{
5798
5799	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5800	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5801		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5802		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5803		       ifq->ifq_ref);
5804		return;
5805	}
5806
5807	/*
5808	 * Remove from its position in the list.
5809	 */
5810	*ifq->ifq_pnext = ifq->ifq_next;
5811	if (ifq->ifq_next != NULL)
5812		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5813	ifq->ifq_next = NULL;
5814	ifq->ifq_pnext = NULL;
5815
5816	MUTEX_DESTROY(&ifq->ifq_lock);
5817	ATOMIC_DEC(softc->ipf_userifqs);
5818	KFREE(ifq);
5819}
5820
5821
5822/* ------------------------------------------------------------------------ */
5823/* Function:    ipf_deletequeueentry                                        */
5824/* Returns:     Nil                                                         */
5825/* Parameters:  tqe(I) - timeout queue entry to delete                      */
5826/*                                                                          */
5827/* Remove a tail queue entry from its queue and make it an orphan.          */
5828/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5829/* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5830/* the correct lock(s) may not be held that would make it safe to do so.    */
5831/* ------------------------------------------------------------------------ */
5832void
5833ipf_deletequeueentry(tqe)
5834	ipftqent_t *tqe;
5835{
5836	ipftq_t *ifq;
5837
5838	ifq = tqe->tqe_ifq;
5839
5840	MUTEX_ENTER(&ifq->ifq_lock);
5841
5842	if (tqe->tqe_pnext != NULL) {
5843		*tqe->tqe_pnext = tqe->tqe_next;
5844		if (tqe->tqe_next != NULL)
5845			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5846		else    /* we must be the tail anyway */
5847			ifq->ifq_tail = tqe->tqe_pnext;
5848
5849		tqe->tqe_pnext = NULL;
5850		tqe->tqe_ifq = NULL;
5851	}
5852
5853	(void) ipf_deletetimeoutqueue(ifq);
5854	ASSERT(ifq->ifq_ref > 0);
5855
5856	MUTEX_EXIT(&ifq->ifq_lock);
5857}
5858
5859
5860/* ------------------------------------------------------------------------ */
5861/* Function:    ipf_queuefront                                              */
5862/* Returns:     Nil                                                         */
5863/* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5864/*                                                                          */
5865/* Move a queue entry to the front of the queue, if it isn't already there. */
5866/* ------------------------------------------------------------------------ */
5867void
5868ipf_queuefront(tqe)
5869	ipftqent_t *tqe;
5870{
5871	ipftq_t *ifq;
5872
5873	ifq = tqe->tqe_ifq;
5874	if (ifq == NULL)
5875		return;
5876
5877	MUTEX_ENTER(&ifq->ifq_lock);
5878	if (ifq->ifq_head != tqe) {
5879		*tqe->tqe_pnext = tqe->tqe_next;
5880		if (tqe->tqe_next)
5881			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5882		else
5883			ifq->ifq_tail = tqe->tqe_pnext;
5884
5885		tqe->tqe_next = ifq->ifq_head;
5886		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5887		ifq->ifq_head = tqe;
5888		tqe->tqe_pnext = &ifq->ifq_head;
5889	}
5890	MUTEX_EXIT(&ifq->ifq_lock);
5891}
5892
5893
5894/* ------------------------------------------------------------------------ */
5895/* Function:    ipf_queueback                                               */
5896/* Returns:     Nil                                                         */
5897/* Parameters:  ticks(I) - ipf tick time to use with this call              */
5898/*              tqe(I)   - pointer to timeout queue entry                   */
5899/*                                                                          */
5900/* Move a queue entry to the back of the queue, if it isn't already there.  */
5901/* We use use ticks to calculate the expiration and mark for when we last   */
5902/* touched the structure.                                                   */
5903/* ------------------------------------------------------------------------ */
5904void
5905ipf_queueback(ticks, tqe)
5906	u_long ticks;
5907	ipftqent_t *tqe;
5908{
5909	ipftq_t *ifq;
5910
5911	ifq = tqe->tqe_ifq;
5912	if (ifq == NULL)
5913		return;
5914	tqe->tqe_die = ticks + ifq->ifq_ttl;
5915	tqe->tqe_touched = ticks;
5916
5917	MUTEX_ENTER(&ifq->ifq_lock);
5918	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5919		/*
5920		 * Remove from list
5921		 */
5922		*tqe->tqe_pnext = tqe->tqe_next;
5923		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5924
5925		/*
5926		 * Make it the last entry.
5927		 */
5928		tqe->tqe_next = NULL;
5929		tqe->tqe_pnext = ifq->ifq_tail;
5930		*ifq->ifq_tail = tqe;
5931		ifq->ifq_tail = &tqe->tqe_next;
5932	}
5933	MUTEX_EXIT(&ifq->ifq_lock);
5934}
5935
5936
5937/* ------------------------------------------------------------------------ */
5938/* Function:    ipf_queueappend                                             */
5939/* Returns:     Nil                                                         */
5940/* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5941/*              tqe(I)    - pointer to timeout queue entry                  */
5942/*              ifq(I)    - pointer to timeout queue                        */
5943/*              parent(I) - owing object pointer                            */
5944/*                                                                          */
5945/* Add a new item to this queue and put it on the very end.                 */
5946/* We use use ticks to calculate the expiration and mark for when we last   */
5947/* touched the structure.                                                   */
5948/* ------------------------------------------------------------------------ */
5949void
5950ipf_queueappend(ticks, tqe, ifq, parent)
5951	u_long ticks;
5952	ipftqent_t *tqe;
5953	ipftq_t *ifq;
5954	void *parent;
5955{
5956
5957	MUTEX_ENTER(&ifq->ifq_lock);
5958	tqe->tqe_parent = parent;
5959	tqe->tqe_pnext = ifq->ifq_tail;
5960	*ifq->ifq_tail = tqe;
5961	ifq->ifq_tail = &tqe->tqe_next;
5962	tqe->tqe_next = NULL;
5963	tqe->tqe_ifq = ifq;
5964	tqe->tqe_die = ticks + ifq->ifq_ttl;
5965	tqe->tqe_touched = ticks;
5966	ifq->ifq_ref++;
5967	MUTEX_EXIT(&ifq->ifq_lock);
5968}
5969
5970
5971/* ------------------------------------------------------------------------ */
5972/* Function:    ipf_movequeue                                               */
5973/* Returns:     Nil                                                         */
5974/* Parameters:  tq(I)   - pointer to timeout queue information              */
5975/*              oifp(I) - old timeout queue entry was on                    */
5976/*              nifp(I) - new timeout queue to put entry on                 */
5977/*                                                                          */
5978/* Move a queue entry from one timeout queue to another timeout queue.      */
5979/* If it notices that the current entry is already last and does not need   */
5980/* to move queue, the return.                                               */
5981/* ------------------------------------------------------------------------ */
5982void
5983ipf_movequeue(ticks, tqe, oifq, nifq)
5984	u_long ticks;
5985	ipftqent_t *tqe;
5986	ipftq_t *oifq, *nifq;
5987{
5988
5989	/*
5990	 * If the queue hasn't changed and we last touched this entry at the
5991	 * same ipf time, then we're not going to achieve anything by either
5992	 * changing the ttl or moving it on the queue.
5993	 */
5994	if (oifq == nifq && tqe->tqe_touched == ticks)
5995		return;
5996
5997	/*
5998	 * For any of this to be outside the lock, there is a risk that two
5999	 * packets entering simultaneously, with one changing to a different
6000	 * queue and one not, could end up with things in a bizarre state.
6001	 */
6002	MUTEX_ENTER(&oifq->ifq_lock);
6003
6004	tqe->tqe_touched = ticks;
6005	tqe->tqe_die = ticks + nifq->ifq_ttl;
6006	/*
6007	 * Is the operation here going to be a no-op ?
6008	 */
6009	if (oifq == nifq) {
6010		if ((tqe->tqe_next == NULL) ||
6011		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6012			MUTEX_EXIT(&oifq->ifq_lock);
6013			return;
6014		}
6015	}
6016
6017	/*
6018	 * Remove from the old queue
6019	 */
6020	*tqe->tqe_pnext = tqe->tqe_next;
6021	if (tqe->tqe_next)
6022		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6023	else
6024		oifq->ifq_tail = tqe->tqe_pnext;
6025	tqe->tqe_next = NULL;
6026
6027	/*
6028	 * If we're moving from one queue to another, release the
6029	 * lock on the old queue and get a lock on the new queue.
6030	 * For user defined queues, if we're moving off it, call
6031	 * delete in case it can now be freed.
6032	 */
6033	if (oifq != nifq) {
6034		tqe->tqe_ifq = NULL;
6035
6036		(void) ipf_deletetimeoutqueue(oifq);
6037
6038		MUTEX_EXIT(&oifq->ifq_lock);
6039
6040		MUTEX_ENTER(&nifq->ifq_lock);
6041
6042		tqe->tqe_ifq = nifq;
6043		nifq->ifq_ref++;
6044	}
6045
6046	/*
6047	 * Add to the bottom of the new queue
6048	 */
6049	tqe->tqe_pnext = nifq->ifq_tail;
6050	*nifq->ifq_tail = tqe;
6051	nifq->ifq_tail = &tqe->tqe_next;
6052	MUTEX_EXIT(&nifq->ifq_lock);
6053}
6054
6055
6056/* ------------------------------------------------------------------------ */
6057/* Function:    ipf_updateipid                                              */
6058/* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6059/* Parameters:  fin(I) - pointer to packet information                      */
6060/*                                                                          */
6061/* When we are doing NAT, change the IP of every packet to represent a      */
6062/* single sequence of packets coming from the host, hiding any host         */
6063/* specific sequencing that might otherwise be revealed.  If the packet is  */
6064/* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6065/* the fragment cache for non-leading fragments.  If a non-leading fragment */
6066/* has no match in the cache, return an error.                              */
6067/* ------------------------------------------------------------------------ */
6068static int
6069ipf_updateipid(fin)
6070	fr_info_t *fin;
6071{
6072	u_short id, ido, sums;
6073	u_32_t sumd, sum;
6074	ip_t *ip;
6075
6076	ip = fin->fin_ip;
6077	ido = ntohs(ip->ip_id);
6078	if (fin->fin_off != 0) {
6079		sum = ipf_frag_ipidknown(fin);
6080		if (sum == 0xffffffff)
6081			return -1;
6082		sum &= 0xffff;
6083		id = (u_short)sum;
6084		ip->ip_id = htons(id);
6085	} else {
6086		ip_fillid(ip);
6087		id = ntohs(ip->ip_id);
6088		if ((fin->fin_flx & FI_FRAG) != 0)
6089			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
6090	}
6091
6092	if (id == ido)
6093		return 0;
6094	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
6095	sum = (~ntohs(ip->ip_sum)) & 0xffff;
6096	sum += sumd;
6097	sum = (sum >> 16) + (sum & 0xffff);
6098	sum = (sum >> 16) + (sum & 0xffff);
6099	sums = ~(u_short)sum;
6100	ip->ip_sum = htons(sums);
6101	return 0;
6102}
6103
6104
6105#ifdef	NEED_FRGETIFNAME
6106/* ------------------------------------------------------------------------ */
6107/* Function:    ipf_getifname                                               */
6108/* Returns:     char *    - pointer to interface name                       */
6109/* Parameters:  ifp(I)    - pointer to network interface                    */
6110/*              buffer(O) - pointer to where to store interface name        */
6111/*                                                                          */
6112/* Constructs an interface name in the buffer passed.  The buffer passed is */
6113/* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6114/* as a NULL pointer then return a pointer to a static array.               */
6115/* ------------------------------------------------------------------------ */
6116char *
6117ipf_getifname(ifp, buffer)
6118	struct ifnet *ifp;
6119	char *buffer;
6120{
6121	static char namebuf[LIFNAMSIZ];
6122# if defined(MENTAT) || defined(__FreeBSD__)
6123	int unit, space;
6124	char temp[20];
6125	char *s;
6126# endif
6127
6128	if (buffer == NULL)
6129		buffer = namebuf;
6130	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6131	buffer[LIFNAMSIZ - 1] = '\0';
6132# if defined(MENTAT) || defined(__FreeBSD__)
6133	for (s = buffer; *s; s++)
6134		;
6135	unit = ifp->if_unit;
6136	space = LIFNAMSIZ - (s - buffer);
6137	if ((space > 0) && (unit >= 0)) {
6138#  if defined(SNPRINTF) && defined(_KERNEL)
6139		SNPRINTF(temp, sizeof(temp), "%d", unit);
6140#  else
6141		(void) sprintf(temp, "%d", unit);
6142#  endif
6143		(void) strncpy(s, temp, space);
6144	}
6145# endif
6146	return buffer;
6147}
6148#endif
6149
6150
6151/* ------------------------------------------------------------------------ */
6152/* Function:    ipf_ioctlswitch                                             */
6153/* Returns:     int     - -1 continue processing, else ioctl return value   */
6154/* Parameters:  unit(I) - device unit opened                                */
6155/*              data(I) - pointer to ioctl data                             */
6156/*              cmd(I)  - ioctl command                                     */
6157/*              mode(I) - mode value                                        */
6158/*              uid(I)  - uid making the ioctl call                         */
6159/*              ctx(I)  - pointer to context data                           */
6160/*                                                                          */
6161/* Based on the value of unit, call the appropriate ioctl handler or return */
6162/* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6163/* for the device in order to execute the ioctl.  A special case is made    */
6164/* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6165/* The context data pointer is passed through as this is used as the key    */
6166/* for locating a matching token for continued access for walking lists,    */
6167/* etc.                                                                     */
6168/* ------------------------------------------------------------------------ */
6169int
6170ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6171	ipf_main_softc_t *softc;
6172	int unit, mode, uid;
6173	ioctlcmd_t cmd;
6174	void *data, *ctx;
6175{
6176	int error = 0;
6177
6178	switch (cmd)
6179	{
6180	case SIOCIPFINTERROR :
6181		error = BCOPYOUT(&softc->ipf_interror, data,
6182				 sizeof(softc->ipf_interror));
6183		if (error != 0) {
6184			IPFERROR(40);
6185			error = EFAULT;
6186		}
6187		return error;
6188	default :
6189		break;
6190	}
6191
6192	switch (unit)
6193	{
6194	case IPL_LOGIPF :
6195		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6196		break;
6197	case IPL_LOGNAT :
6198		if (softc->ipf_running > 0) {
6199			error = ipf_nat_ioctl(softc, data, cmd, mode,
6200					      uid, ctx);
6201		} else {
6202			IPFERROR(42);
6203			error = EIO;
6204		}
6205		break;
6206	case IPL_LOGSTATE :
6207		if (softc->ipf_running > 0) {
6208			error = ipf_state_ioctl(softc, data, cmd, mode,
6209						uid, ctx);
6210		} else {
6211			IPFERROR(43);
6212			error = EIO;
6213		}
6214		break;
6215	case IPL_LOGAUTH :
6216		if (softc->ipf_running > 0) {
6217			error = ipf_auth_ioctl(softc, data, cmd, mode,
6218					       uid, ctx);
6219		} else {
6220			IPFERROR(44);
6221			error = EIO;
6222		}
6223		break;
6224	case IPL_LOGSYNC :
6225		if (softc->ipf_running > 0) {
6226			error = ipf_sync_ioctl(softc, data, cmd, mode,
6227					       uid, ctx);
6228		} else {
6229			error = EIO;
6230			IPFERROR(45);
6231		}
6232		break;
6233	case IPL_LOGSCAN :
6234#ifdef IPFILTER_SCAN
6235		if (softc->ipf_running > 0)
6236			error = ipf_scan_ioctl(softc, data, cmd, mode,
6237					       uid, ctx);
6238		else
6239#endif
6240		{
6241			error = EIO;
6242			IPFERROR(46);
6243		}
6244		break;
6245	case IPL_LOGLOOKUP :
6246		if (softc->ipf_running > 0) {
6247			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6248						 uid, ctx);
6249		} else {
6250			error = EIO;
6251			IPFERROR(47);
6252		}
6253		break;
6254	default :
6255		IPFERROR(48);
6256		error = EIO;
6257		break;
6258	}
6259
6260	return error;
6261}
6262
6263
6264/*
6265 * This array defines the expected size of objects coming into the kernel
6266 * for the various recognised object types. The first column is flags (see
6267 * below), 2nd column is current size, 3rd column is the version number of
6268 * when the current size became current.
6269 * Flags:
6270 * 1 = minimum size, not absolute size
6271 */
6272static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6273	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6274	{ 1,	sizeof(struct friostat),	5010000 },
6275	{ 0,	sizeof(struct fr_info),		5010000 },
6276	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6277	{ 0,	sizeof(struct ipfrstat),	5010000 },
6278	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6279	{ 0,	sizeof(struct natstat),		5010000 },
6280	{ 0,	sizeof(struct ipstate_save),	5010000 },
6281	{ 1,	sizeof(struct nat_save),	5010000 },
6282	{ 0,	sizeof(struct natlookup),	5010000 },
6283	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6284	{ 0,	sizeof(struct ips_stat),	5010000 },
6285	{ 0,	sizeof(struct frauth),		5010000 },
6286	{ 0,	sizeof(struct ipftune),		4010100 },
6287	{ 0,	sizeof(struct nat),		5010000 },
6288	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6289	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6290	{ 0,	sizeof(struct ipftable),	4011400 },
6291	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6292	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6293	{ 1,	0,				0	}, /* IPFEXPR */
6294	{ 0,	0,				0	}, /* PROXYCTL */
6295	{ 0,	sizeof (struct fripf),		5010000	}
6296};
6297
6298
6299/* ------------------------------------------------------------------------ */
6300/* Function:    ipf_inobj                                                   */
6301/* Returns:     int     - 0 = success, else failure                         */
6302/* Parameters:  softc(I) - soft context pointerto work with                 */
6303/*              data(I)  - pointer to ioctl data                            */
6304/*              objp(O)  - where to store ipfobj structure                  */
6305/*              ptr(I)   - pointer to data to copy out                      */
6306/*              type(I)  - type of structure being moved                    */
6307/*                                                                          */
6308/* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6309/* add things to check for version numbers, sizes, etc, to make it backward */
6310/* compatible at the ABI for user land.                                     */
6311/* If objp is not NULL then we assume that the caller wants to see what is  */
6312/* in the ipfobj_t structure being copied in. As an example, this can tell  */
6313/* the caller what version of ipfilter the ioctl program was written to.    */
6314/* ------------------------------------------------------------------------ */
6315int
6316ipf_inobj(softc, data, objp, ptr, type)
6317	ipf_main_softc_t *softc;
6318	void *data;
6319	ipfobj_t *objp;
6320	void *ptr;
6321	int type;
6322{
6323	ipfobj_t obj;
6324	int error;
6325	int size;
6326
6327	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6328		IPFERROR(49);
6329		return EINVAL;
6330	}
6331
6332	if (objp == NULL)
6333		objp = &obj;
6334	error = BCOPYIN(data, objp, sizeof(*objp));
6335	if (error != 0) {
6336		IPFERROR(124);
6337		return EFAULT;
6338	}
6339
6340	if (objp->ipfo_type != type) {
6341		IPFERROR(50);
6342		return EINVAL;
6343	}
6344
6345	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6346		if ((ipf_objbytes[type][0] & 1) != 0) {
6347			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6348				IPFERROR(51);
6349				return EINVAL;
6350			}
6351			size =  ipf_objbytes[type][1];
6352		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6353			size =  objp->ipfo_size;
6354		} else {
6355			IPFERROR(52);
6356			return EINVAL;
6357		}
6358		error = COPYIN(objp->ipfo_ptr, ptr, size);
6359		if (error != 0) {
6360			IPFERROR(55);
6361			error = EFAULT;
6362		}
6363	} else {
6364#ifdef  IPFILTER_COMPAT
6365		error = ipf_in_compat(softc, objp, ptr, 0);
6366#else
6367		IPFERROR(54);
6368		error = EINVAL;
6369#endif
6370	}
6371	return error;
6372}
6373
6374
6375/* ------------------------------------------------------------------------ */
6376/* Function:    ipf_inobjsz                                                 */
6377/* Returns:     int     - 0 = success, else failure                         */
6378/* Parameters:  softc(I) - soft context pointerto work with                 */
6379/*              data(I)  - pointer to ioctl data                            */
6380/*              ptr(I)   - pointer to store real data in                    */
6381/*              type(I)  - type of structure being moved                    */
6382/*              sz(I)    - size of data to copy                             */
6383/*                                                                          */
6384/* As per ipf_inobj, except the size of the object to copy in is passed in  */
6385/* but it must not be smaller than the size defined for the type and the    */
6386/* type must allow for varied sized objects.  The extra requirement here is */
6387/* that sz must match the size of the object being passed in - this is not  */
6388/* not possible nor required in ipf_inobj().                                */
6389/* ------------------------------------------------------------------------ */
6390int
6391ipf_inobjsz(softc, data, ptr, type, sz)
6392	ipf_main_softc_t *softc;
6393	void *data;
6394	void *ptr;
6395	int type, sz;
6396{
6397	ipfobj_t obj;
6398	int error;
6399
6400	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6401		IPFERROR(56);
6402		return EINVAL;
6403	}
6404
6405	error = BCOPYIN(data, &obj, sizeof(obj));
6406	if (error != 0) {
6407		IPFERROR(125);
6408		return EFAULT;
6409	}
6410
6411	if (obj.ipfo_type != type) {
6412		IPFERROR(58);
6413		return EINVAL;
6414	}
6415
6416	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6417		if (((ipf_objbytes[type][0] & 1) == 0) ||
6418		    (sz < ipf_objbytes[type][1])) {
6419			IPFERROR(57);
6420			return EINVAL;
6421		}
6422		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6423		if (error != 0) {
6424			IPFERROR(61);
6425			error = EFAULT;
6426		}
6427	} else {
6428#ifdef	IPFILTER_COMPAT
6429		error = ipf_in_compat(softc, &obj, ptr, sz);
6430#else
6431		IPFERROR(60);
6432		error = EINVAL;
6433#endif
6434	}
6435	return error;
6436}
6437
6438
6439/* ------------------------------------------------------------------------ */
6440/* Function:    ipf_outobjsz                                                */
6441/* Returns:     int     - 0 = success, else failure                         */
6442/* Parameters:  data(I) - pointer to ioctl data                             */
6443/*              ptr(I)  - pointer to store real data in                     */
6444/*              type(I) - type of structure being moved                     */
6445/*              sz(I)   - size of data to copy                              */
6446/*                                                                          */
6447/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6448/* but it must not be smaller than the size defined for the type and the    */
6449/* type must allow for varied sized objects.  The extra requirement here is */
6450/* that sz must match the size of the object being passed in - this is not  */
6451/* not possible nor required in ipf_outobj().                               */
6452/* ------------------------------------------------------------------------ */
6453int
6454ipf_outobjsz(softc, data, ptr, type, sz)
6455	ipf_main_softc_t *softc;
6456	void *data;
6457	void *ptr;
6458	int type, sz;
6459{
6460	ipfobj_t obj;
6461	int error;
6462
6463	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6464		IPFERROR(62);
6465		return EINVAL;
6466	}
6467
6468	error = BCOPYIN(data, &obj, sizeof(obj));
6469	if (error != 0) {
6470		IPFERROR(127);
6471		return EFAULT;
6472	}
6473
6474	if (obj.ipfo_type != type) {
6475		IPFERROR(63);
6476		return EINVAL;
6477	}
6478
6479	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6480		if (((ipf_objbytes[type][0] & 1) == 0) ||
6481		    (sz < ipf_objbytes[type][1])) {
6482			IPFERROR(146);
6483			return EINVAL;
6484		}
6485		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6486		if (error != 0) {
6487			IPFERROR(66);
6488			error = EFAULT;
6489		}
6490	} else {
6491#ifdef	IPFILTER_COMPAT
6492		error = ipf_out_compat(softc, &obj, ptr);
6493#else
6494		IPFERROR(65);
6495		error = EINVAL;
6496#endif
6497	}
6498	return error;
6499}
6500
6501
6502/* ------------------------------------------------------------------------ */
6503/* Function:    ipf_outobj                                                  */
6504/* Returns:     int     - 0 = success, else failure                         */
6505/* Parameters:  data(I) - pointer to ioctl data                             */
6506/*              ptr(I)  - pointer to store real data in                     */
6507/*              type(I) - type of structure being moved                     */
6508/*                                                                          */
6509/* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6510/* future, we add things to check for version numbers, sizes, etc, to make  */
6511/* it backward  compatible at the ABI for user land.                        */
6512/* ------------------------------------------------------------------------ */
6513int
6514ipf_outobj(softc, data, ptr, type)
6515	ipf_main_softc_t *softc;
6516	void *data;
6517	void *ptr;
6518	int type;
6519{
6520	ipfobj_t obj;
6521	int error;
6522
6523	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6524		IPFERROR(67);
6525		return EINVAL;
6526	}
6527
6528	error = BCOPYIN(data, &obj, sizeof(obj));
6529	if (error != 0) {
6530		IPFERROR(126);
6531		return EFAULT;
6532	}
6533
6534	if (obj.ipfo_type != type) {
6535		IPFERROR(68);
6536		return EINVAL;
6537	}
6538
6539	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6540		if ((ipf_objbytes[type][0] & 1) != 0) {
6541			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6542				IPFERROR(69);
6543				return EINVAL;
6544			}
6545		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6546			IPFERROR(70);
6547			return EINVAL;
6548		}
6549
6550		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6551		if (error != 0) {
6552			IPFERROR(73);
6553			error = EFAULT;
6554		}
6555	} else {
6556#ifdef	IPFILTER_COMPAT
6557		error = ipf_out_compat(softc, &obj, ptr);
6558#else
6559		IPFERROR(72);
6560		error = EINVAL;
6561#endif
6562	}
6563	return error;
6564}
6565
6566
6567/* ------------------------------------------------------------------------ */
6568/* Function:    ipf_outobjk                                                 */
6569/* Returns:     int     - 0 = success, else failure                         */
6570/* Parameters:  obj(I)  - pointer to data description structure             */
6571/*              ptr(I)  - pointer to kernel data to copy out                */
6572/*                                                                          */
6573/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6574/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6575/* already populated with information and now we just need to use it.       */
6576/* There is no need for this function to have a "type" parameter as there   */
6577/* is no point in validating information that comes from the kernel with    */
6578/* itself.                                                                  */
6579/* ------------------------------------------------------------------------ */
6580int
6581ipf_outobjk(softc, obj, ptr)
6582	ipf_main_softc_t *softc;
6583	ipfobj_t *obj;
6584	void *ptr;
6585{
6586	int type = obj->ipfo_type;
6587	int error;
6588
6589	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6590		IPFERROR(147);
6591		return EINVAL;
6592	}
6593
6594	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6595		if ((ipf_objbytes[type][0] & 1) != 0) {
6596			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6597				IPFERROR(148);
6598				return EINVAL;
6599			}
6600
6601		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6602			IPFERROR(149);
6603			return EINVAL;
6604		}
6605
6606		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6607		if (error != 0) {
6608			IPFERROR(150);
6609			error = EFAULT;
6610		}
6611	} else {
6612#ifdef  IPFILTER_COMPAT
6613		error = ipf_out_compat(softc, obj, ptr);
6614#else
6615		IPFERROR(151);
6616		error = EINVAL;
6617#endif
6618	}
6619	return error;
6620}
6621
6622
6623/* ------------------------------------------------------------------------ */
6624/* Function:    ipf_checkl4sum                                              */
6625/* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6626/* Parameters:  fin(I) - pointer to packet information                      */
6627/*                                                                          */
6628/* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6629/* not possible, return without indicating a failure or success but in a    */
6630/* way that is ditinguishable. This function should only be called by the   */
6631/* ipf_checkv6sum() for each platform.                                      */
6632/* ------------------------------------------------------------------------ */
6633INLINE int
6634ipf_checkl4sum(fin)
6635	fr_info_t *fin;
6636{
6637	u_short sum, hdrsum, *csump;
6638	udphdr_t *udp;
6639	int dosum;
6640
6641	/*
6642	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6643	 * isn't already considered "bad", then validate the checksum.  If
6644	 * this check fails then considered the packet to be "bad".
6645	 */
6646	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6647		return 1;
6648
6649	csump = NULL;
6650	hdrsum = 0;
6651	dosum = 0;
6652	sum = 0;
6653
6654	switch (fin->fin_p)
6655	{
6656	case IPPROTO_TCP :
6657		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6658		dosum = 1;
6659		break;
6660
6661	case IPPROTO_UDP :
6662		udp = fin->fin_dp;
6663		if (udp->uh_sum != 0) {
6664			csump = &udp->uh_sum;
6665			dosum = 1;
6666		}
6667		break;
6668
6669#ifdef USE_INET6
6670	case IPPROTO_ICMPV6 :
6671		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6672		dosum = 1;
6673		break;
6674#endif
6675
6676	case IPPROTO_ICMP :
6677		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6678		dosum = 1;
6679		break;
6680
6681	default :
6682		return 1;
6683		/*NOTREACHED*/
6684	}
6685
6686	if (csump != NULL)
6687		hdrsum = *csump;
6688
6689	if (dosum) {
6690		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6691	}
6692#if !defined(_KERNEL)
6693	if (sum == hdrsum) {
6694		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6695	} else {
6696		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6697	}
6698#endif
6699	DT2(l4sums, u_short, hdrsum, u_short, sum);
6700	if (hdrsum == sum) {
6701		fin->fin_cksum = FI_CK_SUMOK;
6702		return 0;
6703	}
6704	fin->fin_cksum = FI_CK_BAD;
6705	return -1;
6706}
6707
6708
6709/* ------------------------------------------------------------------------ */
6710/* Function:    ipf_ifpfillv4addr                                           */
6711/* Returns:     int     - 0 = address update, -1 = address not updated      */
6712/* Parameters:  atype(I)   - type of network address update to perform      */
6713/*              sin(I)     - pointer to source of address information       */
6714/*              mask(I)    - pointer to source of netmask information       */
6715/*              inp(I)     - pointer to destination address store           */
6716/*              inpmask(I) - pointer to destination netmask store           */
6717/*                                                                          */
6718/* Given a type of network address update (atype) to perform, copy          */
6719/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6720/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6721/* which case the operation fails.  For all values of atype other than      */
6722/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6723/* value.                                                                   */
6724/* ------------------------------------------------------------------------ */
6725int
6726ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6727	int atype;
6728	struct sockaddr_in *sin, *mask;
6729	struct in_addr *inp, *inpmask;
6730{
6731	if (inpmask != NULL && atype != FRI_NETMASKED)
6732		inpmask->s_addr = 0xffffffff;
6733
6734	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6735		if (atype == FRI_NETMASKED) {
6736			if (inpmask == NULL)
6737				return -1;
6738			inpmask->s_addr = mask->sin_addr.s_addr;
6739		}
6740		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6741	} else {
6742		inp->s_addr = sin->sin_addr.s_addr;
6743	}
6744	return 0;
6745}
6746
6747
6748#ifdef	USE_INET6
6749/* ------------------------------------------------------------------------ */
6750/* Function:    ipf_ifpfillv6addr                                           */
6751/* Returns:     int     - 0 = address update, -1 = address not updated      */
6752/* Parameters:  atype(I)   - type of network address update to perform      */
6753/*              sin(I)     - pointer to source of address information       */
6754/*              mask(I)    - pointer to source of netmask information       */
6755/*              inp(I)     - pointer to destination address store           */
6756/*              inpmask(I) - pointer to destination netmask store           */
6757/*                                                                          */
6758/* Given a type of network address update (atype) to perform, copy          */
6759/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6760/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6761/* which case the operation fails.  For all values of atype other than      */
6762/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6763/* value.                                                                   */
6764/* ------------------------------------------------------------------------ */
6765int
6766ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6767	int atype;
6768	struct sockaddr_in6 *sin, *mask;
6769	i6addr_t *inp, *inpmask;
6770{
6771	i6addr_t *src, *and;
6772
6773	src = (i6addr_t *)&sin->sin6_addr;
6774	and = (i6addr_t *)&mask->sin6_addr;
6775
6776	if (inpmask != NULL && atype != FRI_NETMASKED) {
6777		inpmask->i6[0] = 0xffffffff;
6778		inpmask->i6[1] = 0xffffffff;
6779		inpmask->i6[2] = 0xffffffff;
6780		inpmask->i6[3] = 0xffffffff;
6781	}
6782
6783	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6784		if (atype == FRI_NETMASKED) {
6785			if (inpmask == NULL)
6786				return -1;
6787			inpmask->i6[0] = and->i6[0];
6788			inpmask->i6[1] = and->i6[1];
6789			inpmask->i6[2] = and->i6[2];
6790			inpmask->i6[3] = and->i6[3];
6791		}
6792
6793		inp->i6[0] = src->i6[0] & and->i6[0];
6794		inp->i6[1] = src->i6[1] & and->i6[1];
6795		inp->i6[2] = src->i6[2] & and->i6[2];
6796		inp->i6[3] = src->i6[3] & and->i6[3];
6797	} else {
6798		inp->i6[0] = src->i6[0];
6799		inp->i6[1] = src->i6[1];
6800		inp->i6[2] = src->i6[2];
6801		inp->i6[3] = src->i6[3];
6802	}
6803	return 0;
6804}
6805#endif
6806
6807
6808/* ------------------------------------------------------------------------ */
6809/* Function:    ipf_matchtag                                                */
6810/* Returns:     0 == mismatch, 1 == match.                                  */
6811/* Parameters:  tag1(I) - pointer to first tag to compare                   */
6812/*              tag2(I) - pointer to second tag to compare                  */
6813/*                                                                          */
6814/* Returns true (non-zero) or false(0) if the two tag structures can be     */
6815/* considered to be a match or not match, respectively.  The tag is 16      */
6816/* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6817/* compare the ints instead, for speed. tag1 is the master of the           */
6818/* comparison.  This function should only be called with both tag1 and tag2 */
6819/* as non-NULL pointers.                                                    */
6820/* ------------------------------------------------------------------------ */
6821int
6822ipf_matchtag(tag1, tag2)
6823	ipftag_t *tag1, *tag2;
6824{
6825	if (tag1 == tag2)
6826		return 1;
6827
6828	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6829		return 1;
6830
6831	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6832	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6833	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6834	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6835		return 1;
6836	return 0;
6837}
6838
6839
6840/* ------------------------------------------------------------------------ */
6841/* Function:    ipf_coalesce                                                */
6842/* Returns:     1 == success, -1 == failure, 0 == no change                 */
6843/* Parameters:  fin(I) - pointer to packet information                      */
6844/*                                                                          */
6845/* Attempt to get all of the packet data into a single, contiguous buffer.  */
6846/* If this call returns a failure then the buffers have also been freed.    */
6847/* ------------------------------------------------------------------------ */
6848int
6849ipf_coalesce(fin)
6850	fr_info_t *fin;
6851{
6852
6853	if ((fin->fin_flx & FI_COALESCE) != 0)
6854		return 1;
6855
6856	/*
6857	 * If the mbuf pointers indicate that there is no mbuf to work with,
6858	 * return but do not indicate success or failure.
6859	 */
6860	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6861		return 0;
6862
6863#if defined(_KERNEL)
6864	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6865		ipf_main_softc_t *softc = fin->fin_main_soft;
6866
6867		DT1(frb_coalesce, fr_info_t *, fin);
6868		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6869# ifdef MENTAT
6870		FREE_MB_T(*fin->fin_mp);
6871# endif
6872		fin->fin_reason = FRB_COALESCE;
6873		*fin->fin_mp = NULL;
6874		fin->fin_m = NULL;
6875		return -1;
6876	}
6877#else
6878	fin = fin;	/* LINT */
6879#endif
6880	return 1;
6881}
6882
6883
6884/*
6885 * The following table lists all of the tunable variables that can be
6886 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6887 * in the table below is as follows:
6888 *
6889 * pointer to value, name of value, minimum, maximum, size of the value's
6890 *     container, value attribute flags
6891 *
6892 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6893 * means the value can only be written to when IPFilter is loaded but disabled.
6894 * The obvious implication is if neither of these are set then the value can be
6895 * changed at any time without harm.
6896 */
6897
6898
6899/* ------------------------------------------------------------------------ */
6900/* Function:    ipf_tune_findbycookie                                       */
6901/* Returns:     NULL = search failed, else pointer to tune struct           */
6902/* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6903/*              next(O)   - pointer to place to store the cookie for the    */
6904/*                          "next" tuneable, if it is desired.              */
6905/*                                                                          */
6906/* This function is used to walk through all of the existing tunables with  */
6907/* successive calls.  It searches the known tunables for the one which has  */
6908/* a matching value for "cookie" - ie its address.  When returning a match, */
6909/* the next one to be found may be returned inside next.                    */
6910/* ------------------------------------------------------------------------ */
6911static ipftuneable_t *
6912ipf_tune_findbycookie(ptop, cookie, next)
6913	ipftuneable_t **ptop;
6914	void *cookie, **next;
6915{
6916	ipftuneable_t *ta, **tap;
6917
6918	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6919		if (ta == cookie) {
6920			if (next != NULL) {
6921				/*
6922				 * If the next entry in the array has a name
6923				 * present, then return a pointer to it for
6924				 * where to go next, else return a pointer to
6925				 * the dynaminc list as a key to search there
6926				 * next.  This facilitates a weak linking of
6927				 * the two "lists" together.
6928				 */
6929				if ((ta + 1)->ipft_name != NULL)
6930					*next = ta + 1;
6931				else
6932					*next = ptop;
6933			}
6934			return ta;
6935		}
6936
6937	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6938		if (tap == cookie) {
6939			if (next != NULL)
6940				*next = &ta->ipft_next;
6941			return ta;
6942		}
6943
6944	if (next != NULL)
6945		*next = NULL;
6946	return NULL;
6947}
6948
6949
6950/* ------------------------------------------------------------------------ */
6951/* Function:    ipf_tune_findbyname                                         */
6952/* Returns:     NULL = search failed, else pointer to tune struct           */
6953/* Parameters:  name(I) - name of the tuneable entry to find.               */
6954/*                                                                          */
6955/* Search the static array of tuneables and the list of dynamic tuneables   */
6956/* for an entry with a matching name.  If we can find one, return a pointer */
6957/* to the matching structure.                                               */
6958/* ------------------------------------------------------------------------ */
6959static ipftuneable_t *
6960ipf_tune_findbyname(top, name)
6961	ipftuneable_t *top;
6962	const char *name;
6963{
6964	ipftuneable_t *ta;
6965
6966	for (ta = top; ta != NULL; ta = ta->ipft_next)
6967		if (!strcmp(ta->ipft_name, name)) {
6968			return ta;
6969		}
6970
6971	return NULL;
6972}
6973
6974
6975/* ------------------------------------------------------------------------ */
6976/* Function:    ipf_tune_add_array                                          */
6977/* Returns:     int - 0 == success, else failure                            */
6978/* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6979/*                                                                          */
6980/* Appends tune structures from the array passed in (newtune) to the end of */
6981/* the current list of "dynamic" tuneable parameters.                       */
6982/* If any entry to be added is already present (by name) then the operation */
6983/* is aborted - entries that have been added are removed before returning.  */
6984/* An entry with no name (NULL) is used as the indication that the end of   */
6985/* the array has been reached.                                              */
6986/* ------------------------------------------------------------------------ */
6987int
6988ipf_tune_add_array(softc, newtune)
6989	ipf_main_softc_t *softc;
6990	ipftuneable_t *newtune;
6991{
6992	ipftuneable_t *nt, *dt;
6993	int error = 0;
6994
6995	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6996		error = ipf_tune_add(softc, nt);
6997		if (error != 0) {
6998			for (dt = newtune; dt != nt; dt++) {
6999				(void) ipf_tune_del(softc, dt);
7000			}
7001		}
7002	}
7003
7004	return error;
7005}
7006
7007
7008/* ------------------------------------------------------------------------ */
7009/* Function:    ipf_tune_array_link                                         */
7010/* Returns:     0 == success, -1 == failure                                 */
7011/* Parameters:  softc(I) - soft context pointerto work with                 */
7012/*              array(I) - pointer to an array of tuneables                 */
7013/*                                                                          */
7014/* Given an array of tunables (array), append them to the current list of   */
7015/* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7016/* the array for being appended to the list, initialise all of the next     */
7017/* pointers so we don't need to walk parts of it with ++ and others with    */
7018/* next. The array is expected to have an entry with a NULL name as the     */
7019/* terminator. Trying to add an array with no non-NULL names will return as */
7020/* a failure.                                                               */
7021/* ------------------------------------------------------------------------ */
7022int
7023ipf_tune_array_link(softc, array)
7024	ipf_main_softc_t *softc;
7025	ipftuneable_t *array;
7026{
7027	ipftuneable_t *t, **p;
7028
7029	t = array;
7030	if (t->ipft_name == NULL)
7031		return -1;
7032
7033	for (; t[1].ipft_name != NULL; t++)
7034		t[0].ipft_next = &t[1];
7035	t->ipft_next = NULL;
7036
7037	/*
7038	 * Since a pointer to the last entry isn't kept, we need to find it
7039	 * each time we want to add new variables to the list.
7040	 */
7041	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7042		if (t->ipft_name == NULL)
7043			break;
7044	*p = array;
7045
7046	return 0;
7047}
7048
7049
7050/* ------------------------------------------------------------------------ */
7051/* Function:    ipf_tune_array_unlink                                       */
7052/* Returns:     0 == success, -1 == failure                                 */
7053/* Parameters:  softc(I) - soft context pointerto work with                 */
7054/*              array(I) - pointer to an array of tuneables                 */
7055/*                                                                          */
7056/* ------------------------------------------------------------------------ */
7057int
7058ipf_tune_array_unlink(softc, array)
7059	ipf_main_softc_t *softc;
7060	ipftuneable_t *array;
7061{
7062	ipftuneable_t *t, **p;
7063
7064	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7065		if (t == array)
7066			break;
7067	if (t == NULL)
7068		return -1;
7069
7070	for (; t[1].ipft_name != NULL; t++)
7071		;
7072
7073	*p = t->ipft_next;
7074
7075	return 0;
7076}
7077
7078
7079/* ------------------------------------------------------------------------ */
7080/* Function:   ipf_tune_array_copy                                          */
7081/* Returns:    NULL = failure, else pointer to new array                    */
7082/* Parameters: base(I)     - pointer to structure base                      */
7083/*             size(I)     - size of the array at template                  */
7084/*             template(I) - original array to copy                         */
7085/*                                                                          */
7086/* Allocate memory for a new set of tuneable values and copy everything     */
7087/* from template into the new region of memory.  The new region is full of  */
7088/* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7089/*                                                                          */
7090/* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7091/* In the array template, ipftp_offset is the offset (in bytes) of the      */
7092/* location of the tuneable value inside the structure pointed to by base.  */
7093/* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7094/* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7095/* ipftp_void that points to the stored value.                              */
7096/* ------------------------------------------------------------------------ */
7097ipftuneable_t *
7098ipf_tune_array_copy(base, size, template)
7099	void *base;
7100	size_t size;
7101	ipftuneable_t *template;
7102{
7103	ipftuneable_t *copy;
7104	int i;
7105
7106
7107	KMALLOCS(copy, ipftuneable_t *, size);
7108	if (copy == NULL) {
7109		return NULL;
7110	}
7111	bcopy(template, copy, size);
7112
7113	for (i = 0; copy[i].ipft_name; i++) {
7114		copy[i].ipft_una.ipftp_offset += (u_long)base;
7115		copy[i].ipft_next = copy + i + 1;
7116	}
7117
7118	return copy;
7119}
7120
7121
7122/* ------------------------------------------------------------------------ */
7123/* Function:    ipf_tune_add                                                */
7124/* Returns:     int - 0 == success, else failure                            */
7125/* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7126/*                                                                          */
7127/* Appends tune structures from the array passed in (newtune) to the end of */
7128/* the current list of "dynamic" tuneable parameters.  Once added, the      */
7129/* owner of the object is not expected to ever change "ipft_next".          */
7130/* ------------------------------------------------------------------------ */
7131int
7132ipf_tune_add(softc, newtune)
7133	ipf_main_softc_t *softc;
7134	ipftuneable_t *newtune;
7135{
7136	ipftuneable_t *ta, **tap;
7137
7138	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7139	if (ta != NULL) {
7140		IPFERROR(74);
7141		return EEXIST;
7142	}
7143
7144	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7145		;
7146
7147	newtune->ipft_next = NULL;
7148	*tap = newtune;
7149	return 0;
7150}
7151
7152
7153/* ------------------------------------------------------------------------ */
7154/* Function:    ipf_tune_del                                                */
7155/* Returns:     int - 0 == success, else failure                            */
7156/* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7157/*                        current dynamic tuneables                         */
7158/*                                                                          */
7159/* Search for the tune structure, by pointer, in the list of those that are */
7160/* dynamically added at run time.  If found, adjust the list so that this   */
7161/* structure is no longer part of it.                                       */
7162/* ------------------------------------------------------------------------ */
7163int
7164ipf_tune_del(softc, oldtune)
7165	ipf_main_softc_t *softc;
7166	ipftuneable_t *oldtune;
7167{
7168	ipftuneable_t *ta, **tap;
7169	int error = 0;
7170
7171	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7172	     tap = &ta->ipft_next) {
7173		if (ta == oldtune) {
7174			*tap = oldtune->ipft_next;
7175			oldtune->ipft_next = NULL;
7176			break;
7177		}
7178	}
7179
7180	if (ta == NULL) {
7181		error = ESRCH;
7182		IPFERROR(75);
7183	}
7184	return error;
7185}
7186
7187
7188/* ------------------------------------------------------------------------ */
7189/* Function:    ipf_tune_del_array                                          */
7190/* Returns:     int - 0 == success, else failure                            */
7191/* Parameters:  oldtune - pointer to tuneables array                        */
7192/*                                                                          */
7193/* Remove each tuneable entry in the array from the list of "dynamic"       */
7194/* tunables.  If one entry should fail to be found, an error will be        */
7195/* returned and no further ones removed.                                    */
7196/* An entry with a NULL name is used as the indicator of the last entry in  */
7197/* the array.                                                               */
7198/* ------------------------------------------------------------------------ */
7199int
7200ipf_tune_del_array(softc, oldtune)
7201	ipf_main_softc_t *softc;
7202	ipftuneable_t *oldtune;
7203{
7204	ipftuneable_t *ot;
7205	int error = 0;
7206
7207	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7208		error = ipf_tune_del(softc, ot);
7209		if (error != 0)
7210			break;
7211	}
7212
7213	return error;
7214
7215}
7216
7217
7218/* ------------------------------------------------------------------------ */
7219/* Function:    ipf_tune                                                    */
7220/* Returns:     int - 0 == success, else failure                            */
7221/* Parameters:  cmd(I)  - ioctl command number                              */
7222/*              data(I) - pointer to ioctl data structure                   */
7223/*                                                                          */
7224/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7225/* three ioctls provide the means to access and control global variables    */
7226/* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7227/* changed without rebooting, reloading or recompiling.  The initialisation */
7228/* and 'destruction' routines of the various components of ipfilter are all */
7229/* each responsible for handling their own values being too big.            */
7230/* ------------------------------------------------------------------------ */
7231int
7232ipf_ipftune(softc, cmd, data)
7233	ipf_main_softc_t *softc;
7234	ioctlcmd_t cmd;
7235	void *data;
7236{
7237	ipftuneable_t *ta;
7238	ipftune_t tu;
7239	void *cookie;
7240	int error;
7241
7242	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7243	if (error != 0)
7244		return error;
7245
7246	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7247	cookie = tu.ipft_cookie;
7248	ta = NULL;
7249
7250	switch (cmd)
7251	{
7252	case SIOCIPFGETNEXT :
7253		/*
7254		 * If cookie is non-NULL, assume it to be a pointer to the last
7255		 * entry we looked at, so find it (if possible) and return a
7256		 * pointer to the next one after it.  The last entry in the
7257		 * the table is a NULL entry, so when we get to it, set cookie
7258		 * to NULL and return that, indicating end of list, erstwhile
7259		 * if we come in with cookie set to NULL, we are starting anew
7260		 * at the front of the list.
7261		 */
7262		if (cookie != NULL) {
7263			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7264						   cookie, &tu.ipft_cookie);
7265		} else {
7266			ta = softc->ipf_tuners;
7267			tu.ipft_cookie = ta + 1;
7268		}
7269		if (ta != NULL) {
7270			/*
7271			 * Entry found, but does the data pointed to by that
7272			 * row fit in what we can return?
7273			 */
7274			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7275				IPFERROR(76);
7276				return EINVAL;
7277			}
7278
7279			tu.ipft_vlong = 0;
7280			if (ta->ipft_sz == sizeof(u_long))
7281				tu.ipft_vlong = *ta->ipft_plong;
7282			else if (ta->ipft_sz == sizeof(u_int))
7283				tu.ipft_vint = *ta->ipft_pint;
7284			else if (ta->ipft_sz == sizeof(u_short))
7285				tu.ipft_vshort = *ta->ipft_pshort;
7286			else if (ta->ipft_sz == sizeof(u_char))
7287				tu.ipft_vchar = *ta->ipft_pchar;
7288
7289			tu.ipft_sz = ta->ipft_sz;
7290			tu.ipft_min = ta->ipft_min;
7291			tu.ipft_max = ta->ipft_max;
7292			tu.ipft_flags = ta->ipft_flags;
7293			bcopy(ta->ipft_name, tu.ipft_name,
7294			      MIN(sizeof(tu.ipft_name),
7295				  strlen(ta->ipft_name) + 1));
7296		}
7297		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7298		break;
7299
7300	case SIOCIPFGET :
7301	case SIOCIPFSET :
7302		/*
7303		 * Search by name or by cookie value for a particular entry
7304		 * in the tuning paramter table.
7305		 */
7306		IPFERROR(77);
7307		error = ESRCH;
7308		if (cookie != NULL) {
7309			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7310						   cookie, NULL);
7311			if (ta != NULL)
7312				error = 0;
7313		} else if (tu.ipft_name[0] != '\0') {
7314			ta = ipf_tune_findbyname(softc->ipf_tuners,
7315						 tu.ipft_name);
7316			if (ta != NULL)
7317				error = 0;
7318		}
7319		if (error != 0)
7320			break;
7321
7322		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7323			/*
7324			 * Fetch the tuning parameters for a particular value
7325			 */
7326			tu.ipft_vlong = 0;
7327			if (ta->ipft_sz == sizeof(u_long))
7328				tu.ipft_vlong = *ta->ipft_plong;
7329			else if (ta->ipft_sz == sizeof(u_int))
7330				tu.ipft_vint = *ta->ipft_pint;
7331			else if (ta->ipft_sz == sizeof(u_short))
7332				tu.ipft_vshort = *ta->ipft_pshort;
7333			else if (ta->ipft_sz == sizeof(u_char))
7334				tu.ipft_vchar = *ta->ipft_pchar;
7335			tu.ipft_cookie = ta;
7336			tu.ipft_sz = ta->ipft_sz;
7337			tu.ipft_min = ta->ipft_min;
7338			tu.ipft_max = ta->ipft_max;
7339			tu.ipft_flags = ta->ipft_flags;
7340			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7341
7342		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7343			/*
7344			 * Set an internal parameter.  The hard part here is
7345			 * getting the new value safely and correctly out of
7346			 * the kernel (given we only know its size, not type.)
7347			 */
7348			u_long in;
7349
7350			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7351			    (softc->ipf_running > 0)) {
7352				IPFERROR(78);
7353				error = EBUSY;
7354				break;
7355			}
7356
7357			in = tu.ipft_vlong;
7358			if (in < ta->ipft_min || in > ta->ipft_max) {
7359				IPFERROR(79);
7360				error = EINVAL;
7361				break;
7362			}
7363
7364			if (ta->ipft_func != NULL) {
7365				SPL_INT(s);
7366
7367				SPL_NET(s);
7368				error = (*ta->ipft_func)(softc, ta,
7369							 &tu.ipft_un);
7370				SPL_X(s);
7371
7372			} else if (ta->ipft_sz == sizeof(u_long)) {
7373				tu.ipft_vlong = *ta->ipft_plong;
7374				*ta->ipft_plong = in;
7375
7376			} else if (ta->ipft_sz == sizeof(u_int)) {
7377				tu.ipft_vint = *ta->ipft_pint;
7378				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7379
7380			} else if (ta->ipft_sz == sizeof(u_short)) {
7381				tu.ipft_vshort = *ta->ipft_pshort;
7382				*ta->ipft_pshort = (u_short)(in & 0xffff);
7383
7384			} else if (ta->ipft_sz == sizeof(u_char)) {
7385				tu.ipft_vchar = *ta->ipft_pchar;
7386				*ta->ipft_pchar = (u_char)(in & 0xff);
7387			}
7388			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7389		}
7390		break;
7391
7392	default :
7393		IPFERROR(80);
7394		error = EINVAL;
7395		break;
7396	}
7397
7398	return error;
7399}
7400
7401
7402/* ------------------------------------------------------------------------ */
7403/* Function:    ipf_zerostats                                               */
7404/* Returns:     int - 0 = success, else failure                             */
7405/* Parameters:  data(O) - pointer to pointer for copying data back to       */
7406/*                                                                          */
7407/* Copies the current statistics out to userspace and then zero's the       */
7408/* current ones in the kernel. The lock is only held across the bzero() as  */
7409/* the copyout may result in paging (ie network activity.)                  */
7410/* ------------------------------------------------------------------------ */
7411int
7412ipf_zerostats(softc, data)
7413	ipf_main_softc_t *softc;
7414	caddr_t	data;
7415{
7416	friostat_t fio;
7417	ipfobj_t obj;
7418	int error;
7419
7420	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7421	if (error != 0)
7422		return error;
7423	ipf_getstat(softc, &fio, obj.ipfo_rev);
7424	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7425	if (error != 0)
7426		return error;
7427
7428	WRITE_ENTER(&softc->ipf_mutex);
7429	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7430	RWLOCK_EXIT(&softc->ipf_mutex);
7431
7432	return 0;
7433}
7434
7435
7436/* ------------------------------------------------------------------------ */
7437/* Function:    ipf_resolvedest                                             */
7438/* Returns:     Nil                                                         */
7439/* Parameters:  softc(I) - pointer to soft context main structure           */
7440/*              base(I)  - where strings are stored                         */
7441/*              fdp(IO)  - pointer to destination information to resolve    */
7442/*              v(I)     - IP protocol version to match                     */
7443/*                                                                          */
7444/* Looks up an interface name in the frdest structure pointed to by fdp and */
7445/* if a matching name can be found for the particular IP protocol version   */
7446/* then store the interface pointer in the frdest struct.  If no match is   */
7447/* found, then set the interface pointer to be -1 as NULL is considered to  */
7448/* indicate there is no information at all in the structure.                */
7449/* ------------------------------------------------------------------------ */
7450int
7451ipf_resolvedest(softc, base, fdp, v)
7452	ipf_main_softc_t *softc;
7453	char *base;
7454	frdest_t *fdp;
7455	int v;
7456{
7457	int errval = 0;
7458	void *ifp;
7459
7460	ifp = NULL;
7461
7462	if (fdp->fd_name != -1) {
7463		if (fdp->fd_type == FRD_DSTLIST) {
7464			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7465						  IPLT_DSTLIST,
7466						  base + fdp->fd_name,
7467						  NULL);
7468			if (ifp == NULL) {
7469				IPFERROR(144);
7470				errval = ESRCH;
7471			}
7472		} else {
7473			ifp = GETIFP(base + fdp->fd_name, v);
7474			if (ifp == NULL)
7475				ifp = (void *)-1;
7476		}
7477	}
7478	fdp->fd_ptr = ifp;
7479
7480	if ((ifp != NULL) && (ifp != (void *)-1)) {
7481		fdp->fd_local = ipf_deliverlocal(softc, v, ifp, &fdp->fd_ip6);
7482	}
7483
7484	return errval;
7485}
7486
7487
7488/* ------------------------------------------------------------------------ */
7489/* Function:    ipf_resolvenic                                              */
7490/* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7491/*                      pointer to interface structure for NIC              */
7492/* Parameters:  softc(I)- pointer to soft context main structure            */
7493/*              name(I) - complete interface name                           */
7494/*              v(I)    - IP protocol version                               */
7495/*                                                                          */
7496/* Look for a network interface structure that firstly has a matching name  */
7497/* to that passed in and that is also being used for that IP protocol       */
7498/* version (necessary on some platforms where there are separate listings   */
7499/* for both IPv4 and IPv6 on the same physical NIC.                         */
7500/* ------------------------------------------------------------------------ */
7501void *
7502ipf_resolvenic(softc, name, v)
7503	ipf_main_softc_t *softc;
7504	char *name;
7505	int v;
7506{
7507	void *nic;
7508
7509	softc = softc;	/* gcc -Wextra */
7510	if (name[0] == '\0')
7511		return NULL;
7512
7513	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7514		return NULL;
7515	}
7516
7517	nic = GETIFP(name, v);
7518	if (nic == NULL)
7519		nic = (void *)-1;
7520	return nic;
7521}
7522
7523
7524/* ------------------------------------------------------------------------ */
7525/* Function:    ipf_token_expire                                            */
7526/* Returns:     None.                                                       */
7527/* Parameters:  softc(I) - pointer to soft context main structure           */
7528/*                                                                          */
7529/* This function is run every ipf tick to see if there are any tokens that  */
7530/* have been held for too long and need to be freed up.                     */
7531/* ------------------------------------------------------------------------ */
7532void
7533ipf_token_expire(softc)
7534	ipf_main_softc_t *softc;
7535{
7536	ipftoken_t *it;
7537
7538	WRITE_ENTER(&softc->ipf_tokens);
7539	while ((it = softc->ipf_token_head) != NULL) {
7540		if (it->ipt_die > softc->ipf_ticks)
7541			break;
7542
7543		ipf_token_deref(softc, it);
7544	}
7545	RWLOCK_EXIT(&softc->ipf_tokens);
7546}
7547
7548
7549/* ------------------------------------------------------------------------ */
7550/* Function:    ipf_token_flush                                             */
7551/* Returns:     None.                                                       */
7552/* Parameters:  softc(I) - pointer to soft context main structure           */
7553/*                                                                          */
7554/* Loop through all of the existing tokens and call deref to see if they    */
7555/* can be freed. Normally a function like this might just loop on           */
7556/* ipf_token_head but there is a chance that a token might have a ref count */
7557/* of greater than one and in that case the the reference would drop twice  */
7558/* by code that is only entitled to drop it once.                           */
7559/* ------------------------------------------------------------------------ */
7560static void
7561ipf_token_flush(softc)
7562	ipf_main_softc_t *softc;
7563{
7564	ipftoken_t *it, *next;
7565
7566	WRITE_ENTER(&softc->ipf_tokens);
7567	for (it = softc->ipf_token_head; it != NULL; it = next) {
7568		next = it->ipt_next;
7569		(void) ipf_token_deref(softc, it);
7570	}
7571	RWLOCK_EXIT(&softc->ipf_tokens);
7572}
7573
7574
7575/* ------------------------------------------------------------------------ */
7576/* Function:    ipf_token_del                                               */
7577/* Returns:     int     - 0 = success, else error                           */
7578/* Parameters:  softc(I)- pointer to soft context main structure            */
7579/*              type(I) - the token type to match                           */
7580/*              uid(I)  - uid owning the token                              */
7581/*              ptr(I)  - context pointer for the token                     */
7582/*                                                                          */
7583/* This function looks for a a token in the current list that matches up    */
7584/* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7585/* call ipf_token_dewref() to remove it from the list. In the event that    */
7586/* the token has a reference held elsewhere, setting ipt_complete to 2      */
7587/* enables debugging to distinguish between the two paths that ultimately   */
7588/* lead to a token to be deleted.                                           */
7589/* ------------------------------------------------------------------------ */
7590int
7591ipf_token_del(softc, type, uid, ptr)
7592	ipf_main_softc_t *softc;
7593	int type, uid;
7594	void *ptr;
7595{
7596	ipftoken_t *it;
7597	int error;
7598
7599	IPFERROR(82);
7600	error = ESRCH;
7601
7602	WRITE_ENTER(&softc->ipf_tokens);
7603	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7604		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7605		    uid == it->ipt_uid) {
7606			it->ipt_complete = 2;
7607			ipf_token_deref(softc, it);
7608			error = 0;
7609			break;
7610		}
7611	}
7612	RWLOCK_EXIT(&softc->ipf_tokens);
7613
7614	return error;
7615}
7616
7617
7618/* ------------------------------------------------------------------------ */
7619/* Function:    ipf_token_mark_complete                                     */
7620/* Returns:     None.                                                       */
7621/* Parameters:  token(I) - pointer to token structure                       */
7622/*                                                                          */
7623/* Mark a token as being ineligable for being found with ipf_token_find.    */
7624/* ------------------------------------------------------------------------ */
7625void
7626ipf_token_mark_complete(token)
7627	ipftoken_t *token;
7628{
7629	if (token->ipt_complete == 0)
7630		token->ipt_complete = 1;
7631}
7632
7633
7634/* ------------------------------------------------------------------------ */
7635/* Function:    ipf_token_find                                               */
7636/* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7637/* Parameters:  softc(I)- pointer to soft context main structure            */
7638/*              type(I) - the token type to match                           */
7639/*              uid(I)  - uid owning the token                              */
7640/*              ptr(I)  - context pointer for the token                     */
7641/*                                                                          */
7642/* This function looks for a live token in the list of current tokens that  */
7643/* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7644/* allocated.  If one is found then it is moved to the top of the list of   */
7645/* currently active tokens.                                                 */
7646/* ------------------------------------------------------------------------ */
7647ipftoken_t *
7648ipf_token_find(softc, type, uid, ptr)
7649	ipf_main_softc_t *softc;
7650	int type, uid;
7651	void *ptr;
7652{
7653	ipftoken_t *it, *new;
7654
7655	KMALLOC(new, ipftoken_t *);
7656	if (new != NULL)
7657		bzero((char *)new, sizeof(*new));
7658
7659	WRITE_ENTER(&softc->ipf_tokens);
7660	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7661		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7662		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7663			break;
7664	}
7665
7666	if (it == NULL) {
7667		it = new;
7668		new = NULL;
7669		if (it == NULL) {
7670			RWLOCK_EXIT(&softc->ipf_tokens);
7671			return NULL;
7672		}
7673		it->ipt_ctx = ptr;
7674		it->ipt_uid = uid;
7675		it->ipt_type = type;
7676		it->ipt_ref = 1;
7677	} else {
7678		if (new != NULL) {
7679			KFREE(new);
7680			new = NULL;
7681		}
7682
7683		if (it->ipt_complete > 0)
7684			it = NULL;
7685		else
7686			ipf_token_unlink(softc, it);
7687	}
7688
7689	if (it != NULL) {
7690		it->ipt_pnext = softc->ipf_token_tail;
7691		*softc->ipf_token_tail = it;
7692		softc->ipf_token_tail = &it->ipt_next;
7693		it->ipt_next = NULL;
7694		it->ipt_ref++;
7695
7696		it->ipt_die = softc->ipf_ticks + 20;
7697	}
7698
7699	RWLOCK_EXIT(&softc->ipf_tokens);
7700
7701	return it;
7702}
7703
7704
7705/* ------------------------------------------------------------------------ */
7706/* Function:    ipf_token_unlink                                            */
7707/* Returns:     None.                                                       */
7708/* Parameters:  softc(I) - pointer to soft context main structure           */
7709/*              token(I) - pointer to token structure                       */
7710/* Write Locks: ipf_tokens                                                  */
7711/*                                                                          */
7712/* This function unlinks a token structure from the linked list of tokens   */
7713/* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7714/* but the tail does due to the linked list implementation.                 */
7715/* ------------------------------------------------------------------------ */
7716static void
7717ipf_token_unlink(softc, token)
7718	ipf_main_softc_t *softc;
7719	ipftoken_t *token;
7720{
7721
7722	if (softc->ipf_token_tail == &token->ipt_next)
7723		softc->ipf_token_tail = token->ipt_pnext;
7724
7725	*token->ipt_pnext = token->ipt_next;
7726	if (token->ipt_next != NULL)
7727		token->ipt_next->ipt_pnext = token->ipt_pnext;
7728	token->ipt_next = NULL;
7729	token->ipt_pnext = NULL;
7730}
7731
7732
7733/* ------------------------------------------------------------------------ */
7734/* Function:    ipf_token_deref                                             */
7735/* Returns:     int      - 0 == token freed, else reference count           */
7736/* Parameters:  softc(I) - pointer to soft context main structure           */
7737/*              token(I) - pointer to token structure                       */
7738/* Write Locks: ipf_tokens                                                  */
7739/*                                                                          */
7740/* Drop the reference count on the token structure and if it drops to zero, */
7741/* call the dereference function for the token type because it is then      */
7742/* possible to free the token data structure.                               */
7743/* ------------------------------------------------------------------------ */
7744int
7745ipf_token_deref(softc, token)
7746	ipf_main_softc_t *softc;
7747	ipftoken_t *token;
7748{
7749	void *data, **datap;
7750
7751	ASSERT(token->ipt_ref > 0);
7752	token->ipt_ref--;
7753	if (token->ipt_ref > 0)
7754		return token->ipt_ref;
7755
7756	data = token->ipt_data;
7757	datap = &data;
7758
7759	if ((data != NULL) && (data != (void *)-1)) {
7760		switch (token->ipt_type)
7761		{
7762		case IPFGENITER_IPF :
7763			(void) ipf_derefrule(softc, (frentry_t **)datap);
7764			break;
7765		case IPFGENITER_IPNAT :
7766			WRITE_ENTER(&softc->ipf_nat);
7767			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7768			RWLOCK_EXIT(&softc->ipf_nat);
7769			break;
7770		case IPFGENITER_NAT :
7771			ipf_nat_deref(softc, (nat_t **)datap);
7772			break;
7773		case IPFGENITER_STATE :
7774			ipf_state_deref(softc, (ipstate_t **)datap);
7775			break;
7776		case IPFGENITER_FRAG :
7777			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7778			break;
7779		case IPFGENITER_NATFRAG :
7780			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7781			break;
7782		case IPFGENITER_HOSTMAP :
7783			WRITE_ENTER(&softc->ipf_nat);
7784			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7785			RWLOCK_EXIT(&softc->ipf_nat);
7786			break;
7787		default :
7788			ipf_lookup_iterderef(softc, token->ipt_type, data);
7789			break;
7790		}
7791	}
7792
7793	ipf_token_unlink(softc, token);
7794	KFREE(token);
7795	return 0;
7796}
7797
7798
7799/* ------------------------------------------------------------------------ */
7800/* Function:    ipf_nextrule                                                */
7801/* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7802/* Parameters:  softc(I)    - pointer to soft context main structure        */
7803/*              fr(I)       - pointer to filter rule                        */
7804/*              out(I)      - 1 == out rules, 0 == input rules              */
7805/*                                                                          */
7806/* Starting with "fr", find the next rule to visit. This includes visiting  */
7807/* the list of rule groups if either fr is NULL (empty list) or it is the   */
7808/* last rule in the list. When walking rule lists, it is either input or    */
7809/* output rules that are returned, never both.                              */
7810/* ------------------------------------------------------------------------ */
7811static frentry_t *
7812ipf_nextrule(softc, active, unit, fr, out)
7813	ipf_main_softc_t *softc;
7814	int active, unit;
7815	frentry_t *fr;
7816	int out;
7817{
7818	frentry_t *next;
7819	frgroup_t *fg;
7820
7821	if (fr != NULL && fr->fr_group != -1) {
7822		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7823				   unit, active, NULL);
7824		if (fg != NULL)
7825			fg = fg->fg_next;
7826	} else {
7827		fg = softc->ipf_groups[unit][active];
7828	}
7829
7830	while (fg != NULL) {
7831		next = fg->fg_start;
7832		while (next != NULL) {
7833			if (out) {
7834				if (next->fr_flags & FR_OUTQUE)
7835					return next;
7836			} else if (next->fr_flags & FR_INQUE) {
7837				return next;
7838			}
7839			next = next->fr_next;
7840		}
7841		if (next == NULL)
7842			fg = fg->fg_next;
7843	}
7844
7845	return NULL;
7846}
7847
7848/* ------------------------------------------------------------------------ */
7849/* Function:    ipf_getnextrule                                             */
7850/* Returns:     int - 0 = success, else error                               */
7851/* Parameters:  softc(I)- pointer to soft context main structure            */
7852/*              t(I)   - pointer to destination information to resolve      */
7853/*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7854/*                                                                          */
7855/* This function's first job is to bring in the ipfruleiter_t structure via */
7856/* the ipfobj_t structure to determine what should be the next rule to      */
7857/* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7858/* find the 'next rule'.  This may include searching rule group lists or    */
7859/* just be as simple as looking at the 'next' field in the rule structure.  */
7860/* When we have found the rule to return, increase its reference count and  */
7861/* if we used an existing rule to get here, decrease its reference count.   */
7862/* ------------------------------------------------------------------------ */
7863int
7864ipf_getnextrule(softc, t, ptr)
7865	ipf_main_softc_t *softc;
7866	ipftoken_t *t;
7867	void *ptr;
7868{
7869	frentry_t *fr, *next, zero;
7870	ipfruleiter_t it;
7871	int error, out;
7872	frgroup_t *fg;
7873	ipfobj_t obj;
7874	int predict;
7875	char *dst;
7876	int unit;
7877
7878	if (t == NULL || ptr == NULL) {
7879		IPFERROR(84);
7880		return EFAULT;
7881	}
7882
7883	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7884	if (error != 0)
7885		return error;
7886
7887	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7888		IPFERROR(85);
7889		return EINVAL;
7890	}
7891	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7892		IPFERROR(86);
7893		return EINVAL;
7894	}
7895	if (it.iri_nrules == 0) {
7896		IPFERROR(87);
7897		return ENOSPC;
7898	}
7899	if (it.iri_rule == NULL) {
7900		IPFERROR(88);
7901		return EFAULT;
7902	}
7903
7904	fg = NULL;
7905	fr = t->ipt_data;
7906	if ((it.iri_inout & F_OUT) != 0)
7907		out = 1;
7908	else
7909		out = 0;
7910	if ((it.iri_inout & F_ACIN) != 0)
7911		unit = IPL_LOGCOUNT;
7912	else
7913		unit = IPL_LOGIPF;
7914
7915	READ_ENTER(&softc->ipf_mutex);
7916	if (fr == NULL) {
7917		if (*it.iri_group == '\0') {
7918			if (unit == IPL_LOGCOUNT) {
7919				next = softc->ipf_acct[out][it.iri_active];
7920			} else {
7921				next = softc->ipf_rules[out][it.iri_active];
7922			}
7923			if (next == NULL)
7924				next = ipf_nextrule(softc, it.iri_active,
7925						    unit, NULL, out);
7926		} else {
7927			fg = ipf_findgroup(softc, it.iri_group, unit,
7928					   it.iri_active, NULL);
7929			if (fg != NULL)
7930				next = fg->fg_start;
7931			else
7932				next = NULL;
7933		}
7934	} else {
7935		next = fr->fr_next;
7936		if (next == NULL)
7937			next = ipf_nextrule(softc, it.iri_active, unit,
7938					    fr, out);
7939	}
7940
7941	if (next != NULL && next->fr_next != NULL)
7942		predict = 1;
7943	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7944		predict = 1;
7945	else
7946		predict = 0;
7947
7948	if (fr != NULL)
7949		(void) ipf_derefrule(softc, &fr);
7950
7951	obj.ipfo_type = IPFOBJ_FRENTRY;
7952	dst = (char *)it.iri_rule;
7953
7954	if (next != NULL) {
7955		obj.ipfo_size = next->fr_size;
7956		MUTEX_ENTER(&next->fr_lock);
7957		next->fr_ref++;
7958		MUTEX_EXIT(&next->fr_lock);
7959		t->ipt_data = next;
7960	} else {
7961		obj.ipfo_size = sizeof(frentry_t);
7962		bzero(&zero, sizeof(zero));
7963		next = &zero;
7964		t->ipt_data = NULL;
7965	}
7966	it.iri_rule = predict ? next : NULL;
7967	if (predict == 0)
7968		ipf_token_mark_complete(t);
7969
7970	RWLOCK_EXIT(&softc->ipf_mutex);
7971
7972	obj.ipfo_ptr = dst;
7973	error = ipf_outobjk(softc, &obj, next);
7974	if (error == 0 && t->ipt_data != NULL) {
7975		dst += obj.ipfo_size;
7976		if (next->fr_data != NULL) {
7977			ipfobj_t dobj;
7978
7979			if (next->fr_type == FR_T_IPFEXPR)
7980				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7981			else
7982				dobj.ipfo_type = IPFOBJ_FRIPF;
7983			dobj.ipfo_size = next->fr_dsize;
7984			dobj.ipfo_rev = obj.ipfo_rev;
7985			dobj.ipfo_ptr = dst;
7986			error = ipf_outobjk(softc, &dobj, next->fr_data);
7987		}
7988	}
7989
7990	if ((fr != NULL) && (next == &zero))
7991		(void) ipf_derefrule(softc, &fr);
7992
7993	return error;
7994}
7995
7996
7997/* ------------------------------------------------------------------------ */
7998/* Function:    ipf_frruleiter                                              */
7999/* Returns:     int - 0 = success, else error                               */
8000/* Parameters:  softc(I)- pointer to soft context main structure            */
8001/*              data(I) - the token type to match                           */
8002/*              uid(I)  - uid owning the token                              */
8003/*              ptr(I)  - context pointer for the token                     */
8004/*                                                                          */
8005/* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8006/* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8007/* the process doing the ioctl and use that to ask for the next rule.       */
8008/* ------------------------------------------------------------------------ */
8009static int
8010ipf_frruleiter(softc, data, uid, ctx)
8011	ipf_main_softc_t *softc;
8012	void *data, *ctx;
8013	int uid;
8014{
8015	ipftoken_t *token;
8016	ipfruleiter_t it;
8017	ipfobj_t obj;
8018	int error;
8019
8020	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8021	if (token != NULL) {
8022		error = ipf_getnextrule(softc, token, data);
8023		WRITE_ENTER(&softc->ipf_tokens);
8024		ipf_token_deref(softc, token);
8025		RWLOCK_EXIT(&softc->ipf_tokens);
8026	} else {
8027		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8028		if (error != 0)
8029			return error;
8030		it.iri_rule = NULL;
8031		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8032	}
8033
8034	return error;
8035}
8036
8037
8038/* ------------------------------------------------------------------------ */
8039/* Function:    ipf_geniter                                                 */
8040/* Returns:     int - 0 = success, else error                               */
8041/* Parameters:  softc(I) - pointer to soft context main structure           */
8042/*              token(I) - pointer to ipftoken_t structure                  */
8043/*              itp(I)   - pointer to iterator data                         */
8044/*                                                                          */
8045/* Decide which iterator function to call using information passed through  */
8046/* the ipfgeniter_t structure at itp.                                       */
8047/* ------------------------------------------------------------------------ */
8048static int
8049ipf_geniter(softc, token, itp)
8050	ipf_main_softc_t *softc;
8051	ipftoken_t *token;
8052	ipfgeniter_t *itp;
8053{
8054	int error;
8055
8056	switch (itp->igi_type)
8057	{
8058	case IPFGENITER_FRAG :
8059		error = ipf_frag_pkt_next(softc, token, itp);
8060		break;
8061	default :
8062		IPFERROR(92);
8063		error = EINVAL;
8064		break;
8065	}
8066
8067	return error;
8068}
8069
8070
8071/* ------------------------------------------------------------------------ */
8072/* Function:    ipf_genericiter                                             */
8073/* Returns:     int - 0 = success, else error                               */
8074/* Parameters:  softc(I)- pointer to soft context main structure            */
8075/*              data(I) - the token type to match                           */
8076/*              uid(I)  - uid owning the token                              */
8077/*              ptr(I)  - context pointer for the token                     */
8078/*                                                                          */
8079/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8080/* ------------------------------------------------------------------------ */
8081int
8082ipf_genericiter(softc, data, uid, ctx)
8083	ipf_main_softc_t *softc;
8084	void *data, *ctx;
8085	int uid;
8086{
8087	ipftoken_t *token;
8088	ipfgeniter_t iter;
8089	int error;
8090
8091	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8092	if (error != 0)
8093		return error;
8094
8095	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8096	if (token != NULL) {
8097		token->ipt_subtype = iter.igi_type;
8098		error = ipf_geniter(softc, token, &iter);
8099		WRITE_ENTER(&softc->ipf_tokens);
8100		ipf_token_deref(softc, token);
8101		RWLOCK_EXIT(&softc->ipf_tokens);
8102	} else {
8103		IPFERROR(93);
8104		error = 0;
8105	}
8106
8107	return error;
8108}
8109
8110
8111/* ------------------------------------------------------------------------ */
8112/* Function:    ipf_ipf_ioctl                                               */
8113/* Returns:     int - 0 = success, else error                               */
8114/* Parameters:  softc(I)- pointer to soft context main structure           */
8115/*              data(I) - the token type to match                           */
8116/*              cmd(I)  - the ioctl command number                          */
8117/*              mode(I) - mode flags for the ioctl                          */
8118/*              uid(I)  - uid owning the token                              */
8119/*              ptr(I)  - context pointer for the token                     */
8120/*                                                                          */
8121/* This function handles all of the ioctl command that are actually isssued */
8122/* to the /dev/ipl device.                                                  */
8123/* ------------------------------------------------------------------------ */
8124int
8125ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8126	ipf_main_softc_t *softc;
8127	caddr_t data;
8128	ioctlcmd_t cmd;
8129	int mode, uid;
8130	void *ctx;
8131{
8132	friostat_t fio;
8133	int error, tmp;
8134	ipfobj_t obj;
8135	SPL_INT(s);
8136
8137	switch (cmd)
8138	{
8139	case SIOCFRENB :
8140		if (!(mode & FWRITE)) {
8141			IPFERROR(94);
8142			error = EPERM;
8143		} else {
8144			error = BCOPYIN(data, &tmp, sizeof(tmp));
8145			if (error != 0) {
8146				IPFERROR(95);
8147				error = EFAULT;
8148				break;
8149			}
8150
8151			WRITE_ENTER(&softc->ipf_global);
8152			if (tmp) {
8153				if (softc->ipf_running > 0)
8154					error = 0;
8155				else
8156					error = ipfattach(softc);
8157				if (error == 0)
8158					softc->ipf_running = 1;
8159				else
8160					(void) ipfdetach(softc);
8161			} else {
8162				if (softc->ipf_running == 1)
8163					error = ipfdetach(softc);
8164				else
8165					error = 0;
8166				if (error == 0)
8167					softc->ipf_running = -1;
8168			}
8169			RWLOCK_EXIT(&softc->ipf_global);
8170		}
8171		break;
8172
8173	case SIOCIPFSET :
8174		if (!(mode & FWRITE)) {
8175			IPFERROR(96);
8176			error = EPERM;
8177			break;
8178		}
8179		/* FALLTHRU */
8180	case SIOCIPFGETNEXT :
8181	case SIOCIPFGET :
8182		error = ipf_ipftune(softc, cmd, (void *)data);
8183		break;
8184
8185	case SIOCSETFF :
8186		if (!(mode & FWRITE)) {
8187			IPFERROR(97);
8188			error = EPERM;
8189		} else {
8190			error = BCOPYIN(data, &softc->ipf_flags,
8191					sizeof(softc->ipf_flags));
8192			if (error != 0) {
8193				IPFERROR(98);
8194				error = EFAULT;
8195			}
8196		}
8197		break;
8198
8199	case SIOCGETFF :
8200		error = BCOPYOUT(&softc->ipf_flags, data,
8201				 sizeof(softc->ipf_flags));
8202		if (error != 0) {
8203			IPFERROR(99);
8204			error = EFAULT;
8205		}
8206		break;
8207
8208	case SIOCFUNCL :
8209		error = ipf_resolvefunc(softc, (void *)data);
8210		break;
8211
8212	case SIOCINAFR :
8213	case SIOCRMAFR :
8214	case SIOCADAFR :
8215	case SIOCZRLST :
8216		if (!(mode & FWRITE)) {
8217			IPFERROR(100);
8218			error = EPERM;
8219		} else {
8220			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8221					  softc->ipf_active, 1);
8222		}
8223		break;
8224
8225	case SIOCINIFR :
8226	case SIOCRMIFR :
8227	case SIOCADIFR :
8228		if (!(mode & FWRITE)) {
8229			IPFERROR(101);
8230			error = EPERM;
8231		} else {
8232			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8233					  1 - softc->ipf_active, 1);
8234		}
8235		break;
8236
8237	case SIOCSWAPA :
8238		if (!(mode & FWRITE)) {
8239			IPFERROR(102);
8240			error = EPERM;
8241		} else {
8242			WRITE_ENTER(&softc->ipf_mutex);
8243			error = BCOPYOUT(&softc->ipf_active, data,
8244					 sizeof(softc->ipf_active));
8245			if (error != 0) {
8246				IPFERROR(103);
8247				error = EFAULT;
8248			} else {
8249				softc->ipf_active = 1 - softc->ipf_active;
8250			}
8251			RWLOCK_EXIT(&softc->ipf_mutex);
8252		}
8253		break;
8254
8255	case SIOCGETFS :
8256		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8257				  IPFOBJ_IPFSTAT);
8258		if (error != 0)
8259			break;
8260		ipf_getstat(softc, &fio, obj.ipfo_rev);
8261		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8262		break;
8263
8264	case SIOCFRZST :
8265		if (!(mode & FWRITE)) {
8266			IPFERROR(104);
8267			error = EPERM;
8268		} else
8269			error = ipf_zerostats(softc, (caddr_t)data);
8270		break;
8271
8272	case SIOCIPFFL :
8273		if (!(mode & FWRITE)) {
8274			IPFERROR(105);
8275			error = EPERM;
8276		} else {
8277			error = BCOPYIN(data, &tmp, sizeof(tmp));
8278			if (!error) {
8279				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8280				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8281				if (error != 0) {
8282					IPFERROR(106);
8283					error = EFAULT;
8284				}
8285			} else {
8286				IPFERROR(107);
8287				error = EFAULT;
8288			}
8289		}
8290		break;
8291
8292#ifdef USE_INET6
8293	case SIOCIPFL6 :
8294		if (!(mode & FWRITE)) {
8295			IPFERROR(108);
8296			error = EPERM;
8297		} else {
8298			error = BCOPYIN(data, &tmp, sizeof(tmp));
8299			if (!error) {
8300				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8301				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8302				if (error != 0) {
8303					IPFERROR(109);
8304					error = EFAULT;
8305				}
8306			} else {
8307				IPFERROR(110);
8308				error = EFAULT;
8309			}
8310		}
8311		break;
8312#endif
8313
8314	case SIOCSTLCK :
8315		if (!(mode & FWRITE)) {
8316			IPFERROR(122);
8317			error = EPERM;
8318		} else {
8319			error = BCOPYIN(data, &tmp, sizeof(tmp));
8320			if (error == 0) {
8321				ipf_state_setlock(softc->ipf_state_soft, tmp);
8322				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8323				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8324				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8325			} else {
8326				IPFERROR(111);
8327				error = EFAULT;
8328			}
8329		}
8330		break;
8331
8332#ifdef	IPFILTER_LOG
8333	case SIOCIPFFB :
8334		if (!(mode & FWRITE)) {
8335			IPFERROR(112);
8336			error = EPERM;
8337		} else {
8338			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8339			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8340			if (error) {
8341				IPFERROR(113);
8342				error = EFAULT;
8343			}
8344		}
8345		break;
8346#endif /* IPFILTER_LOG */
8347
8348	case SIOCFRSYN :
8349		if (!(mode & FWRITE)) {
8350			IPFERROR(114);
8351			error = EPERM;
8352		} else {
8353			WRITE_ENTER(&softc->ipf_global);
8354#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8355			error = ipfsync();
8356#else
8357			ipf_sync(softc, NULL);
8358			error = 0;
8359#endif
8360			RWLOCK_EXIT(&softc->ipf_global);
8361
8362		}
8363		break;
8364
8365	case SIOCGFRST :
8366		error = ipf_outobj(softc, (void *)data,
8367				   ipf_frag_stats(softc->ipf_frag_soft),
8368				   IPFOBJ_FRAGSTAT);
8369		break;
8370
8371#ifdef	IPFILTER_LOG
8372	case FIONREAD :
8373		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8374		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8375		break;
8376#endif
8377
8378	case SIOCIPFITER :
8379		SPL_SCHED(s);
8380		error = ipf_frruleiter(softc, data, uid, ctx);
8381		SPL_X(s);
8382		break;
8383
8384	case SIOCGENITER :
8385		SPL_SCHED(s);
8386		error = ipf_genericiter(softc, data, uid, ctx);
8387		SPL_X(s);
8388		break;
8389
8390	case SIOCIPFDELTOK :
8391		error = BCOPYIN(data, &tmp, sizeof(tmp));
8392		if (error == 0) {
8393			SPL_SCHED(s);
8394			error = ipf_token_del(softc, tmp, uid, ctx);
8395			SPL_X(s);
8396		}
8397		break;
8398
8399	default :
8400		IPFERROR(115);
8401		error = EINVAL;
8402		break;
8403	}
8404
8405	return error;
8406}
8407
8408
8409/* ------------------------------------------------------------------------ */
8410/* Function:    ipf_decaps                                                  */
8411/* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8412/*                           flags indicating packet filtering decision.    */
8413/* Parameters:  fin(I)     - pointer to packet information                  */
8414/*              pass(I)    - IP protocol version to match                   */
8415/*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8416/*                                                                          */
8417/* This function is called for packets that are wrapt up in other packets,  */
8418/* for example, an IP packet that is the entire data segment for another IP */
8419/* packet.  If the basic constraints for this are satisfied, change the     */
8420/* buffer to point to the start of the inner packet and start processing    */
8421/* rules belonging to the head group this rule specifies.                   */
8422/* ------------------------------------------------------------------------ */
8423u_32_t
8424ipf_decaps(fin, pass, l5proto)
8425	fr_info_t *fin;
8426	u_32_t pass;
8427	int l5proto;
8428{
8429	fr_info_t fin2, *fino = NULL;
8430	int elen, hlen, nh;
8431	grehdr_t gre;
8432	ip_t *ip;
8433	mb_t *m;
8434
8435	if ((fin->fin_flx & FI_COALESCE) == 0)
8436		if (ipf_coalesce(fin) == -1)
8437			goto cantdecaps;
8438
8439	m = fin->fin_m;
8440	hlen = fin->fin_hlen;
8441
8442	switch (fin->fin_p)
8443	{
8444	case IPPROTO_UDP :
8445		/*
8446		 * In this case, the specific protocol being decapsulated
8447		 * inside UDP frames comes from the rule.
8448		 */
8449		nh = fin->fin_fr->fr_icode;
8450		break;
8451
8452	case IPPROTO_GRE :	/* 47 */
8453		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8454		hlen += sizeof(grehdr_t);
8455		if (gre.gr_R|gre.gr_s)
8456			goto cantdecaps;
8457		if (gre.gr_C)
8458			hlen += 4;
8459		if (gre.gr_K)
8460			hlen += 4;
8461		if (gre.gr_S)
8462			hlen += 4;
8463
8464		nh = IPPROTO_IP;
8465
8466		/*
8467		 * If the routing options flag is set, validate that it is
8468		 * there and bounce over it.
8469		 */
8470#if 0
8471		/* This is really heavy weight and lots of room for error, */
8472		/* so for now, put it off and get the simple stuff right.  */
8473		if (gre.gr_R) {
8474			u_char off, len, *s;
8475			u_short af;
8476			int end;
8477
8478			end = 0;
8479			s = fin->fin_dp;
8480			s += hlen;
8481			aplen = fin->fin_plen - hlen;
8482			while (aplen > 3) {
8483				af = (s[0] << 8) | s[1];
8484				off = s[2];
8485				len = s[3];
8486				aplen -= 4;
8487				s += 4;
8488				if (af == 0 && len == 0) {
8489					end = 1;
8490					break;
8491				}
8492				if (aplen < len)
8493					break;
8494				s += len;
8495				aplen -= len;
8496			}
8497			if (end != 1)
8498				goto cantdecaps;
8499			hlen = s - (u_char *)fin->fin_dp;
8500		}
8501#endif
8502		break;
8503
8504#ifdef IPPROTO_IPIP
8505	case IPPROTO_IPIP :	/* 4 */
8506#endif
8507		nh = IPPROTO_IP;
8508		break;
8509
8510	default :	/* Includes ESP, AH is special for IPv4 */
8511		goto cantdecaps;
8512	}
8513
8514	switch (nh)
8515	{
8516	case IPPROTO_IP :
8517	case IPPROTO_IPV6 :
8518		break;
8519	default :
8520		goto cantdecaps;
8521	}
8522
8523	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8524	fino = fin;
8525	fin = &fin2;
8526	elen = hlen;
8527#if defined(MENTAT) && defined(_KERNEL)
8528	m->b_rptr += elen;
8529#else
8530	m->m_data += elen;
8531	m->m_len -= elen;
8532#endif
8533	fin->fin_plen -= elen;
8534
8535	ip = (ip_t *)((char *)fin->fin_ip + elen);
8536
8537	/*
8538	 * Make sure we have at least enough data for the network layer
8539	 * header.
8540	 */
8541	if (IP_V(ip) == 4)
8542		hlen = IP_HL(ip) << 2;
8543#ifdef USE_INET6
8544	else if (IP_V(ip) == 6)
8545		hlen = sizeof(ip6_t);
8546#endif
8547	else
8548		goto cantdecaps2;
8549
8550	if (fin->fin_plen < hlen)
8551		goto cantdecaps2;
8552
8553	fin->fin_dp = (char *)ip + hlen;
8554
8555	if (IP_V(ip) == 4) {
8556		/*
8557		 * Perform IPv4 header checksum validation.
8558		 */
8559		if (ipf_cksum((u_short *)ip, hlen))
8560			goto cantdecaps2;
8561	}
8562
8563	if (ipf_makefrip(hlen, ip, fin) == -1) {
8564cantdecaps2:
8565		if (m != NULL) {
8566#if defined(MENTAT) && defined(_KERNEL)
8567			m->b_rptr -= elen;
8568#else
8569			m->m_data -= elen;
8570			m->m_len += elen;
8571#endif
8572		}
8573cantdecaps:
8574		DT1(frb_decapfrip, fr_info_t *, fin);
8575		pass &= ~FR_CMDMASK;
8576		pass |= FR_BLOCK|FR_QUICK;
8577		fin->fin_reason = FRB_DECAPFRIP;
8578		return -1;
8579	}
8580
8581	pass = ipf_scanlist(fin, pass);
8582
8583	/*
8584	 * Copy the packet filter "result" fields out of the fr_info_t struct
8585	 * that is local to the decapsulation processing and back into the
8586	 * one we were called with.
8587	 */
8588	fino->fin_flx = fin->fin_flx;
8589	fino->fin_rev = fin->fin_rev;
8590	fino->fin_icode = fin->fin_icode;
8591	fino->fin_rule = fin->fin_rule;
8592	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8593	fino->fin_fr = fin->fin_fr;
8594	fino->fin_error = fin->fin_error;
8595	fino->fin_mp = fin->fin_mp;
8596	fino->fin_m = fin->fin_m;
8597	m = fin->fin_m;
8598	if (m != NULL) {
8599#if defined(MENTAT) && defined(_KERNEL)
8600		m->b_rptr -= elen;
8601#else
8602		m->m_data -= elen;
8603		m->m_len += elen;
8604#endif
8605	}
8606	return pass;
8607}
8608
8609
8610/* ------------------------------------------------------------------------ */
8611/* Function:    ipf_matcharray_load                                         */
8612/* Returns:     int         - 0 = success, else error                       */
8613/* Parameters:  softc(I)    - pointer to soft context main structure        */
8614/*              data(I)     - pointer to ioctl data                         */
8615/*              objp(I)     - ipfobj_t structure to load data into          */
8616/*              arrayptr(I) - pointer to location to store array pointer    */
8617/*                                                                          */
8618/* This function loads in a mathing array through the ipfobj_t struct that  */
8619/* describes it.  Sanity checking and array size limitations are enforced   */
8620/* in this function to prevent userspace from trying to load in something   */
8621/* that is insanely big.  Once the size of the array is known, the memory   */
8622/* required is malloc'd and returned through changing *arrayptr.  The       */
8623/* contents of the array are verified before returning.  Only in the event  */
8624/* of a successful call is the caller required to free up the malloc area.  */
8625/* ------------------------------------------------------------------------ */
8626int
8627ipf_matcharray_load(softc, data, objp, arrayptr)
8628	ipf_main_softc_t *softc;
8629	caddr_t data;
8630	ipfobj_t *objp;
8631	int **arrayptr;
8632{
8633	int arraysize, *array, error;
8634
8635	*arrayptr = NULL;
8636
8637	error = BCOPYIN(data, objp, sizeof(*objp));
8638	if (error != 0) {
8639		IPFERROR(116);
8640		return EFAULT;
8641	}
8642
8643	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8644		IPFERROR(117);
8645		return EINVAL;
8646	}
8647
8648	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8649	    (objp->ipfo_size > 1024)) {
8650		IPFERROR(118);
8651		return EINVAL;
8652	}
8653
8654	arraysize = objp->ipfo_size * sizeof(*array);
8655	KMALLOCS(array, int *, arraysize);
8656	if (array == NULL) {
8657		IPFERROR(119);
8658		return ENOMEM;
8659	}
8660
8661	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8662	if (error != 0) {
8663		KFREES(array, arraysize);
8664		IPFERROR(120);
8665		return EFAULT;
8666	}
8667
8668	if (ipf_matcharray_verify(array, arraysize) != 0) {
8669		KFREES(array, arraysize);
8670		IPFERROR(121);
8671		return EINVAL;
8672	}
8673
8674	*arrayptr = array;
8675	return 0;
8676}
8677
8678
8679/* ------------------------------------------------------------------------ */
8680/* Function:    ipf_matcharray_verify                                       */
8681/* Returns:     Nil                                                         */
8682/* Parameters:  array(I)     - pointer to matching array                    */
8683/*              arraysize(I) - number of elements in the array              */
8684/*                                                                          */
8685/* Verify the contents of a matching array by stepping through each element */
8686/* in it.  The actual commands in the array are not verified for            */
8687/* correctness, only that all of the sizes are correctly within limits.     */
8688/* ------------------------------------------------------------------------ */
8689int
8690ipf_matcharray_verify(array, arraysize)
8691	int *array, arraysize;
8692{
8693	int i, nelem, maxidx;
8694	ipfexp_t *e;
8695
8696	nelem = arraysize / sizeof(*array);
8697
8698	/*
8699	 * Currently, it makes no sense to have an array less than 6
8700	 * elements long - the initial size at the from, a single operation
8701	 * (minimum 4 in length) and a trailer, for a total of 6.
8702	 */
8703	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8704		return -1;
8705	}
8706
8707	/*
8708	 * Verify the size of data pointed to by array with how long
8709	 * the array claims to be itself.
8710	 */
8711	if (array[0] * sizeof(*array) != arraysize) {
8712		return -1;
8713	}
8714
8715	maxidx = nelem - 1;
8716	/*
8717	 * The last opcode in this array should be an IPF_EXP_END.
8718	 */
8719	if (array[maxidx] != IPF_EXP_END) {
8720		return -1;
8721	}
8722
8723	for (i = 1; i < maxidx; ) {
8724		e = (ipfexp_t *)(array + i);
8725
8726		/*
8727		 * The length of the bits to check must be at least 1
8728		 * (or else there is nothing to comapre with!) and it
8729		 * cannot exceed the length of the data present.
8730		 */
8731		if ((e->ipfe_size < 1 ) ||
8732		    (e->ipfe_size + i > maxidx)) {
8733			return -1;
8734		}
8735		i += e->ipfe_size;
8736	}
8737	return 0;
8738}
8739
8740
8741/* ------------------------------------------------------------------------ */
8742/* Function:    ipf_fr_matcharray                                           */
8743/* Returns:     int      - 0 = match failed, else positive match            */
8744/* Parameters:  fin(I)   - pointer to packet information                    */
8745/*              array(I) - pointer to matching array                        */
8746/*                                                                          */
8747/* This function is used to apply a matching array against a packet and     */
8748/* return an indication of whether or not the packet successfully matches   */
8749/* all of the commands in it.                                               */
8750/* ------------------------------------------------------------------------ */
8751static int
8752ipf_fr_matcharray(fin, array)
8753	fr_info_t *fin;
8754	int *array;
8755{
8756	int i, n, *x, rv, p;
8757	ipfexp_t *e;
8758
8759	rv = 0;
8760	n = array[0];
8761	x = array + 1;
8762
8763	for (; n > 0; x += 3 + x[3], rv = 0) {
8764		e = (ipfexp_t *)x;
8765		if (e->ipfe_cmd == IPF_EXP_END)
8766			break;
8767		n -= e->ipfe_size;
8768
8769		/*
8770		 * The upper 16 bits currently store the protocol value.
8771		 * This is currently used with TCP and UDP port compares and
8772		 * allows "tcp.port = 80" without requiring an explicit
8773		 " "ip.pr = tcp" first.
8774		 */
8775		p = e->ipfe_cmd >> 16;
8776		if ((p != 0) && (p != fin->fin_p))
8777			break;
8778
8779		switch (e->ipfe_cmd)
8780		{
8781		case IPF_EXP_IP_PR :
8782			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8783				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8784			}
8785			break;
8786
8787		case IPF_EXP_IP_SRCADDR :
8788			if (fin->fin_v != 4)
8789				break;
8790			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8791				rv |= ((fin->fin_saddr &
8792					e->ipfe_arg0[i * 2 + 1]) ==
8793				       e->ipfe_arg0[i * 2]);
8794			}
8795			break;
8796
8797		case IPF_EXP_IP_DSTADDR :
8798			if (fin->fin_v != 4)
8799				break;
8800			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8801				rv |= ((fin->fin_daddr &
8802					e->ipfe_arg0[i * 2 + 1]) ==
8803				       e->ipfe_arg0[i * 2]);
8804			}
8805			break;
8806
8807		case IPF_EXP_IP_ADDR :
8808			if (fin->fin_v != 4)
8809				break;
8810			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8811				rv |= ((fin->fin_saddr &
8812					e->ipfe_arg0[i * 2 + 1]) ==
8813				       e->ipfe_arg0[i * 2]) ||
8814				      ((fin->fin_daddr &
8815					e->ipfe_arg0[i * 2 + 1]) ==
8816				       e->ipfe_arg0[i * 2]);
8817			}
8818			break;
8819
8820#ifdef USE_INET6
8821		case IPF_EXP_IP6_SRCADDR :
8822			if (fin->fin_v != 6)
8823				break;
8824			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8825				rv |= IP6_MASKEQ(&fin->fin_src6,
8826						 &e->ipfe_arg0[i * 8 + 4],
8827						 &e->ipfe_arg0[i * 8]);
8828			}
8829			break;
8830
8831		case IPF_EXP_IP6_DSTADDR :
8832			if (fin->fin_v != 6)
8833				break;
8834			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8835				rv |= IP6_MASKEQ(&fin->fin_dst6,
8836						 &e->ipfe_arg0[i * 8 + 4],
8837						 &e->ipfe_arg0[i * 8]);
8838			}
8839			break;
8840
8841		case IPF_EXP_IP6_ADDR :
8842			if (fin->fin_v != 6)
8843				break;
8844			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8845				rv |= IP6_MASKEQ(&fin->fin_src6,
8846						 &e->ipfe_arg0[i * 8 + 4],
8847						 &e->ipfe_arg0[i * 8]) ||
8848				      IP6_MASKEQ(&fin->fin_dst6,
8849						 &e->ipfe_arg0[i * 8 + 4],
8850						 &e->ipfe_arg0[i * 8]);
8851			}
8852			break;
8853#endif
8854
8855		case IPF_EXP_UDP_PORT :
8856		case IPF_EXP_TCP_PORT :
8857			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8858				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8859				      (fin->fin_dport == e->ipfe_arg0[i]);
8860			}
8861			break;
8862
8863		case IPF_EXP_UDP_SPORT :
8864		case IPF_EXP_TCP_SPORT :
8865			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8866				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8867			}
8868			break;
8869
8870		case IPF_EXP_UDP_DPORT :
8871		case IPF_EXP_TCP_DPORT :
8872			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8873				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8874			}
8875			break;
8876
8877		case IPF_EXP_TCP_FLAGS :
8878			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8879				rv |= ((fin->fin_tcpf &
8880					e->ipfe_arg0[i * 2 + 1]) ==
8881				       e->ipfe_arg0[i * 2]);
8882			}
8883			break;
8884		}
8885		rv ^= e->ipfe_not;
8886
8887		if (rv == 0)
8888			break;
8889	}
8890
8891	return rv;
8892}
8893
8894
8895/* ------------------------------------------------------------------------ */
8896/* Function:    ipf_queueflush                                              */
8897/* Returns:     int - number of entries flushed (0 = none)                  */
8898/* Parameters:  softc(I)    - pointer to soft context main structure        */
8899/*              deletefn(I) - function to call to delete entry              */
8900/*              ipfqs(I)    - top of the list of ipf internal queues        */
8901/*              userqs(I)   - top of the list of user defined timeouts      */
8902/*                                                                          */
8903/* This fucntion gets called when the state/NAT hash tables fill up and we  */
8904/* need to try a bit harder to free up some space.  The algorithm used here */
8905/* split into two parts but both halves have the same goal: to reduce the   */
8906/* number of connections considered to be "active" to the low watermark.    */
8907/* There are two steps in doing this:                                       */
8908/* 1) Remove any TCP connections that are already considered to be "closed" */
8909/*    but have not yet been removed from the state table.  The two states   */
8910/*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8911/*    candidates for this style of removal.  If freeing up entries in       */
8912/*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8913/*    we do not go on to step 2.                                            */
8914/*                                                                          */
8915/* 2) Look for the oldest entries on each timeout queue and free them if    */
8916/*    they are within the given window we are considering.  Where the       */
8917/*    window starts and the steps taken to increase its size depend upon    */
8918/*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8919/*    last 30 seconds is not touched.                                       */
8920/*                                              touched                     */
8921/*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8922/*           |          |        |           |     |     |                  */
8923/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8924/*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8925/*                                                                          */
8926/* Points to note:                                                          */
8927/* - tqe_die is the time, in the future, when entries die.                  */
8928/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8929/*   ticks.                                                                 */
8930/* - tqe_touched is when the entry was last used by NAT/state               */
8931/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8932/*   ipf_ticks any given timeout queue and vice versa.                      */
8933/* - both tqe_die and tqe_touched increase over time                        */
8934/* - timeout queues are sorted with the highest value of tqe_die at the     */
8935/*   bottom and therefore the smallest values of each are at the top        */
8936/* - the pointer passed in as ipfqs should point to an array of timeout     */
8937/*   queues representing each of the TCP states                             */
8938/*                                                                          */
8939/* We start by setting up a maximum range to scan for things to move of     */
8940/* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8941/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8942/* we start again with a new value for "iend" and "istart".  This is        */
8943/* continued until we either finish the scan of 30 second intervals or the  */
8944/* low water mark is reached.                                               */
8945/* ------------------------------------------------------------------------ */
8946int
8947ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8948	ipf_main_softc_t *softc;
8949	ipftq_delete_fn_t deletefn;
8950	ipftq_t *ipfqs, *userqs;
8951	u_int *activep;
8952	int size, low;
8953{
8954	u_long interval, istart, iend;
8955	ipftq_t *ifq, *ifqnext;
8956	ipftqent_t *tqe, *tqn;
8957	int removed = 0;
8958
8959	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8960		tqn = tqe->tqe_next;
8961		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8962			removed++;
8963	}
8964	if ((*activep * 100 / size) > low) {
8965		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8966		     ((tqe = tqn) != NULL); ) {
8967			tqn = tqe->tqe_next;
8968			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8969				removed++;
8970		}
8971	}
8972
8973	if ((*activep * 100 / size) <= low) {
8974		return removed;
8975	}
8976
8977	/*
8978	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8979	 *       used then the operations are upgraded to floating point
8980	 *       and kernels don't like floating point...
8981	 */
8982	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8983		istart = IPF_TTLVAL(86400 * 4);
8984		interval = IPF_TTLVAL(43200);
8985	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8986		istart = IPF_TTLVAL(43200);
8987		interval = IPF_TTLVAL(1800);
8988	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8989		istart = IPF_TTLVAL(1800);
8990		interval = IPF_TTLVAL(30);
8991	} else {
8992		return 0;
8993	}
8994	if (istart > softc->ipf_ticks) {
8995		if (softc->ipf_ticks - interval < interval)
8996			istart = interval;
8997		else
8998			istart = (softc->ipf_ticks / interval) * interval;
8999	}
9000
9001	iend = softc->ipf_ticks - interval;
9002
9003	while ((*activep * 100 / size) > low) {
9004		u_long try;
9005
9006		try = softc->ipf_ticks - istart;
9007
9008		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9009			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9010				if (try < tqe->tqe_touched)
9011					break;
9012				tqn = tqe->tqe_next;
9013				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9014					removed++;
9015			}
9016		}
9017
9018		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9019			ifqnext = ifq->ifq_next;
9020
9021			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9022				if (try < tqe->tqe_touched)
9023					break;
9024				tqn = tqe->tqe_next;
9025				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9026					removed++;
9027			}
9028		}
9029
9030		if (try >= iend) {
9031			if (interval == IPF_TTLVAL(43200)) {
9032				interval = IPF_TTLVAL(1800);
9033			} else if (interval == IPF_TTLVAL(1800)) {
9034				interval = IPF_TTLVAL(30);
9035			} else {
9036				break;
9037			}
9038			if (interval >= softc->ipf_ticks)
9039				break;
9040
9041			iend = softc->ipf_ticks - interval;
9042		}
9043		istart -= interval;
9044	}
9045
9046	return removed;
9047}
9048
9049
9050/* ------------------------------------------------------------------------ */
9051/* Function:    ipf_deliverlocal                                            */
9052/* Returns:     int - 1 = local address, 0 = non-local address              */
9053/* Parameters:  softc(I)     - pointer to soft context main structure       */
9054/*              ipversion(I) - IP protocol version (4 or 6)                 */
9055/*              ifp(I)       - network interface pointer                    */
9056/*              ipaddr(I)    - IPv4/6 destination address                   */
9057/*                                                                          */
9058/* This fucntion is used to determine in the address "ipaddr" belongs to    */
9059/* the network interface represented by ifp.                                */
9060/* ------------------------------------------------------------------------ */
9061int
9062ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9063	ipf_main_softc_t *softc;
9064	int ipversion;
9065	void *ifp;
9066	i6addr_t *ipaddr;
9067{
9068	i6addr_t addr;
9069	int islocal = 0;
9070
9071	if (ipversion == 4) {
9072		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9073			if (addr.in4.s_addr == ipaddr->in4.s_addr)
9074				islocal = 1;
9075		}
9076
9077#ifdef USE_INET6
9078	} else if (ipversion == 6) {
9079		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9080			if (IP6_EQ(&addr, ipaddr))
9081				islocal = 1;
9082		}
9083#endif
9084	}
9085
9086	return islocal;
9087}
9088
9089
9090/* ------------------------------------------------------------------------ */
9091/* Function:    ipf_settimeout                                              */
9092/* Returns:     int - 0 = success, -1 = failure                             */
9093/* Parameters:  softc(I) - pointer to soft context main structure           */
9094/*              t(I)     - pointer to tuneable array entry                  */
9095/*              p(I)     - pointer to values passed in to apply             */
9096/*                                                                          */
9097/* This function is called to set the timeout values for each distinct      */
9098/* queue timeout that is available.  When called, it calls into both the    */
9099/* state and NAT code, telling them to update their timeout queues.         */
9100/* ------------------------------------------------------------------------ */
9101static int
9102ipf_settimeout(softc, t, p)
9103	struct ipf_main_softc_s *softc;
9104	ipftuneable_t *t;
9105	ipftuneval_t *p;
9106{
9107
9108	/*
9109	 * ipf_interror should be set by the functions called here, not
9110	 * by this function - it's just a middle man.
9111	 */
9112	if (ipf_state_settimeout(softc, t, p) == -1)
9113		return -1;
9114	if (ipf_nat_settimeout(softc, t, p) == -1)
9115		return -1;
9116	return 0;
9117}
9118
9119
9120/* ------------------------------------------------------------------------ */
9121/* Function:    ipf_apply_timeout                                           */
9122/* Returns:     int - 0 = success, -1 = failure                             */
9123/* Parameters:  head(I)    - pointer to tuneable array entry                */
9124/*              seconds(I) - pointer to values passed in to apply           */
9125/*                                                                          */
9126/* This function applies a timeout of "seconds" to the timeout queue that   */
9127/* is pointed to by "head".  All entries on this list have an expiration    */
9128/* set to be the current tick value of ipf plus the ttl.  Given that this   */
9129/* function should only be called when the delta is non-zero, the task is   */
9130/* to walk the entire list and apply the change.  The sort order will not   */
9131/* change.  The only catch is that this is O(n) across the list, so if the  */
9132/* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9133/* could take a relatively long time to work through them all.              */
9134/* ------------------------------------------------------------------------ */
9135void
9136ipf_apply_timeout(head, seconds)
9137	ipftq_t *head;
9138	u_int seconds;
9139{
9140	u_int oldtimeout, newtimeout;
9141	ipftqent_t *tqe;
9142	int delta;
9143
9144	MUTEX_ENTER(&head->ifq_lock);
9145	oldtimeout = head->ifq_ttl;
9146	newtimeout = IPF_TTLVAL(seconds);
9147	delta = oldtimeout - newtimeout;
9148
9149	head->ifq_ttl = newtimeout;
9150
9151	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9152		tqe->tqe_die += delta;
9153	}
9154	MUTEX_EXIT(&head->ifq_lock);
9155}
9156
9157
9158/* ------------------------------------------------------------------------ */
9159/* Function:   ipf_settimeout_tcp                                           */
9160/* Returns:    int - 0 = successfully applied, -1 = failed                  */
9161/* Parameters: t(I)   - pointer to tuneable to change                       */
9162/*             p(I)   - pointer to new timeout information                  */
9163/*             tab(I) - pointer to table of TCP queues                      */
9164/*                                                                          */
9165/* This function applies the new timeout (p) to the TCP tunable (t) and     */
9166/* updates all of the entries on the relevant timeout queue by calling      */
9167/* ipf_apply_timeout().                                                     */
9168/* ------------------------------------------------------------------------ */
9169int
9170ipf_settimeout_tcp(t, p, tab)
9171	ipftuneable_t *t;
9172	ipftuneval_t *p;
9173	ipftq_t *tab;
9174{
9175	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9176	    !strcmp(t->ipft_name, "tcp_established")) {
9177		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9178	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9179		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9180	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9181		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9182	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9183		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9184		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9185		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9186	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
9187		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9188	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9189		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9190	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
9191		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9192	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9193		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9194	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9195		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9196	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
9197		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9198	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9199		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9200	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9201		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9202	} else {
9203		/*
9204		 * ipf_interror isn't set here because it should be set
9205		 * by whatever called this function.
9206		 */
9207		return -1;
9208	}
9209	return 0;
9210}
9211
9212
9213/* ------------------------------------------------------------------------ */
9214/* Function:   ipf_main_soft_create                                         */
9215/* Returns:    NULL = failure, else success                                 */
9216/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9217/*                                                                          */
9218/* Create the foundation soft context structure. In circumstances where it  */
9219/* is not required to dynamically allocate the context, a pointer can be    */
9220/* passed in (rather than NULL) to a structure to be initialised.           */
9221/* The main thing of interest is that a number of locks are initialised     */
9222/* here instead of in the where might be expected - in the relevant create  */
9223/* function elsewhere.  This is done because the current locking design has */
9224/* some areas where these locks are used outside of their module.           */
9225/* Possibly the most important exercise that is done here is setting of all */
9226/* the timeout values, allowing them to be changed before init().           */
9227/* ------------------------------------------------------------------------ */
9228void *
9229ipf_main_soft_create(arg)
9230	void *arg;
9231{
9232	ipf_main_softc_t *softc;
9233
9234	if (arg == NULL) {
9235		KMALLOC(softc, ipf_main_softc_t *);
9236		if (softc == NULL)
9237			return NULL;
9238	} else {
9239		softc = arg;
9240	}
9241
9242	bzero((char *)softc, sizeof(*softc));
9243
9244	/*
9245	 * This serves as a flag as to whether or not the softc should be
9246	 * free'd when _destroy is called.
9247	 */
9248	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9249
9250	softc->ipf_tuners = ipf_tune_array_copy(softc,
9251						sizeof(ipf_main_tuneables),
9252						ipf_main_tuneables);
9253	if (softc->ipf_tuners == NULL) {
9254		ipf_main_soft_destroy(softc);
9255		return NULL;
9256	}
9257
9258	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9259	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9260	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9261	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9262	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9263	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9264	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9265	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9266	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9267
9268	softc->ipf_token_head = NULL;
9269	softc->ipf_token_tail = &softc->ipf_token_head;
9270
9271	softc->ipf_tcpidletimeout = FIVE_DAYS;
9272	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9273	softc->ipf_tcplastack = IPF_TTLVAL(30);
9274	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9275	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9276	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9277	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9278	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9279	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9280	softc->ipf_udptimeout = IPF_TTLVAL(120);
9281	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9282	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9283	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9284	softc->ipf_iptimeout = IPF_TTLVAL(60);
9285
9286#if defined(IPFILTER_DEFAULT_BLOCK)
9287	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9288#else
9289	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9290#endif
9291	softc->ipf_minttl = 4;
9292	softc->ipf_icmpminfragmtu = 68;
9293	softc->ipf_flags = IPF_LOGGING;
9294
9295	return softc;
9296}
9297
9298/* ------------------------------------------------------------------------ */
9299/* Function:   ipf_main_soft_init                                           */
9300/* Returns:    0 = success, -1 = failure                                    */
9301/* Parameters: softc(I) - pointer to soft context main structure            */
9302/*                                                                          */
9303/* A null-op function that exists as a placeholder so that the flow in      */
9304/* other functions is obvious.                                              */
9305/* ------------------------------------------------------------------------ */
9306/*ARGSUSED*/
9307int
9308ipf_main_soft_init(softc)
9309	ipf_main_softc_t *softc;
9310{
9311	return 0;
9312}
9313
9314
9315/* ------------------------------------------------------------------------ */
9316/* Function:   ipf_main_soft_destroy                                        */
9317/* Returns:    void                                                         */
9318/* Parameters: softc(I) - pointer to soft context main structure            */
9319/*                                                                          */
9320/* Undo everything that we did in ipf_main_soft_create.                     */
9321/*                                                                          */
9322/* The most important check that needs to be made here is whether or not    */
9323/* the structure was allocated by ipf_main_soft_create() by checking what   */
9324/* value is stored in ipf_dynamic_main.                                     */
9325/* ------------------------------------------------------------------------ */
9326/*ARGSUSED*/
9327void
9328ipf_main_soft_destroy(softc)
9329	ipf_main_softc_t *softc;
9330{
9331
9332	RW_DESTROY(&softc->ipf_frag);
9333	RW_DESTROY(&softc->ipf_poolrw);
9334	RW_DESTROY(&softc->ipf_nat);
9335	RW_DESTROY(&softc->ipf_state);
9336	RW_DESTROY(&softc->ipf_tokens);
9337	RW_DESTROY(&softc->ipf_mutex);
9338	RW_DESTROY(&softc->ipf_global);
9339	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9340	MUTEX_DESTROY(&softc->ipf_rw);
9341
9342	if (softc->ipf_tuners != NULL) {
9343		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9344	}
9345	if (softc->ipf_dynamic_softc == 1) {
9346		KFREE(softc);
9347	}
9348}
9349
9350
9351/* ------------------------------------------------------------------------ */
9352/* Function:   ipf_main_soft_fini                                           */
9353/* Returns:    0 = success, -1 = failure                                    */
9354/* Parameters: softc(I) - pointer to soft context main structure            */
9355/*                                                                          */
9356/* Clean out the rules which have been added since _init was last called,   */
9357/* the only dynamic part of the mainline.                                   */
9358/* ------------------------------------------------------------------------ */
9359int
9360ipf_main_soft_fini(softc)
9361	ipf_main_softc_t *softc;
9362{
9363	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9364	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9365	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9366	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9367
9368	return 0;
9369}
9370
9371
9372/* ------------------------------------------------------------------------ */
9373/* Function:   ipf_main_load                                                */
9374/* Returns:    0 = success, -1 = failure                                    */
9375/* Parameters: none                                                         */
9376/*                                                                          */
9377/* Handle global initialisation that needs to be done for the base part of  */
9378/* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9379/* arrays that get used by the state/NAT code.                              */
9380/* ------------------------------------------------------------------------ */
9381int
9382ipf_main_load()
9383{
9384	int i;
9385
9386	/* fill icmp reply type table */
9387	for (i = 0; i <= ICMP_MAXTYPE; i++)
9388		icmpreplytype4[i] = -1;
9389	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9390	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9391	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9392	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9393
9394#ifdef  USE_INET6
9395	/* fill icmp reply type table */
9396	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9397		icmpreplytype6[i] = -1;
9398	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9399	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9400	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9401	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9402	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9403#endif
9404
9405	return 0;
9406}
9407
9408
9409/* ------------------------------------------------------------------------ */
9410/* Function:   ipf_main_unload                                              */
9411/* Returns:    0 = success, -1 = failure                                    */
9412/* Parameters: none                                                         */
9413/*                                                                          */
9414/* A null-op function that exists as a placeholder so that the flow in      */
9415/* other functions is obvious.                                              */
9416/* ------------------------------------------------------------------------ */
9417int
9418ipf_main_unload()
9419{
9420	return 0;
9421}
9422
9423
9424/* ------------------------------------------------------------------------ */
9425/* Function:   ipf_load_all                                                 */
9426/* Returns:    0 = success, -1 = failure                                    */
9427/* Parameters: none                                                         */
9428/*                                                                          */
9429/* Work through all of the subsystems inside IPFilter and call the load     */
9430/* function for each in an order that won't lead to a crash :)              */
9431/* ------------------------------------------------------------------------ */
9432int
9433ipf_load_all()
9434{
9435	if (ipf_main_load() == -1)
9436		return -1;
9437
9438	if (ipf_state_main_load() == -1)
9439		return -1;
9440
9441	if (ipf_nat_main_load() == -1)
9442		return -1;
9443
9444	if (ipf_frag_main_load() == -1)
9445		return -1;
9446
9447	if (ipf_auth_main_load() == -1)
9448		return -1;
9449
9450	if (ipf_proxy_main_load() == -1)
9451		return -1;
9452
9453	return 0;
9454}
9455
9456
9457/* ------------------------------------------------------------------------ */
9458/* Function:   ipf_unload_all                                               */
9459/* Returns:    0 = success, -1 = failure                                    */
9460/* Parameters: none                                                         */
9461/*                                                                          */
9462/* Work through all of the subsystems inside IPFilter and call the unload   */
9463/* function for each in an order that won't lead to a crash :)              */
9464/* ------------------------------------------------------------------------ */
9465int
9466ipf_unload_all()
9467{
9468	if (ipf_proxy_main_unload() == -1)
9469		return -1;
9470
9471	if (ipf_auth_main_unload() == -1)
9472		return -1;
9473
9474	if (ipf_frag_main_unload() == -1)
9475		return -1;
9476
9477	if (ipf_nat_main_unload() == -1)
9478		return -1;
9479
9480	if (ipf_state_main_unload() == -1)
9481		return -1;
9482
9483	if (ipf_main_unload() == -1)
9484		return -1;
9485
9486	return 0;
9487}
9488
9489
9490/* ------------------------------------------------------------------------ */
9491/* Function:   ipf_create_all                                               */
9492/* Returns:    NULL = failure, else success                                 */
9493/* Parameters: arg(I) - pointer to soft context main structure              */
9494/*                                                                          */
9495/* Work through all of the subsystems inside IPFilter and call the create   */
9496/* function for each in an order that won't lead to a crash :)              */
9497/* ------------------------------------------------------------------------ */
9498ipf_main_softc_t *
9499ipf_create_all(arg)
9500	void *arg;
9501{
9502	ipf_main_softc_t *softc;
9503
9504	softc = ipf_main_soft_create(arg);
9505	if (softc == NULL)
9506		return NULL;
9507
9508#ifdef IPFILTER_LOG
9509	softc->ipf_log_soft = ipf_log_soft_create(softc);
9510	if (softc->ipf_log_soft == NULL) {
9511		ipf_destroy_all(softc);
9512		return NULL;
9513	}
9514#endif
9515
9516	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9517	if (softc->ipf_lookup_soft == NULL) {
9518		ipf_destroy_all(softc);
9519		return NULL;
9520	}
9521
9522	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9523	if (softc->ipf_sync_soft == NULL) {
9524		ipf_destroy_all(softc);
9525		return NULL;
9526	}
9527
9528	softc->ipf_state_soft = ipf_state_soft_create(softc);
9529	if (softc->ipf_state_soft == NULL) {
9530		ipf_destroy_all(softc);
9531		return NULL;
9532	}
9533
9534	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9535	if (softc->ipf_nat_soft == NULL) {
9536		ipf_destroy_all(softc);
9537		return NULL;
9538	}
9539
9540	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9541	if (softc->ipf_frag_soft == NULL) {
9542		ipf_destroy_all(softc);
9543		return NULL;
9544	}
9545
9546	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9547	if (softc->ipf_auth_soft == NULL) {
9548		ipf_destroy_all(softc);
9549		return NULL;
9550	}
9551
9552	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9553	if (softc->ipf_proxy_soft == NULL) {
9554		ipf_destroy_all(softc);
9555		return NULL;
9556	}
9557
9558	return softc;
9559}
9560
9561
9562/* ------------------------------------------------------------------------ */
9563/* Function:   ipf_destroy_all                                              */
9564/* Returns:    void                                                         */
9565/* Parameters: softc(I) - pointer to soft context main structure            */
9566/*                                                                          */
9567/* Work through all of the subsystems inside IPFilter and call the destroy  */
9568/* function for each in an order that won't lead to a crash :)              */
9569/*                                                                          */
9570/* Every one of these functions is expected to succeed, so there is no      */
9571/* checking of return values.                                               */
9572/* ------------------------------------------------------------------------ */
9573void
9574ipf_destroy_all(softc)
9575	ipf_main_softc_t *softc;
9576{
9577
9578	if (softc->ipf_state_soft != NULL) {
9579		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9580		softc->ipf_state_soft = NULL;
9581	}
9582
9583	if (softc->ipf_nat_soft != NULL) {
9584		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9585		softc->ipf_nat_soft = NULL;
9586	}
9587
9588	if (softc->ipf_frag_soft != NULL) {
9589		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9590		softc->ipf_frag_soft = NULL;
9591	}
9592
9593	if (softc->ipf_auth_soft != NULL) {
9594		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9595		softc->ipf_auth_soft = NULL;
9596	}
9597
9598	if (softc->ipf_proxy_soft != NULL) {
9599		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9600		softc->ipf_proxy_soft = NULL;
9601	}
9602
9603	if (softc->ipf_sync_soft != NULL) {
9604		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9605		softc->ipf_sync_soft = NULL;
9606	}
9607
9608	if (softc->ipf_lookup_soft != NULL) {
9609		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9610		softc->ipf_lookup_soft = NULL;
9611	}
9612
9613#ifdef IPFILTER_LOG
9614	if (softc->ipf_log_soft != NULL) {
9615		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9616		softc->ipf_log_soft = NULL;
9617	}
9618#endif
9619
9620	ipf_main_soft_destroy(softc);
9621}
9622
9623
9624/* ------------------------------------------------------------------------ */
9625/* Function:   ipf_init_all                                                 */
9626/* Returns:    0 = success, -1 = failure                                    */
9627/* Parameters: softc(I) - pointer to soft context main structure            */
9628/*                                                                          */
9629/* Work through all of the subsystems inside IPFilter and call the init     */
9630/* function for each in an order that won't lead to a crash :)              */
9631/* ------------------------------------------------------------------------ */
9632int
9633ipf_init_all(softc)
9634	ipf_main_softc_t *softc;
9635{
9636
9637	if (ipf_main_soft_init(softc) == -1)
9638		return -1;
9639
9640#ifdef IPFILTER_LOG
9641	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9642		return -1;
9643#endif
9644
9645	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9646		return -1;
9647
9648	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9649		return -1;
9650
9651	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9652		return -1;
9653
9654	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9655		return -1;
9656
9657	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9658		return -1;
9659
9660	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9661		return -1;
9662
9663	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9664		return -1;
9665
9666	return 0;
9667}
9668
9669
9670/* ------------------------------------------------------------------------ */
9671/* Function:   ipf_fini_all                                                 */
9672/* Returns:    0 = success, -1 = failure                                    */
9673/* Parameters: softc(I) - pointer to soft context main structure            */
9674/*                                                                          */
9675/* Work through all of the subsystems inside IPFilter and call the fini     */
9676/* function for each in an order that won't lead to a crash :)              */
9677/* ------------------------------------------------------------------------ */
9678int
9679ipf_fini_all(softc)
9680	ipf_main_softc_t *softc;
9681{
9682
9683	ipf_token_flush(softc);
9684
9685	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9686		return -1;
9687
9688	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9689		return -1;
9690
9691	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9692		return -1;
9693
9694	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9695		return -1;
9696
9697	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9698		return -1;
9699
9700	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9701		return -1;
9702
9703	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9704		return -1;
9705
9706#ifdef IPFILTER_LOG
9707	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9708		return -1;
9709#endif
9710
9711	if (ipf_main_soft_fini(softc) == -1)
9712		return -1;
9713
9714	return 0;
9715}
9716
9717
9718/* ------------------------------------------------------------------------ */
9719/* Function:    ipf_rule_expire                                             */
9720/* Returns:     Nil                                                         */
9721/* Parameters:  softc(I) - pointer to soft context main structure           */
9722/*                                                                          */
9723/* At present this function exists just to support temporary addition of    */
9724/* firewall rules. Both inactive and active lists are scanned for items to  */
9725/* purge, as by rights, the expiration is computed as soon as the rule is   */
9726/* loaded in.                                                               */
9727/* ------------------------------------------------------------------------ */
9728void
9729ipf_rule_expire(softc)
9730	ipf_main_softc_t *softc;
9731{
9732	frentry_t *fr;
9733
9734	if ((softc->ipf_rule_explist[0] == NULL) &&
9735	    (softc->ipf_rule_explist[1] == NULL))
9736		return;
9737
9738	WRITE_ENTER(&softc->ipf_mutex);
9739
9740	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9741		/*
9742		 * Because the list is kept sorted on insertion, the fist
9743		 * one that dies in the future means no more work to do.
9744		 */
9745		if (fr->fr_die > softc->ipf_ticks)
9746			break;
9747		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9748	}
9749
9750	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9751		/*
9752		 * Because the list is kept sorted on insertion, the fist
9753		 * one that dies in the future means no more work to do.
9754		 */
9755		if (fr->fr_die > softc->ipf_ticks)
9756			break;
9757		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9758	}
9759
9760	RWLOCK_EXIT(&softc->ipf_mutex);
9761}
9762
9763
9764static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9765static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9766				      i6addr_t *));
9767
9768host_node_t RBI_ZERO(ipf_rb);
9769RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9770
9771
9772/* ------------------------------------------------------------------------ */
9773/* Function:    ipf_ht_node_cmp                                             */
9774/* Returns:     int   - 0 == nodes are the same, ..                         */
9775/* Parameters:  k1(I) - pointer to first key to compare                     */
9776/*              k2(I) - pointer to second key to compare                    */
9777/*                                                                          */
9778/* The "key" for the node is a combination of two fields: the address       */
9779/* family and the address itself.                                           */
9780/*                                                                          */
9781/* Because we're not actually interpreting the address data, it isn't       */
9782/* necessary to convert them to/from network/host byte order. The mask is   */
9783/* just used to remove bits that aren't significant - it doesn't matter     */
9784/* where they are, as long as they're always in the same place.             */
9785/*                                                                          */
9786/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9787/* this is where individual ones will differ the most - but not true for    */
9788/* for /48's, etc.                                                          */
9789/* ------------------------------------------------------------------------ */
9790static int
9791ipf_ht_node_cmp(k1, k2)
9792	struct host_node_s *k1, *k2;
9793{
9794	int i;
9795
9796	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9797	if (i != 0)
9798		return i;
9799
9800	if (k1->hn_addr.adf_family == AF_INET)
9801		return (k2->hn_addr.adf_addr.in4.s_addr -
9802			k1->hn_addr.adf_addr.in4.s_addr);
9803
9804	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9805	if (i != 0)
9806		return i;
9807	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9808	if (i != 0)
9809		return i;
9810	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9811	if (i != 0)
9812		return i;
9813	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9814	return i;
9815}
9816
9817
9818/* ------------------------------------------------------------------------ */
9819/* Function:    ipf_ht_node_make_key                                        */
9820/* Returns:     Nil                                                         */
9821/* parameters:  htp(I)    - pointer to address tracking structure           */
9822/*              key(I)    - where to store masked address for lookup        */
9823/*              family(I) - protocol family of address                      */
9824/*              addr(I)   - pointer to network address                      */
9825/*                                                                          */
9826/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9827/* copy the address passed in into the key structure whilst masking out the */
9828/* bits that we don't want.                                                 */
9829/*                                                                          */
9830/* Because the parser will set ht_netmask to 128 if there is no protocol    */
9831/* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9832/* have to be wary of that and not allow 32-128 to happen.                  */
9833/* ------------------------------------------------------------------------ */
9834static void
9835ipf_ht_node_make_key(htp, key, family, addr)
9836	host_track_t *htp;
9837	host_node_t *key;
9838	int family;
9839	i6addr_t *addr;
9840{
9841	key->hn_addr.adf_family = family;
9842	if (family == AF_INET) {
9843		u_32_t mask;
9844		int bits;
9845
9846		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9847		bits = htp->ht_netmask;
9848		if (bits >= 32) {
9849			mask = 0xffffffff;
9850		} else {
9851			mask = htonl(0xffffffff << (32 - bits));
9852		}
9853		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9854#ifdef USE_INET6
9855	} else {
9856		int bits = htp->ht_netmask;
9857
9858		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9859		if (bits > 96) {
9860			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9861					     htonl(0xffffffff << (128 - bits));
9862			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9863			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9864			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9865		} else if (bits > 64) {
9866			key->hn_addr.adf_addr.i6[3] = 0;
9867			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9868					     htonl(0xffffffff << (96 - bits));
9869			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9870			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9871		} else if (bits > 32) {
9872			key->hn_addr.adf_addr.i6[3] = 0;
9873			key->hn_addr.adf_addr.i6[2] = 0;
9874			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9875					     htonl(0xffffffff << (64 - bits));
9876			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9877		} else {
9878			key->hn_addr.adf_addr.i6[3] = 0;
9879			key->hn_addr.adf_addr.i6[2] = 0;
9880			key->hn_addr.adf_addr.i6[1] = 0;
9881			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9882					     htonl(0xffffffff << (32 - bits));
9883		}
9884#endif
9885	}
9886}
9887
9888
9889/* ------------------------------------------------------------------------ */
9890/* Function:    ipf_ht_node_add                                             */
9891/* Returns:     int       - 0 == success,  -1 == failure                    */
9892/* Parameters:  softc(I)  - pointer to soft context main structure          */
9893/*              htp(I)    - pointer to address tracking structure           */
9894/*              family(I) - protocol family of address                      */
9895/*              addr(I)   - pointer to network address                      */
9896/*                                                                          */
9897/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9898/*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9899/*                                                                          */
9900/* After preparing the key with the address information to find, look in    */
9901/* the red-black tree to see if the address is known. A successful call to  */
9902/* this function can mean one of two things: a new node was added to the    */
9903/* tree or a matching node exists and we're able to bump up its activity.   */
9904/* ------------------------------------------------------------------------ */
9905int
9906ipf_ht_node_add(softc, htp, family, addr)
9907	ipf_main_softc_t *softc;
9908	host_track_t *htp;
9909	int family;
9910	i6addr_t *addr;
9911{
9912	host_node_t *h;
9913	host_node_t k;
9914
9915	ipf_ht_node_make_key(htp, &k, family, addr);
9916
9917	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9918	if (h == NULL) {
9919		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9920			return -1;
9921		KMALLOC(h, host_node_t *);
9922		if (h == NULL) {
9923			DT(ipf_rb_no_mem);
9924			LBUMP(ipf_rb_no_mem);
9925			return -1;
9926		}
9927
9928		/*
9929		 * If there was a macro to initialise the RB node then that
9930		 * would get used here, but there isn't...
9931		 */
9932		bzero((char *)h, sizeof(*h));
9933		h->hn_addr = k.hn_addr;
9934		h->hn_addr.adf_family = k.hn_addr.adf_family;
9935		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9936		htp->ht_cur_nodes++;
9937	} else {
9938		if ((htp->ht_max_per_node != 0) &&
9939		    (h->hn_active >= htp->ht_max_per_node)) {
9940			DT(ipf_rb_node_max);
9941			LBUMP(ipf_rb_node_max);
9942			return -1;
9943		}
9944	}
9945
9946	h->hn_active++;
9947
9948	return 0;
9949}
9950
9951
9952/* ------------------------------------------------------------------------ */
9953/* Function:    ipf_ht_node_del                                             */
9954/* Returns:     int       - 0 == success,  -1 == failure                    */
9955/* parameters:  htp(I)    - pointer to address tracking structure           */
9956/*              family(I) - protocol family of address                      */
9957/*              addr(I)   - pointer to network address                      */
9958/*                                                                          */
9959/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9960/*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9961/*                                                                          */
9962/* Try and find the address passed in amongst the leavese on this tree to   */
9963/* be friend. If found then drop the active account for that node drops by  */
9964/* one. If that count reaches 0, it is time to free it all up.              */
9965/* ------------------------------------------------------------------------ */
9966int
9967ipf_ht_node_del(htp, family, addr)
9968	host_track_t *htp;
9969	int family;
9970	i6addr_t *addr;
9971{
9972	host_node_t *h;
9973	host_node_t k;
9974
9975	ipf_ht_node_make_key(htp, &k, family, addr);
9976
9977	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9978	if (h == NULL) {
9979		return -1;
9980	} else {
9981		h->hn_active--;
9982		if (h->hn_active == 0) {
9983			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9984			htp->ht_cur_nodes--;
9985			KFREE(h);
9986		}
9987	}
9988
9989	return 0;
9990}
9991
9992
9993/* ------------------------------------------------------------------------ */
9994/* Function:    ipf_rb_ht_init                                              */
9995/* Returns:     Nil                                                         */
9996/* Parameters:  head(I) - pointer to host tracking structure                */
9997/*                                                                          */
9998/* Initialise the host tracking structure to be ready for use above.        */
9999/* ------------------------------------------------------------------------ */
10000void
10001ipf_rb_ht_init(head)
10002	host_track_t *head;
10003{
10004	RBI_INIT(ipf_rb, &head->ht_root);
10005}
10006
10007
10008/* ------------------------------------------------------------------------ */
10009/* Function:    ipf_rb_ht_freenode                                          */
10010/* Returns:     Nil                                                         */
10011/* Parameters:  head(I) - pointer to host tracking structure                */
10012/*              arg(I)  - additional argument from walk caller              */
10013/*                                                                          */
10014/* Free an actual host_node_t structure.                                    */
10015/* ------------------------------------------------------------------------ */
10016void
10017ipf_rb_ht_freenode(node, arg)
10018	host_node_t *node;
10019	void *arg;
10020{
10021	KFREE(node);
10022}
10023
10024
10025/* ------------------------------------------------------------------------ */
10026/* Function:    ipf_rb_ht_flush                                             */
10027/* Returns:     Nil                                                         */
10028/* Parameters:  head(I) - pointer to host tracking structure                */
10029/*                                                                          */
10030/* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10031/* and free'ing each one.                                                   */
10032/* ------------------------------------------------------------------------ */
10033void
10034ipf_rb_ht_flush(head)
10035	host_track_t *head;
10036{
10037	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10038}
10039
10040
10041/* ------------------------------------------------------------------------ */
10042/* Function:    ipf_slowtimer                                               */
10043/* Returns:     Nil                                                         */
10044/* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10045/*                                                                          */
10046/* Slowly expire held state for fragments.  Timeouts are set * in           */
10047/* expectation of this being called twice per second.                       */
10048/* ------------------------------------------------------------------------ */
10049void
10050ipf_slowtimer(softc)
10051	ipf_main_softc_t *softc;
10052{
10053
10054	ipf_token_expire(softc);
10055	ipf_frag_expire(softc);
10056	ipf_state_expire(softc);
10057	ipf_nat_expire(softc);
10058	ipf_auth_expire(softc);
10059	ipf_lookup_expire(softc);
10060	ipf_rule_expire(softc);
10061	ipf_sync_expire(softc);
10062	softc->ipf_ticks++;
10063}
10064
10065
10066/* ------------------------------------------------------------------------ */
10067/* Function:    ipf_inet_mask_add                                           */
10068/* Returns:     Nil                                                         */
10069/* Parameters:  bits(I) - pointer to nat context information                */
10070/*              mtab(I) - pointer to mask hash table structure              */
10071/*                                                                          */
10072/* When called, bits represents the mask of a new NAT rule that has just    */
10073/* been added. This function inserts a bitmask into the array of masks to   */
10074/* search when searching for a matching NAT rule for a packet.              */
10075/* Prevention of duplicate masks is achieved by checking the use count for  */
10076/* a given netmask.                                                         */
10077/* ------------------------------------------------------------------------ */
10078void
10079ipf_inet_mask_add(bits, mtab)
10080	int bits;
10081	ipf_v4_masktab_t *mtab;
10082{
10083	u_32_t mask;
10084	int i, j;
10085
10086	mtab->imt4_masks[bits]++;
10087	if (mtab->imt4_masks[bits] > 1)
10088		return;
10089
10090	if (bits == 0)
10091		mask = 0;
10092	else
10093		mask = 0xffffffff << (32 - bits);
10094
10095	for (i = 0; i < 33; i++) {
10096		if (ntohl(mtab->imt4_active[i]) < mask) {
10097			for (j = 32; j > i; j--)
10098				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10099			mtab->imt4_active[i] = htonl(mask);
10100			break;
10101		}
10102	}
10103	mtab->imt4_max++;
10104}
10105
10106
10107/* ------------------------------------------------------------------------ */
10108/* Function:    ipf_inet_mask_del                                           */
10109/* Returns:     Nil                                                         */
10110/* Parameters:  bits(I) - number of bits set in the netmask                 */
10111/*              mtab(I) - pointer to mask hash table structure              */
10112/*                                                                          */
10113/* Remove the 32bit bitmask represented by "bits" from the collection of    */
10114/* netmasks stored inside of mtab.                                          */
10115/* ------------------------------------------------------------------------ */
10116void
10117ipf_inet_mask_del(bits, mtab)
10118	int bits;
10119	ipf_v4_masktab_t *mtab;
10120{
10121	u_32_t mask;
10122	int i, j;
10123
10124	mtab->imt4_masks[bits]--;
10125	if (mtab->imt4_masks[bits] > 0)
10126		return;
10127
10128	mask = htonl(0xffffffff << (32 - bits));
10129	for (i = 0; i < 33; i++) {
10130		if (mtab->imt4_active[i] == mask) {
10131			for (j = i + 1; j < 33; j++)
10132				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10133			break;
10134		}
10135	}
10136	mtab->imt4_max--;
10137	ASSERT(mtab->imt4_max >= 0);
10138}
10139
10140
10141#ifdef USE_INET6
10142/* ------------------------------------------------------------------------ */
10143/* Function:    ipf_inet6_mask_add                                          */
10144/* Returns:     Nil                                                         */
10145/* Parameters:  bits(I) - number of bits set in mask                        */
10146/*              mask(I) - pointer to mask to add                            */
10147/*              mtab(I) - pointer to mask hash table structure              */
10148/*                                                                          */
10149/* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10150/* has just been added. This function inserts a bitmask into the array of   */
10151/* masks to search when searching for a matching NAT rule for a packet.     */
10152/* Prevention of duplicate masks is achieved by checking the use count for  */
10153/* a given netmask.                                                         */
10154/* ------------------------------------------------------------------------ */
10155void
10156ipf_inet6_mask_add(bits, mask, mtab)
10157	int bits;
10158	i6addr_t *mask;
10159	ipf_v6_masktab_t *mtab;
10160{
10161	i6addr_t zero;
10162	int i, j;
10163
10164	mtab->imt6_masks[bits]++;
10165	if (mtab->imt6_masks[bits] > 1)
10166		return;
10167
10168	if (bits == 0) {
10169		mask = &zero;
10170		zero.i6[0] = 0;
10171		zero.i6[1] = 0;
10172		zero.i6[2] = 0;
10173		zero.i6[3] = 0;
10174	}
10175
10176	for (i = 0; i < 129; i++) {
10177		if (IP6_LT(&mtab->imt6_active[i], mask)) {
10178			for (j = 128; j > i; j--)
10179				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10180			mtab->imt6_active[i] = *mask;
10181			break;
10182		}
10183	}
10184	mtab->imt6_max++;
10185}
10186
10187
10188/* ------------------------------------------------------------------------ */
10189/* Function:    ipf_inet6_mask_del                                          */
10190/* Returns:     Nil                                                         */
10191/* Parameters:  bits(I) - number of bits set in mask                        */
10192/*              mask(I) - pointer to mask to remove                         */
10193/*              mtab(I) - pointer to mask hash table structure              */
10194/*                                                                          */
10195/* Remove the 128bit bitmask represented by "bits" from the collection of   */
10196/* netmasks stored inside of mtab.                                          */
10197/* ------------------------------------------------------------------------ */
10198void
10199ipf_inet6_mask_del(bits, mask, mtab)
10200	int bits;
10201	i6addr_t *mask;
10202	ipf_v6_masktab_t *mtab;
10203{
10204	i6addr_t zero;
10205	int i, j;
10206
10207	mtab->imt6_masks[bits]--;
10208	if (mtab->imt6_masks[bits] > 0)
10209		return;
10210
10211	if (bits == 0)
10212		mask = &zero;
10213	zero.i6[0] = 0;
10214	zero.i6[1] = 0;
10215	zero.i6[2] = 0;
10216	zero.i6[3] = 0;
10217
10218	for (i = 0; i < 129; i++) {
10219		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10220			for (j = i + 1; j < 129; j++) {
10221				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10222				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10223					break;
10224			}
10225			break;
10226		}
10227	}
10228	mtab->imt6_max--;
10229	ASSERT(mtab->imt6_max >= 0);
10230}
10231#endif
10232