fil.c revision 349931
1/*	$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 349931 2019-07-12 02:14:05Z 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 349931 2019-07-12 02:14:05Z 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#ifdef	USE_INET6
183static	u_int		ipf_pcksum6 __P((fr_info_t *, ip6_t *,
184						u_int32_t, u_int32_t));
185#endif
186#if !defined(_KERNEL) || SOLARIS
187static	int		ppsratecheck(struct timeval *, int *, int);
188#endif
189
190
191/*
192 * bit values for identifying presence of individual IP options
193 * All of these tables should be ordered by increasing key value on the left
194 * hand side to allow for binary searching of the array and include a trailer
195 * with a 0 for the bitmask for linear searches to easily find the end with.
196 */
197static const	struct	optlist	ipopts[20] = {
198	{ IPOPT_NOP,	0x000001 },
199	{ IPOPT_RR,	0x000002 },
200	{ IPOPT_ZSU,	0x000004 },
201	{ IPOPT_MTUP,	0x000008 },
202	{ IPOPT_MTUR,	0x000010 },
203	{ IPOPT_ENCODE,	0x000020 },
204	{ IPOPT_TS,	0x000040 },
205	{ IPOPT_TR,	0x000080 },
206	{ IPOPT_SECURITY, 0x000100 },
207	{ IPOPT_LSRR,	0x000200 },
208	{ IPOPT_E_SEC,	0x000400 },
209	{ IPOPT_CIPSO,	0x000800 },
210	{ IPOPT_SATID,	0x001000 },
211	{ IPOPT_SSRR,	0x002000 },
212	{ IPOPT_ADDEXT,	0x004000 },
213	{ IPOPT_VISA,	0x008000 },
214	{ IPOPT_IMITD,	0x010000 },
215	{ IPOPT_EIP,	0x020000 },
216	{ IPOPT_FINN,	0x040000 },
217	{ 0,		0x000000 }
218};
219
220#ifdef USE_INET6
221static const struct optlist ip6exthdr[] = {
222	{ IPPROTO_HOPOPTS,		0x000001 },
223	{ IPPROTO_IPV6,			0x000002 },
224	{ IPPROTO_ROUTING,		0x000004 },
225	{ IPPROTO_FRAGMENT,		0x000008 },
226	{ IPPROTO_ESP,			0x000010 },
227	{ IPPROTO_AH,			0x000020 },
228	{ IPPROTO_NONE,			0x000040 },
229	{ IPPROTO_DSTOPTS,		0x000080 },
230	{ IPPROTO_MOBILITY,		0x000100 },
231	{ 0,				0 }
232};
233#endif
234
235/*
236 * bit values for identifying presence of individual IP security options
237 */
238static const	struct	optlist	secopt[8] = {
239	{ IPSO_CLASS_RES4,	0x01 },
240	{ IPSO_CLASS_TOPS,	0x02 },
241	{ IPSO_CLASS_SECR,	0x04 },
242	{ IPSO_CLASS_RES3,	0x08 },
243	{ IPSO_CLASS_CONF,	0x10 },
244	{ IPSO_CLASS_UNCL,	0x20 },
245	{ IPSO_CLASS_RES2,	0x40 },
246	{ IPSO_CLASS_RES1,	0x80 }
247};
248
249char	ipfilter_version[] = IPL_VERSION;
250
251int	ipf_features = 0
252#ifdef	IPFILTER_LKM
253		| IPF_FEAT_LKM
254#endif
255#ifdef	IPFILTER_LOG
256		| IPF_FEAT_LOG
257#endif
258		| IPF_FEAT_LOOKUP
259#ifdef	IPFILTER_BPF
260		| IPF_FEAT_BPF
261#endif
262#ifdef	IPFILTER_COMPILED
263		| IPF_FEAT_COMPILED
264#endif
265#ifdef	IPFILTER_CKSUM
266		| IPF_FEAT_CKSUM
267#endif
268		| IPF_FEAT_SYNC
269#ifdef	IPFILTER_SCAN
270		| IPF_FEAT_SCAN
271#endif
272#ifdef	USE_INET6
273		| IPF_FEAT_IPV6
274#endif
275	;
276
277
278/*
279 * Table of functions available for use with call rules.
280 */
281static ipfunc_resolve_t ipf_availfuncs[] = {
282	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
283	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
284	{ "",	      NULL,	      NULL,	      NULL }
285};
286
287static ipftuneable_t ipf_main_tuneables[] = {
288	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
289		"ipf_flags",		0,	0xffffffff,
290		stsizeof(ipf_main_softc_t, ipf_flags),
291		0,			NULL,	NULL },
292	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
293		"active",		0,	0,
294		stsizeof(ipf_main_softc_t, ipf_active),
295		IPFT_RDONLY,		NULL,	NULL },
296	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
297		"control_forwarding",	0, 1,
298		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
299		0,			NULL,	NULL },
300	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
301		"update_ipid",		0,	1,
302		stsizeof(ipf_main_softc_t, ipf_update_ipid),
303		0,			NULL,	NULL },
304	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
305		"chksrc",		0,	1,
306		stsizeof(ipf_main_softc_t, ipf_chksrc),
307		0,			NULL,	NULL },
308	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
309		"min_ttl",		0,	1,
310		stsizeof(ipf_main_softc_t, ipf_minttl),
311		0,			NULL,	NULL },
312	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
313		"icmp_minfragmtu",	0,	1,
314		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
315		0,			NULL,	NULL },
316	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
317		"default_pass",		0,	0xffffffff,
318		stsizeof(ipf_main_softc_t, ipf_pass),
319		0,			NULL,	NULL },
320	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
321		"tcp_idle_timeout",	1,	0x7fffffff,
322		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
323		0,			NULL,	ipf_settimeout },
324	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
325		"tcp_close_wait",	1,	0x7fffffff,
326		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
327		0,			NULL,	ipf_settimeout },
328	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
329		"tcp_last_ack",		1,	0x7fffffff,
330		stsizeof(ipf_main_softc_t, ipf_tcplastack),
331		0,			NULL,	ipf_settimeout },
332	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
333		"tcp_timeout",		1,	0x7fffffff,
334		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
335		0,			NULL,	ipf_settimeout },
336	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
337		"tcp_syn_sent",		1,	0x7fffffff,
338		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
339		0,			NULL,	ipf_settimeout },
340	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
341		"tcp_syn_received",	1,	0x7fffffff,
342		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
343		0,			NULL,	ipf_settimeout },
344	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
345		"tcp_closed",		1,	0x7fffffff,
346		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
347		0,			NULL,	ipf_settimeout },
348	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
349		"tcp_half_closed",	1,	0x7fffffff,
350		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
351		0,			NULL,	ipf_settimeout },
352	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
353		"tcp_time_wait",	1,	0x7fffffff,
354		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
355		0,			NULL,	ipf_settimeout },
356	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
357		"udp_timeout",		1,	0x7fffffff,
358		stsizeof(ipf_main_softc_t, ipf_udptimeout),
359		0,			NULL,	ipf_settimeout },
360	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
361		"udp_ack_timeout",	1,	0x7fffffff,
362		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
363		0,			NULL,	ipf_settimeout },
364	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
365		"icmp_timeout",		1,	0x7fffffff,
366		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
367		0,			NULL,	ipf_settimeout },
368	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
369		"icmp_ack_timeout",	1,	0x7fffffff,
370		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
371		0,			NULL,	ipf_settimeout },
372	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
373		"ip_timeout",		1,	0x7fffffff,
374		stsizeof(ipf_main_softc_t, ipf_iptimeout),
375		0,			NULL,	ipf_settimeout },
376#if defined(INSTANCES) && defined(_KERNEL)
377	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
378		"intercept_loopback",	0,	1,
379		stsizeof(ipf_main_softc_t, ipf_get_loopback),
380		0,			NULL,	ipf_set_loopback },
381#endif
382	{ { 0 },
383		NULL,			0,	0,
384		0,
385		0,			NULL,	NULL }
386};
387
388
389/*
390 * The next section of code is a collection of small routines that set
391 * fields in the fr_info_t structure passed based on properties of the
392 * current packet.  There are different routines for the same protocol
393 * for each of IPv4 and IPv6.  Adding a new protocol, for which there
394 * will "special" inspection for setup, is now more easily done by adding
395 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
396 * adding more code to a growing switch statement.
397 */
398#ifdef USE_INET6
399static	INLINE int	ipf_pr_ah6 __P((fr_info_t *));
400static	INLINE void	ipf_pr_esp6 __P((fr_info_t *));
401static	INLINE void	ipf_pr_gre6 __P((fr_info_t *));
402static	INLINE void	ipf_pr_udp6 __P((fr_info_t *));
403static	INLINE void	ipf_pr_tcp6 __P((fr_info_t *));
404static	INLINE void	ipf_pr_icmp6 __P((fr_info_t *));
405static	INLINE void	ipf_pr_ipv6hdr __P((fr_info_t *));
406static	INLINE void	ipf_pr_short6 __P((fr_info_t *, int));
407static	INLINE int	ipf_pr_hopopts6 __P((fr_info_t *));
408static	INLINE int	ipf_pr_mobility6 __P((fr_info_t *));
409static	INLINE int	ipf_pr_routing6 __P((fr_info_t *));
410static	INLINE int	ipf_pr_dstopts6 __P((fr_info_t *));
411static	INLINE int	ipf_pr_fragment6 __P((fr_info_t *));
412static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
413
414
415/* ------------------------------------------------------------------------ */
416/* Function:    ipf_pr_short6                                               */
417/* Returns:     void                                                        */
418/* Parameters:  fin(I)  - pointer to packet information                     */
419/*              xmin(I) - minimum header size                               */
420/*                                                                          */
421/* IPv6 Only                                                                */
422/* This is function enforces the 'is a packet too short to be legit' rule   */
423/* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
424/* for ipf_pr_short() for more details.                                     */
425/* ------------------------------------------------------------------------ */
426static INLINE void
427ipf_pr_short6(fin, xmin)
428	fr_info_t *fin;
429	int xmin;
430{
431
432	if (fin->fin_dlen < xmin)
433		fin->fin_flx |= FI_SHORT;
434}
435
436
437/* ------------------------------------------------------------------------ */
438/* Function:    ipf_pr_ipv6hdr                                              */
439/* Returns:     void                                                        */
440/* Parameters:  fin(I) - pointer to packet information                      */
441/*                                                                          */
442/* IPv6 Only                                                                */
443/* Copy values from the IPv6 header into the fr_info_t struct and call the  */
444/* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
445/* analyzer may pullup or free the packet itself so we need to be vigiliant */
446/* of that possibility arising.                                             */
447/* ------------------------------------------------------------------------ */
448static INLINE void
449ipf_pr_ipv6hdr(fin)
450	fr_info_t *fin;
451{
452	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
453	int p, go = 1, i, hdrcount;
454	fr_ip_t *fi = &fin->fin_fi;
455
456	fin->fin_off = 0;
457
458	fi->fi_tos = 0;
459	fi->fi_optmsk = 0;
460	fi->fi_secmsk = 0;
461	fi->fi_auth = 0;
462
463	p = ip6->ip6_nxt;
464	fin->fin_crc = p;
465	fi->fi_ttl = ip6->ip6_hlim;
466	fi->fi_src.in6 = ip6->ip6_src;
467	fin->fin_crc += fi->fi_src.i6[0];
468	fin->fin_crc += fi->fi_src.i6[1];
469	fin->fin_crc += fi->fi_src.i6[2];
470	fin->fin_crc += fi->fi_src.i6[3];
471	fi->fi_dst.in6 = ip6->ip6_dst;
472	fin->fin_crc += fi->fi_dst.i6[0];
473	fin->fin_crc += fi->fi_dst.i6[1];
474	fin->fin_crc += fi->fi_dst.i6[2];
475	fin->fin_crc += fi->fi_dst.i6[3];
476	fin->fin_id = 0;
477	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
478		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
479
480	hdrcount = 0;
481	while (go && !(fin->fin_flx & FI_SHORT)) {
482		switch (p)
483		{
484		case IPPROTO_UDP :
485			ipf_pr_udp6(fin);
486			go = 0;
487			break;
488
489		case IPPROTO_TCP :
490			ipf_pr_tcp6(fin);
491			go = 0;
492			break;
493
494		case IPPROTO_ICMPV6 :
495			ipf_pr_icmp6(fin);
496			go = 0;
497			break;
498
499		case IPPROTO_GRE :
500			ipf_pr_gre6(fin);
501			go = 0;
502			break;
503
504		case IPPROTO_HOPOPTS :
505			p = ipf_pr_hopopts6(fin);
506			break;
507
508		case IPPROTO_MOBILITY :
509			p = ipf_pr_mobility6(fin);
510			break;
511
512		case IPPROTO_DSTOPTS :
513			p = ipf_pr_dstopts6(fin);
514			break;
515
516		case IPPROTO_ROUTING :
517			p = ipf_pr_routing6(fin);
518			break;
519
520		case IPPROTO_AH :
521			p = ipf_pr_ah6(fin);
522			break;
523
524		case IPPROTO_ESP :
525			ipf_pr_esp6(fin);
526			go = 0;
527			break;
528
529		case IPPROTO_IPV6 :
530			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
531				if (ip6exthdr[i].ol_val == p) {
532					fin->fin_flx |= ip6exthdr[i].ol_bit;
533					break;
534				}
535			go = 0;
536			break;
537
538		case IPPROTO_NONE :
539			go = 0;
540			break;
541
542		case IPPROTO_FRAGMENT :
543			p = ipf_pr_fragment6(fin);
544			/*
545			 * Given that the only fragments we want to let through
546			 * (where fin_off != 0) are those where the non-first
547			 * fragments only have data, we can safely stop looking
548			 * at headers if this is a non-leading fragment.
549			 */
550			if (fin->fin_off != 0)
551				go = 0;
552			break;
553
554		default :
555			go = 0;
556			break;
557		}
558		hdrcount++;
559
560		/*
561		 * It is important to note that at this point, for the
562		 * extension headers (go != 0), the entire header may not have
563		 * been pulled up when the code gets to this point.  This is
564		 * only done for "go != 0" because the other header handlers
565		 * will all pullup their complete header.  The other indicator
566		 * of an incomplete packet is that this was just an extension
567		 * header.
568		 */
569		if ((go != 0) && (p != IPPROTO_NONE) &&
570		    (ipf_pr_pullup(fin, 0) == -1)) {
571			p = IPPROTO_NONE;
572			break;
573		}
574	}
575
576	/*
577	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
578	 * and destroy whatever packet was here.  The caller of this function
579	 * expects us to return if there is a problem with ipf_pullup.
580	 */
581	if (fin->fin_m == NULL) {
582		ipf_main_softc_t *softc = fin->fin_main_soft;
583
584		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
585		return;
586	}
587
588	fi->fi_p = p;
589
590	/*
591	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
592	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
593	 */
594	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
595		ipf_main_softc_t *softc = fin->fin_main_soft;
596
597		fin->fin_flx |= FI_BAD;
598		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
599		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
600		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
601	}
602}
603
604
605/* ------------------------------------------------------------------------ */
606/* Function:    ipf_pr_ipv6exthdr                                           */
607/* Returns:     struct ip6_ext * - pointer to the start of the next header  */
608/*                                 or NULL if there is a prolblem.          */
609/* Parameters:  fin(I)      - pointer to packet information                 */
610/*              multiple(I) - flag indicating yes/no if multiple occurances */
611/*                            of this extension header are allowed.         */
612/*              proto(I)    - protocol number for this extension header     */
613/*                                                                          */
614/* IPv6 Only                                                                */
615/* This function embodies a number of common checks that all IPv6 extension */
616/* headers must be subjected to.  For example, making sure the packet is    */
617/* big enough for it to be in, checking if it is repeated and setting a     */
618/* flag to indicate its presence.                                           */
619/* ------------------------------------------------------------------------ */
620static INLINE struct ip6_ext *
621ipf_pr_ipv6exthdr(fin, multiple, proto)
622	fr_info_t *fin;
623	int multiple, proto;
624{
625	ipf_main_softc_t *softc = fin->fin_main_soft;
626	struct ip6_ext *hdr;
627	u_short shift;
628	int i;
629
630	fin->fin_flx |= FI_V6EXTHDR;
631
632				/* 8 is default length of extension hdr */
633	if ((fin->fin_dlen - 8) < 0) {
634		fin->fin_flx |= FI_SHORT;
635		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
636		return NULL;
637	}
638
639	if (ipf_pr_pullup(fin, 8) == -1) {
640		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
641		return NULL;
642	}
643
644	hdr = fin->fin_dp;
645	switch (proto)
646	{
647	case IPPROTO_FRAGMENT :
648		shift = 8;
649		break;
650	default :
651		shift = 8 + (hdr->ip6e_len << 3);
652		break;
653	}
654
655	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
656		fin->fin_flx |= FI_BAD;
657		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
658		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
659		return NULL;
660	}
661
662	fin->fin_dp = (char *)fin->fin_dp + shift;
663	fin->fin_dlen -= shift;
664
665	/*
666	 * If we have seen a fragment header, do not set any flags to indicate
667	 * the presence of this extension header as it has no impact on the
668	 * end result until after it has been defragmented.
669	 */
670	if (fin->fin_flx & FI_FRAG)
671		return hdr;
672
673	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
674		if (ip6exthdr[i].ol_val == proto) {
675			/*
676			 * Most IPv6 extension headers are only allowed once.
677			 */
678			if ((multiple == 0) &&
679			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
680				fin->fin_flx |= FI_BAD;
681				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
682			} else
683				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
684			break;
685		}
686
687	return hdr;
688}
689
690
691/* ------------------------------------------------------------------------ */
692/* Function:    ipf_pr_hopopts6                                             */
693/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
694/* Parameters:  fin(I) - pointer to packet information                      */
695/*                                                                          */
696/* IPv6 Only                                                                */
697/* This is function checks pending hop by hop options extension header      */
698/* ------------------------------------------------------------------------ */
699static INLINE int
700ipf_pr_hopopts6(fin)
701	fr_info_t *fin;
702{
703	struct ip6_ext *hdr;
704
705	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
706	if (hdr == NULL)
707		return IPPROTO_NONE;
708	return hdr->ip6e_nxt;
709}
710
711
712/* ------------------------------------------------------------------------ */
713/* Function:    ipf_pr_mobility6                                            */
714/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
715/* Parameters:  fin(I) - pointer to packet information                      */
716/*                                                                          */
717/* IPv6 Only                                                                */
718/* This is function checks the IPv6 mobility extension header               */
719/* ------------------------------------------------------------------------ */
720static INLINE int
721ipf_pr_mobility6(fin)
722	fr_info_t *fin;
723{
724	struct ip6_ext *hdr;
725
726	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
727	if (hdr == NULL)
728		return IPPROTO_NONE;
729	return hdr->ip6e_nxt;
730}
731
732
733/* ------------------------------------------------------------------------ */
734/* Function:    ipf_pr_routing6                                             */
735/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
736/* Parameters:  fin(I) - pointer to packet information                      */
737/*                                                                          */
738/* IPv6 Only                                                                */
739/* This is function checks pending routing extension header                 */
740/* ------------------------------------------------------------------------ */
741static INLINE int
742ipf_pr_routing6(fin)
743	fr_info_t *fin;
744{
745	struct ip6_routing *hdr;
746
747	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
748	if (hdr == NULL)
749		return IPPROTO_NONE;
750
751	switch (hdr->ip6r_type)
752	{
753	case 0 :
754		/*
755		 * Nasty extension header length?
756		 */
757		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
758		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
759			ipf_main_softc_t *softc = fin->fin_main_soft;
760
761			fin->fin_flx |= FI_BAD;
762			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
763			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
764			return IPPROTO_NONE;
765		}
766		break;
767
768	default :
769		break;
770	}
771
772	return hdr->ip6r_nxt;
773}
774
775
776/* ------------------------------------------------------------------------ */
777/* Function:    ipf_pr_fragment6                                            */
778/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
779/* Parameters:  fin(I) - pointer to packet information                      */
780/*                                                                          */
781/* IPv6 Only                                                                */
782/* Examine the IPv6 fragment header and extract fragment offset information.*/
783/*                                                                          */
784/* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
785/* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
786/* packets with a fragment header can fit into.  They are as follows:       */
787/*                                                                          */
788/* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
789/* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
790/* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
791/* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
792/* 5.  [IPV6][0-n EH][FH][data]                                             */
793/*                                                                          */
794/* IPV6 = IPv6 header, FH = Fragment Header,                                */
795/* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
796/*                                                                          */
797/* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
798/* scenario in which they happen is in extreme circumstances that are most  */
799/* likely to be an indication of an attack rather than normal traffic.      */
800/* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
801/* are two rules that can be used to guard against type 3 packets: L4       */
802/* headers must always be in a packet that has the offset field set to 0    */
803/* and no packet is allowed to overlay that where offset = 0.               */
804/* ------------------------------------------------------------------------ */
805static INLINE int
806ipf_pr_fragment6(fin)
807	fr_info_t *fin;
808{
809	ipf_main_softc_t *softc = fin->fin_main_soft;
810	struct ip6_frag *frag;
811
812	fin->fin_flx |= FI_FRAG;
813
814	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
815	if (frag == NULL) {
816		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
817		return IPPROTO_NONE;
818	}
819
820	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
821		/*
822		 * Any fragment that isn't the last fragment must have its
823		 * length as a multiple of 8.
824		 */
825		if ((fin->fin_plen & 7) != 0) {
826			fin->fin_flx |= FI_BAD;
827			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
828		}
829	}
830
831	fin->fin_fraghdr = frag;
832	fin->fin_id = frag->ip6f_ident;
833	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
834	if (fin->fin_off != 0)
835		fin->fin_flx |= FI_FRAGBODY;
836
837	/*
838	 * Jumbograms aren't handled, so the max. length is 64k
839	 */
840	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
841		  fin->fin_flx |= FI_BAD;
842		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
843	}
844
845	/*
846	 * We don't know where the transport layer header (or whatever is next
847	 * is), as it could be behind destination options (amongst others) so
848	 * return the fragment header as the type of packet this is.  Note that
849	 * this effectively disables the fragment cache for > 1 protocol at a
850	 * time.
851	 */
852	return frag->ip6f_nxt;
853}
854
855
856/* ------------------------------------------------------------------------ */
857/* Function:    ipf_pr_dstopts6                                             */
858/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
859/* Parameters:  fin(I) - pointer to packet information                      */
860/*                                                                          */
861/* IPv6 Only                                                                */
862/* This is function checks pending destination options extension header     */
863/* ------------------------------------------------------------------------ */
864static INLINE int
865ipf_pr_dstopts6(fin)
866	fr_info_t *fin;
867{
868	ipf_main_softc_t *softc = fin->fin_main_soft;
869	struct ip6_ext *hdr;
870
871	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
872	if (hdr == NULL) {
873		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
874		return IPPROTO_NONE;
875	}
876	return hdr->ip6e_nxt;
877}
878
879
880/* ------------------------------------------------------------------------ */
881/* Function:    ipf_pr_icmp6                                                */
882/* Returns:     void                                                        */
883/* Parameters:  fin(I) - pointer to packet information                      */
884/*                                                                          */
885/* IPv6 Only                                                                */
886/* This routine is mainly concerned with determining the minimum valid size */
887/* for an ICMPv6 packet.                                                    */
888/* ------------------------------------------------------------------------ */
889static INLINE void
890ipf_pr_icmp6(fin)
891	fr_info_t *fin;
892{
893	int minicmpsz = sizeof(struct icmp6_hdr);
894	struct icmp6_hdr *icmp6;
895
896	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
897		ipf_main_softc_t *softc = fin->fin_main_soft;
898
899		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
900		return;
901	}
902
903	if (fin->fin_dlen > 1) {
904		ip6_t *ip6;
905
906		icmp6 = fin->fin_dp;
907
908		fin->fin_data[0] = *(u_short *)icmp6;
909
910		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
911			fin->fin_flx |= FI_ICMPQUERY;
912
913		switch (icmp6->icmp6_type)
914		{
915		case ICMP6_ECHO_REPLY :
916		case ICMP6_ECHO_REQUEST :
917			if (fin->fin_dlen >= 6)
918				fin->fin_data[1] = icmp6->icmp6_id;
919			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
920			break;
921
922		case ICMP6_DST_UNREACH :
923		case ICMP6_PACKET_TOO_BIG :
924		case ICMP6_TIME_EXCEEDED :
925		case ICMP6_PARAM_PROB :
926			fin->fin_flx |= FI_ICMPERR;
927			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
928			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
929				break;
930
931			if (M_LEN(fin->fin_m) < fin->fin_plen) {
932				if (ipf_coalesce(fin) != 1)
933					return;
934			}
935
936			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
937				return;
938
939			/*
940			 * If the destination of this packet doesn't match the
941			 * source of the original packet then this packet is
942			 * not correct.
943			 */
944			icmp6 = fin->fin_dp;
945			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
946			if (IP6_NEQ(&fin->fin_fi.fi_dst,
947				    (i6addr_t *)&ip6->ip6_src)) {
948				fin->fin_flx |= FI_BAD;
949				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
950			}
951			break;
952		default :
953			break;
954		}
955	}
956
957	ipf_pr_short6(fin, minicmpsz);
958	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
959		u_char p = fin->fin_p;
960
961		fin->fin_p = IPPROTO_ICMPV6;
962		ipf_checkv6sum(fin);
963		fin->fin_p = p;
964	}
965}
966
967
968/* ------------------------------------------------------------------------ */
969/* Function:    ipf_pr_udp6                                                 */
970/* Returns:     void                                                        */
971/* Parameters:  fin(I) - pointer to packet information                      */
972/*                                                                          */
973/* IPv6 Only                                                                */
974/* Analyse the packet for IPv6/UDP properties.                              */
975/* Is not expected to be called for fragmented packets.                     */
976/* ------------------------------------------------------------------------ */
977static INLINE void
978ipf_pr_udp6(fin)
979	fr_info_t *fin;
980{
981
982	if (ipf_pr_udpcommon(fin) == 0) {
983		u_char p = fin->fin_p;
984
985		fin->fin_p = IPPROTO_UDP;
986		ipf_checkv6sum(fin);
987		fin->fin_p = p;
988	}
989}
990
991
992/* ------------------------------------------------------------------------ */
993/* Function:    ipf_pr_tcp6                                                 */
994/* Returns:     void                                                        */
995/* Parameters:  fin(I) - pointer to packet information                      */
996/*                                                                          */
997/* IPv6 Only                                                                */
998/* Analyse the packet for IPv6/TCP properties.                              */
999/* Is not expected to be called for fragmented packets.                     */
1000/* ------------------------------------------------------------------------ */
1001static INLINE void
1002ipf_pr_tcp6(fin)
1003	fr_info_t *fin;
1004{
1005
1006	if (ipf_pr_tcpcommon(fin) == 0) {
1007		u_char p = fin->fin_p;
1008
1009		fin->fin_p = IPPROTO_TCP;
1010		ipf_checkv6sum(fin);
1011		fin->fin_p = p;
1012	}
1013}
1014
1015
1016/* ------------------------------------------------------------------------ */
1017/* Function:    ipf_pr_esp6                                                 */
1018/* Returns:     void                                                        */
1019/* Parameters:  fin(I) - pointer to packet information                      */
1020/*                                                                          */
1021/* IPv6 Only                                                                */
1022/* Analyse the packet for ESP properties.                                   */
1023/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1024/* even though the newer ESP packets must also have a sequence number that  */
1025/* is 32bits as well, it is not possible(?) to determine the version from a */
1026/* simple packet header.                                                    */
1027/* ------------------------------------------------------------------------ */
1028static INLINE void
1029ipf_pr_esp6(fin)
1030	fr_info_t *fin;
1031{
1032
1033	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1034		ipf_main_softc_t *softc = fin->fin_main_soft;
1035
1036		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1037		return;
1038	}
1039}
1040
1041
1042/* ------------------------------------------------------------------------ */
1043/* Function:    ipf_pr_ah6                                                  */
1044/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1045/* Parameters:  fin(I) - pointer to packet information                      */
1046/*                                                                          */
1047/* IPv6 Only                                                                */
1048/* Analyse the packet for AH properties.                                    */
1049/* The minimum length is taken to be the combination of all fields in the   */
1050/* header being present and no authentication data (null algorithm used.)   */
1051/* ------------------------------------------------------------------------ */
1052static INLINE int
1053ipf_pr_ah6(fin)
1054	fr_info_t *fin;
1055{
1056	authhdr_t *ah;
1057
1058	fin->fin_flx |= FI_AH;
1059
1060	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1061	if (ah == NULL) {
1062		ipf_main_softc_t *softc = fin->fin_main_soft;
1063
1064		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1065		return IPPROTO_NONE;
1066	}
1067
1068	ipf_pr_short6(fin, sizeof(*ah));
1069
1070	/*
1071	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1072	 * enough data to satisfy ah_next (the very first one.)
1073	 */
1074	return ah->ah_next;
1075}
1076
1077
1078/* ------------------------------------------------------------------------ */
1079/* Function:    ipf_pr_gre6                                                 */
1080/* Returns:     void                                                        */
1081/* Parameters:  fin(I) - pointer to packet information                      */
1082/*                                                                          */
1083/* Analyse the packet for GRE properties.                                   */
1084/* ------------------------------------------------------------------------ */
1085static INLINE void
1086ipf_pr_gre6(fin)
1087	fr_info_t *fin;
1088{
1089	grehdr_t *gre;
1090
1091	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1092		ipf_main_softc_t *softc = fin->fin_main_soft;
1093
1094		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1095		return;
1096	}
1097
1098	gre = fin->fin_dp;
1099	if (GRE_REV(gre->gr_flags) == 1)
1100		fin->fin_data[0] = gre->gr_call;
1101}
1102#endif	/* USE_INET6 */
1103
1104
1105/* ------------------------------------------------------------------------ */
1106/* Function:    ipf_pr_pullup                                               */
1107/* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1108/* Parameters:  fin(I)  - pointer to packet information                     */
1109/*              plen(I) - length (excluding L3 header) to pullup            */
1110/*                                                                          */
1111/* Short inline function to cut down on code duplication to perform a call  */
1112/* to ipf_pullup to ensure there is the required amount of data,            */
1113/* consecutively in the packet buffer.                                      */
1114/*                                                                          */
1115/* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1116/* points to the first byte after the complete layer 3 header, which will   */
1117/* include all of the known extension headers for IPv6 or options for IPv4. */
1118/*                                                                          */
1119/* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1120/* is necessary to add those we can already assume to be pulled up (fin_dp  */
1121/* - fin_ip) to what is passed through.                                     */
1122/* ------------------------------------------------------------------------ */
1123int
1124ipf_pr_pullup(fin, plen)
1125	fr_info_t *fin;
1126	int plen;
1127{
1128	ipf_main_softc_t *softc = fin->fin_main_soft;
1129
1130	if (fin->fin_m != NULL) {
1131		if (fin->fin_dp != NULL)
1132			plen += (char *)fin->fin_dp -
1133				((char *)fin->fin_ip + fin->fin_hlen);
1134		plen += fin->fin_hlen;
1135		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1136#if defined(_KERNEL)
1137			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1138				DT(ipf_pullup_fail);
1139				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1140				return -1;
1141			}
1142			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1143#else
1144			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1145			/*
1146			 * Fake ipf_pullup failing
1147			 */
1148			fin->fin_reason = FRB_PULLUP;
1149			*fin->fin_mp = NULL;
1150			fin->fin_m = NULL;
1151			fin->fin_ip = NULL;
1152			return -1;
1153#endif
1154		}
1155	}
1156	return 0;
1157}
1158
1159
1160/* ------------------------------------------------------------------------ */
1161/* Function:    ipf_pr_short                                                */
1162/* Returns:     void                                                        */
1163/* Parameters:  fin(I)  - pointer to packet information                     */
1164/*              xmin(I) - minimum header size                               */
1165/*                                                                          */
1166/* Check if a packet is "short" as defined by xmin.  The rule we are        */
1167/* applying here is that the packet must not be fragmented within the layer */
1168/* 4 header.  That is, it must not be a fragment that has its offset set to */
1169/* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1170/* entire layer 4 header must be present (min).                             */
1171/* ------------------------------------------------------------------------ */
1172static INLINE void
1173ipf_pr_short(fin, xmin)
1174	fr_info_t *fin;
1175	int xmin;
1176{
1177
1178	if (fin->fin_off == 0) {
1179		if (fin->fin_dlen < xmin)
1180			fin->fin_flx |= FI_SHORT;
1181	} else if (fin->fin_off < xmin) {
1182		fin->fin_flx |= FI_SHORT;
1183	}
1184}
1185
1186
1187/* ------------------------------------------------------------------------ */
1188/* Function:    ipf_pr_icmp                                                 */
1189/* Returns:     void                                                        */
1190/* Parameters:  fin(I) - pointer to packet information                      */
1191/*                                                                          */
1192/* IPv4 Only                                                                */
1193/* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1194/* except extrememly bad packets, both type and code will be present.       */
1195/* The expected minimum size of an ICMP packet is very much dependent on    */
1196/* the type of it.                                                          */
1197/*                                                                          */
1198/* XXX - other ICMP sanity checks?                                          */
1199/* ------------------------------------------------------------------------ */
1200static INLINE void
1201ipf_pr_icmp(fin)
1202	fr_info_t *fin;
1203{
1204	ipf_main_softc_t *softc = fin->fin_main_soft;
1205	int minicmpsz = sizeof(struct icmp);
1206	icmphdr_t *icmp;
1207	ip_t *oip;
1208
1209	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1210
1211	if (fin->fin_off != 0) {
1212		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1213		return;
1214	}
1215
1216	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1217		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1218		return;
1219	}
1220
1221	icmp = fin->fin_dp;
1222
1223	fin->fin_data[0] = *(u_short *)icmp;
1224	fin->fin_data[1] = icmp->icmp_id;
1225
1226	switch (icmp->icmp_type)
1227	{
1228	case ICMP_ECHOREPLY :
1229	case ICMP_ECHO :
1230	/* Router discovery messaes - RFC 1256 */
1231	case ICMP_ROUTERADVERT :
1232	case ICMP_ROUTERSOLICIT :
1233		fin->fin_flx |= FI_ICMPQUERY;
1234		minicmpsz = ICMP_MINLEN;
1235		break;
1236	/*
1237	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1238	 * 3 * timestamp(3 * 4)
1239	 */
1240	case ICMP_TSTAMP :
1241	case ICMP_TSTAMPREPLY :
1242		fin->fin_flx |= FI_ICMPQUERY;
1243		minicmpsz = 20;
1244		break;
1245	/*
1246	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1247	 * mask(4)
1248	 */
1249	case ICMP_IREQ :
1250	case ICMP_IREQREPLY :
1251	case ICMP_MASKREQ :
1252	case ICMP_MASKREPLY :
1253		fin->fin_flx |= FI_ICMPQUERY;
1254		minicmpsz = 12;
1255		break;
1256	/*
1257	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1258	 */
1259	case ICMP_UNREACH :
1260#ifdef icmp_nextmtu
1261		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1262			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1263				fin->fin_flx |= FI_BAD;
1264				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1265			}
1266		}
1267#endif
1268		/* FALLTHROUGH */
1269	case ICMP_SOURCEQUENCH :
1270	case ICMP_REDIRECT :
1271	case ICMP_TIMXCEED :
1272	case ICMP_PARAMPROB :
1273		fin->fin_flx |= FI_ICMPERR;
1274		if (ipf_coalesce(fin) != 1) {
1275			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1276			return;
1277		}
1278
1279		/*
1280		 * ICMP error packets should not be generated for IP
1281		 * packets that are a fragment that isn't the first
1282		 * fragment.
1283		 */
1284		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1285		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1286			fin->fin_flx |= FI_BAD;
1287			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1288		}
1289
1290		/*
1291		 * If the destination of this packet doesn't match the
1292		 * source of the original packet then this packet is
1293		 * not correct.
1294		 */
1295		if (oip->ip_src.s_addr != fin->fin_daddr) {
1296			fin->fin_flx |= FI_BAD;
1297			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1298		}
1299		break;
1300	default :
1301		break;
1302	}
1303
1304	ipf_pr_short(fin, minicmpsz);
1305
1306	ipf_checkv4sum(fin);
1307}
1308
1309
1310/* ------------------------------------------------------------------------ */
1311/* Function:    ipf_pr_tcpcommon                                            */
1312/* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1313/* Parameters:  fin(I) - pointer to packet information                      */
1314/*                                                                          */
1315/* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1316/* and make some checks with how they interact with other fields.           */
1317/* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1318/* valid and mark the packet as bad if not.                                 */
1319/* ------------------------------------------------------------------------ */
1320static INLINE int
1321ipf_pr_tcpcommon(fin)
1322	fr_info_t *fin;
1323{
1324	ipf_main_softc_t *softc = fin->fin_main_soft;
1325	int flags, tlen;
1326	tcphdr_t *tcp;
1327
1328	fin->fin_flx |= FI_TCPUDP;
1329	if (fin->fin_off != 0) {
1330		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1331		return 0;
1332	}
1333
1334	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1335		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1336		return -1;
1337	}
1338
1339	tcp = fin->fin_dp;
1340	if (fin->fin_dlen > 3) {
1341		fin->fin_sport = ntohs(tcp->th_sport);
1342		fin->fin_dport = ntohs(tcp->th_dport);
1343	}
1344
1345	if ((fin->fin_flx & FI_SHORT) != 0) {
1346		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1347		return 1;
1348	}
1349
1350	/*
1351	 * Use of the TCP data offset *must* result in a value that is at
1352	 * least the same size as the TCP header.
1353	 */
1354	tlen = TCP_OFF(tcp) << 2;
1355	if (tlen < sizeof(tcphdr_t)) {
1356		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1357		fin->fin_flx |= FI_BAD;
1358		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1359		return 1;
1360	}
1361
1362	flags = tcp->th_flags;
1363	fin->fin_tcpf = tcp->th_flags;
1364
1365	/*
1366	 * If the urgent flag is set, then the urgent pointer must
1367	 * also be set and vice versa.  Good TCP packets do not have
1368	 * just one of these set.
1369	 */
1370	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1371		fin->fin_flx |= FI_BAD;
1372		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1373#if 0
1374	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1375		/*
1376		 * Ignore this case (#if 0) as it shows up in "real"
1377		 * traffic with bogus values in the urgent pointer field.
1378		 */
1379		fin->fin_flx |= FI_BAD;
1380		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1381#endif
1382	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1383		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1384		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1385		fin->fin_flx |= FI_BAD;
1386		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1387#if 1
1388	} else if (((flags & TH_SYN) != 0) &&
1389		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1390		/*
1391		 * SYN with URG and PUSH set is not for normal TCP but it is
1392		 * possible(?) with T/TCP...but who uses T/TCP?
1393		 */
1394		fin->fin_flx |= FI_BAD;
1395		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1396#endif
1397	} else if (!(flags & TH_ACK)) {
1398		/*
1399		 * If the ack bit isn't set, then either the SYN or
1400		 * RST bit must be set.  If the SYN bit is set, then
1401		 * we expect the ACK field to be 0.  If the ACK is
1402		 * not set and if URG, PSH or FIN are set, consdier
1403		 * that to indicate a bad TCP packet.
1404		 */
1405		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1406			/*
1407			 * Cisco PIX sets the ACK field to a random value.
1408			 * In light of this, do not set FI_BAD until a patch
1409			 * is available from Cisco to ensure that
1410			 * interoperability between existing systems is
1411			 * achieved.
1412			 */
1413			/*fin->fin_flx |= FI_BAD*/;
1414			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1415		} else if (!(flags & (TH_RST|TH_SYN))) {
1416			fin->fin_flx |= FI_BAD;
1417			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1418		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1419			fin->fin_flx |= FI_BAD;
1420			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1421		}
1422	}
1423	if (fin->fin_flx & FI_BAD) {
1424		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1425		return 1;
1426	}
1427
1428	/*
1429	 * At this point, it's not exactly clear what is to be gained by
1430	 * marking up which TCP options are and are not present.  The one we
1431	 * are most interested in is the TCP window scale.  This is only in
1432	 * a SYN packet [RFC1323] so we don't need this here...?
1433	 * Now if we were to analyse the header for passive fingerprinting,
1434	 * then that might add some weight to adding this...
1435	 */
1436	if (tlen == sizeof(tcphdr_t)) {
1437		return 0;
1438	}
1439
1440	if (ipf_pr_pullup(fin, tlen) == -1) {
1441		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1442		return -1;
1443	}
1444
1445#if 0
1446	tcp = fin->fin_dp;
1447	ip = fin->fin_ip;
1448	s = (u_char *)(tcp + 1);
1449	off = IP_HL(ip) << 2;
1450# ifdef _KERNEL
1451	if (fin->fin_mp != NULL) {
1452		mb_t *m = *fin->fin_mp;
1453
1454		if (off + tlen > M_LEN(m))
1455			return;
1456	}
1457# endif
1458	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1459		opt = *s;
1460		if (opt == '\0')
1461			break;
1462		else if (opt == TCPOPT_NOP)
1463			ol = 1;
1464		else {
1465			if (tlen < 2)
1466				break;
1467			ol = (int)*(s + 1);
1468			if (ol < 2 || ol > tlen)
1469				break;
1470		}
1471
1472		for (i = 9, mv = 4; mv >= 0; ) {
1473			op = ipopts + i;
1474			if (opt == (u_char)op->ol_val) {
1475				optmsk |= op->ol_bit;
1476				break;
1477			}
1478		}
1479		tlen -= ol;
1480		s += ol;
1481	}
1482#endif /* 0 */
1483
1484	return 0;
1485}
1486
1487
1488
1489/* ------------------------------------------------------------------------ */
1490/* Function:    ipf_pr_udpcommon                                            */
1491/* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1492/* Parameters:  fin(I) - pointer to packet information                      */
1493/*                                                                          */
1494/* Extract the UDP source and destination ports, if present.  If compiled   */
1495/* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1496/* ------------------------------------------------------------------------ */
1497static INLINE int
1498ipf_pr_udpcommon(fin)
1499	fr_info_t *fin;
1500{
1501	udphdr_t *udp;
1502
1503	fin->fin_flx |= FI_TCPUDP;
1504
1505	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1506		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1507			ipf_main_softc_t *softc = fin->fin_main_soft;
1508
1509			fin->fin_flx |= FI_SHORT;
1510			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1511			return 1;
1512		}
1513
1514		udp = fin->fin_dp;
1515
1516		fin->fin_sport = ntohs(udp->uh_sport);
1517		fin->fin_dport = ntohs(udp->uh_dport);
1518	}
1519
1520	return 0;
1521}
1522
1523
1524/* ------------------------------------------------------------------------ */
1525/* Function:    ipf_pr_tcp                                                  */
1526/* Returns:     void                                                        */
1527/* Parameters:  fin(I) - pointer to packet information                      */
1528/*                                                                          */
1529/* IPv4 Only                                                                */
1530/* Analyse the packet for IPv4/TCP properties.                              */
1531/* ------------------------------------------------------------------------ */
1532static INLINE void
1533ipf_pr_tcp(fin)
1534	fr_info_t *fin;
1535{
1536
1537	ipf_pr_short(fin, sizeof(tcphdr_t));
1538
1539	if (ipf_pr_tcpcommon(fin) == 0)
1540		ipf_checkv4sum(fin);
1541}
1542
1543
1544/* ------------------------------------------------------------------------ */
1545/* Function:    ipf_pr_udp                                                  */
1546/* Returns:     void                                                        */
1547/* Parameters:  fin(I) - pointer to packet information                      */
1548/*                                                                          */
1549/* IPv4 Only                                                                */
1550/* Analyse the packet for IPv4/UDP properties.                              */
1551/* ------------------------------------------------------------------------ */
1552static INLINE void
1553ipf_pr_udp(fin)
1554	fr_info_t *fin;
1555{
1556
1557	ipf_pr_short(fin, sizeof(udphdr_t));
1558
1559	if (ipf_pr_udpcommon(fin) == 0)
1560		ipf_checkv4sum(fin);
1561}
1562
1563
1564/* ------------------------------------------------------------------------ */
1565/* Function:    ipf_pr_esp                                                  */
1566/* Returns:     void                                                        */
1567/* Parameters:  fin(I) - pointer to packet information                      */
1568/*                                                                          */
1569/* Analyse the packet for ESP properties.                                   */
1570/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1571/* even though the newer ESP packets must also have a sequence number that  */
1572/* is 32bits as well, it is not possible(?) to determine the version from a */
1573/* simple packet header.                                                    */
1574/* ------------------------------------------------------------------------ */
1575static INLINE void
1576ipf_pr_esp(fin)
1577	fr_info_t *fin;
1578{
1579
1580	if (fin->fin_off == 0) {
1581		ipf_pr_short(fin, 8);
1582		if (ipf_pr_pullup(fin, 8) == -1) {
1583			ipf_main_softc_t *softc = fin->fin_main_soft;
1584
1585			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1586		}
1587	}
1588}
1589
1590
1591/* ------------------------------------------------------------------------ */
1592/* Function:    ipf_pr_ah                                                   */
1593/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1594/* Parameters:  fin(I) - pointer to packet information                      */
1595/*                                                                          */
1596/* Analyse the packet for AH properties.                                    */
1597/* The minimum length is taken to be the combination of all fields in the   */
1598/* header being present and no authentication data (null algorithm used.)   */
1599/* ------------------------------------------------------------------------ */
1600static INLINE int
1601ipf_pr_ah(fin)
1602	fr_info_t *fin;
1603{
1604	ipf_main_softc_t *softc = fin->fin_main_soft;
1605	authhdr_t *ah;
1606	int len;
1607
1608	fin->fin_flx |= FI_AH;
1609	ipf_pr_short(fin, sizeof(*ah));
1610
1611	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1612		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1613		return IPPROTO_NONE;
1614	}
1615
1616	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1617		DT(fr_v4_ah_pullup_1);
1618		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1619		return IPPROTO_NONE;
1620	}
1621
1622	ah = (authhdr_t *)fin->fin_dp;
1623
1624	len = (ah->ah_plen + 2) << 2;
1625	ipf_pr_short(fin, len);
1626	if (ipf_pr_pullup(fin, len) == -1) {
1627		DT(fr_v4_ah_pullup_2);
1628		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1629		return IPPROTO_NONE;
1630	}
1631
1632	/*
1633	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1634	 * header.
1635	 */
1636	fin->fin_dp = (char *)fin->fin_dp + len;
1637	fin->fin_dlen -= len;
1638	return ah->ah_next;
1639}
1640
1641
1642/* ------------------------------------------------------------------------ */
1643/* Function:    ipf_pr_gre                                                  */
1644/* Returns:     void                                                        */
1645/* Parameters:  fin(I) - pointer to packet information                      */
1646/*                                                                          */
1647/* Analyse the packet for GRE properties.                                   */
1648/* ------------------------------------------------------------------------ */
1649static INLINE void
1650ipf_pr_gre(fin)
1651	fr_info_t *fin;
1652{
1653	ipf_main_softc_t *softc = fin->fin_main_soft;
1654	grehdr_t *gre;
1655
1656	ipf_pr_short(fin, sizeof(grehdr_t));
1657
1658	if (fin->fin_off != 0) {
1659		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1660		return;
1661	}
1662
1663	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1664		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1665		return;
1666	}
1667
1668	gre = fin->fin_dp;
1669	if (GRE_REV(gre->gr_flags) == 1)
1670		fin->fin_data[0] = gre->gr_call;
1671}
1672
1673
1674/* ------------------------------------------------------------------------ */
1675/* Function:    ipf_pr_ipv4hdr                                              */
1676/* Returns:     void                                                        */
1677/* Parameters:  fin(I) - pointer to packet information                      */
1678/*                                                                          */
1679/* IPv4 Only                                                                */
1680/* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1681/* Check all options present and flag their presence if any exist.          */
1682/* ------------------------------------------------------------------------ */
1683static INLINE void
1684ipf_pr_ipv4hdr(fin)
1685	fr_info_t *fin;
1686{
1687	u_short optmsk = 0, secmsk = 0, auth = 0;
1688	int hlen, ol, mv, p, i;
1689	const struct optlist *op;
1690	u_char *s, opt;
1691	u_short off;
1692	fr_ip_t *fi;
1693	ip_t *ip;
1694
1695	fi = &fin->fin_fi;
1696	hlen = fin->fin_hlen;
1697
1698	ip = fin->fin_ip;
1699	p = ip->ip_p;
1700	fi->fi_p = p;
1701	fin->fin_crc = p;
1702	fi->fi_tos = ip->ip_tos;
1703	fin->fin_id = ip->ip_id;
1704	off = ntohs(ip->ip_off);
1705
1706	/* Get both TTL and protocol */
1707	fi->fi_p = ip->ip_p;
1708	fi->fi_ttl = ip->ip_ttl;
1709
1710	/* Zero out bits not used in IPv6 address */
1711	fi->fi_src.i6[1] = 0;
1712	fi->fi_src.i6[2] = 0;
1713	fi->fi_src.i6[3] = 0;
1714	fi->fi_dst.i6[1] = 0;
1715	fi->fi_dst.i6[2] = 0;
1716	fi->fi_dst.i6[3] = 0;
1717
1718	fi->fi_saddr = ip->ip_src.s_addr;
1719	fin->fin_crc += fi->fi_saddr;
1720	fi->fi_daddr = ip->ip_dst.s_addr;
1721	fin->fin_crc += fi->fi_daddr;
1722	if (IN_CLASSD(ntohl(fi->fi_daddr)))
1723		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1724
1725	/*
1726	 * set packet attribute flags based on the offset and
1727	 * calculate the byte offset that it represents.
1728	 */
1729	off &= IP_MF|IP_OFFMASK;
1730	if (off != 0) {
1731		int morefrag = off & IP_MF;
1732
1733		fi->fi_flx |= FI_FRAG;
1734		off &= IP_OFFMASK;
1735		if (off == 1 && p == IPPROTO_TCP) {
1736			fin->fin_flx |= FI_SHORT;	/* RFC 3128 */
1737			DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1738		}
1739		if (off != 0) {
1740			fin->fin_flx |= FI_FRAGBODY;
1741			off <<= 3;
1742			if ((off + fin->fin_dlen > 65535) ||
1743			    (fin->fin_dlen == 0) ||
1744			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1745				/*
1746				 * The length of the packet, starting at its
1747				 * offset cannot exceed 65535 (0xffff) as the
1748				 * length of an IP packet is only 16 bits.
1749				 *
1750				 * Any fragment that isn't the last fragment
1751				 * must have a length greater than 0 and it
1752				 * must be an even multiple of 8.
1753				 */
1754				fi->fi_flx |= FI_BAD;
1755				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1756			}
1757		}
1758	}
1759	fin->fin_off = off;
1760
1761	/*
1762	 * Call per-protocol setup and checking
1763	 */
1764	if (p == IPPROTO_AH) {
1765		/*
1766		 * Treat AH differently because we expect there to be another
1767		 * layer 4 header after it.
1768		 */
1769		p = ipf_pr_ah(fin);
1770	}
1771
1772	switch (p)
1773	{
1774	case IPPROTO_UDP :
1775		ipf_pr_udp(fin);
1776		break;
1777	case IPPROTO_TCP :
1778		ipf_pr_tcp(fin);
1779		break;
1780	case IPPROTO_ICMP :
1781		ipf_pr_icmp(fin);
1782		break;
1783	case IPPROTO_ESP :
1784		ipf_pr_esp(fin);
1785		break;
1786	case IPPROTO_GRE :
1787		ipf_pr_gre(fin);
1788		break;
1789	}
1790
1791	ip = fin->fin_ip;
1792	if (ip == NULL)
1793		return;
1794
1795	/*
1796	 * If it is a standard IP header (no options), set the flag fields
1797	 * which relate to options to 0.
1798	 */
1799	if (hlen == sizeof(*ip)) {
1800		fi->fi_optmsk = 0;
1801		fi->fi_secmsk = 0;
1802		fi->fi_auth = 0;
1803		return;
1804	}
1805
1806	/*
1807	 * So the IP header has some IP options attached.  Walk the entire
1808	 * list of options present with this packet and set flags to indicate
1809	 * which ones are here and which ones are not.  For the somewhat out
1810	 * of date and obscure security classification options, set a flag to
1811	 * represent which classification is present.
1812	 */
1813	fi->fi_flx |= FI_OPTIONS;
1814
1815	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1816		opt = *s;
1817		if (opt == '\0')
1818			break;
1819		else if (opt == IPOPT_NOP)
1820			ol = 1;
1821		else {
1822			if (hlen < 2)
1823				break;
1824			ol = (int)*(s + 1);
1825			if (ol < 2 || ol > hlen)
1826				break;
1827		}
1828		for (i = 9, mv = 4; mv >= 0; ) {
1829			op = ipopts + i;
1830
1831			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1832				u_32_t doi;
1833
1834				switch (opt)
1835				{
1836				case IPOPT_SECURITY :
1837					if (optmsk & op->ol_bit) {
1838						fin->fin_flx |= FI_BAD;
1839						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1840					} else {
1841						doi = ipf_checkripso(s);
1842						secmsk = doi >> 16;
1843						auth = doi & 0xffff;
1844					}
1845					break;
1846
1847				case IPOPT_CIPSO :
1848
1849					if (optmsk & op->ol_bit) {
1850						fin->fin_flx |= FI_BAD;
1851						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1852					} else {
1853						doi = ipf_checkcipso(fin,
1854								     s, ol);
1855						secmsk = doi >> 16;
1856						auth = doi & 0xffff;
1857					}
1858					break;
1859				}
1860				optmsk |= op->ol_bit;
1861			}
1862
1863			if (opt < op->ol_val)
1864				i -= mv;
1865			else
1866				i += mv;
1867			mv--;
1868		}
1869		hlen -= ol;
1870		s += ol;
1871	}
1872
1873	/*
1874	 *
1875	 */
1876	if (auth && !(auth & 0x0100))
1877		auth &= 0xff00;
1878	fi->fi_optmsk = optmsk;
1879	fi->fi_secmsk = secmsk;
1880	fi->fi_auth = auth;
1881}
1882
1883
1884/* ------------------------------------------------------------------------ */
1885/* Function:    ipf_checkripso                                              */
1886/* Returns:     void                                                        */
1887/* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1888/*                                                                          */
1889/* ------------------------------------------------------------------------ */
1890static u_32_t
1891ipf_checkripso(s)
1892	u_char *s;
1893{
1894	const struct optlist *sp;
1895	u_short secmsk = 0, auth = 0;
1896	u_char sec;
1897	int j, m;
1898
1899	sec = *(s + 2);	/* classification */
1900	for (j = 3, m = 2; m >= 0; ) {
1901		sp = secopt + j;
1902		if (sec == sp->ol_val) {
1903			secmsk |= sp->ol_bit;
1904			auth = *(s + 3);
1905			auth *= 256;
1906			auth += *(s + 4);
1907			break;
1908		}
1909		if (sec < sp->ol_val)
1910			j -= m;
1911		else
1912			j += m;
1913		m--;
1914	}
1915
1916	return (secmsk << 16) | auth;
1917}
1918
1919
1920/* ------------------------------------------------------------------------ */
1921/* Function:    ipf_checkcipso                                              */
1922/* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1923/* Parameters:  fin(IO) - pointer to packet information                     */
1924/*              s(I)    - pointer to start of CIPSO option                  */
1925/*              ol(I)   - length of CIPSO option field                      */
1926/*                                                                          */
1927/* This function returns the domain of integrity (DOI) field from the CIPSO */
1928/* header and returns that whilst also storing the highest sensitivity      */
1929/* value found in the fr_info_t structure.                                  */
1930/*                                                                          */
1931/* No attempt is made to extract the category bitmaps as these are defined  */
1932/* by the user (rather than the protocol) and can be rather numerous on the */
1933/* end nodes.                                                               */
1934/* ------------------------------------------------------------------------ */
1935static u_32_t
1936ipf_checkcipso(fin, s, ol)
1937	fr_info_t *fin;
1938	u_char *s;
1939	int ol;
1940{
1941	ipf_main_softc_t *softc = fin->fin_main_soft;
1942	fr_ip_t *fi;
1943	u_32_t doi;
1944	u_char *t, tag, tlen, sensitivity;
1945	int len;
1946
1947	if (ol < 6 || ol > 40) {
1948		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1949		fin->fin_flx |= FI_BAD;
1950		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1951		return 0;
1952	}
1953
1954	fi = &fin->fin_fi;
1955	fi->fi_sensitivity = 0;
1956	/*
1957	 * The DOI field MUST be there.
1958	 */
1959	bcopy(s + 2, &doi, sizeof(doi));
1960
1961	t = (u_char *)s + 6;
1962	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1963		tag = *t;
1964		tlen = *(t + 1);
1965		if (tlen > len || tlen < 4 || tlen > 34) {
1966			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1967			fin->fin_flx |= FI_BAD;
1968			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1969			return 0;
1970		}
1971
1972		sensitivity = 0;
1973		/*
1974		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1975		 * draft (16 July 1992) that has expired.
1976		 */
1977		if (tag == 0) {
1978			fin->fin_flx |= FI_BAD;
1979			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1980			continue;
1981		} else if (tag == 1) {
1982			if (*(t + 2) != 0) {
1983				fin->fin_flx |= FI_BAD;
1984				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1985				continue;
1986			}
1987			sensitivity = *(t + 3);
1988			/* Category bitmap for categories 0-239 */
1989
1990		} else if (tag == 4) {
1991			if (*(t + 2) != 0) {
1992				fin->fin_flx |= FI_BAD;
1993				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1994				continue;
1995			}
1996			sensitivity = *(t + 3);
1997			/* Enumerated categories, 16bits each, upto 15 */
1998
1999		} else if (tag == 5) {
2000			if (*(t + 2) != 0) {
2001				fin->fin_flx |= FI_BAD;
2002				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
2003				continue;
2004			}
2005			sensitivity = *(t + 3);
2006			/* Range of categories (2*16bits), up to 7 pairs */
2007
2008		} else if (tag > 127) {
2009			/* Custom defined DOI */
2010			;
2011		} else {
2012			fin->fin_flx |= FI_BAD;
2013			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2014			continue;
2015		}
2016
2017		if (sensitivity > fi->fi_sensitivity)
2018			fi->fi_sensitivity = sensitivity;
2019	}
2020
2021	return doi;
2022}
2023
2024
2025/* ------------------------------------------------------------------------ */
2026/* Function:    ipf_makefrip                                                */
2027/* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2028/* Parameters:  hlen(I) - length of IP packet header                        */
2029/*              ip(I)   - pointer to the IP header                          */
2030/*              fin(IO) - pointer to packet information                     */
2031/*                                                                          */
2032/* Compact the IP header into a structure which contains just the info.     */
2033/* which is useful for comparing IP headers with and store this information */
2034/* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2035/* this function will be called with either an IPv4 or IPv6 packet.         */
2036/* ------------------------------------------------------------------------ */
2037int
2038ipf_makefrip(hlen, ip, fin)
2039	int hlen;
2040	ip_t *ip;
2041	fr_info_t *fin;
2042{
2043	ipf_main_softc_t *softc = fin->fin_main_soft;
2044	int v;
2045
2046	fin->fin_depth = 0;
2047	fin->fin_hlen = (u_short)hlen;
2048	fin->fin_ip = ip;
2049	fin->fin_rule = 0xffffffff;
2050	fin->fin_group[0] = -1;
2051	fin->fin_group[1] = '\0';
2052	fin->fin_dp = (char *)ip + hlen;
2053
2054	v = fin->fin_v;
2055	if (v == 4) {
2056		fin->fin_plen = ntohs(ip->ip_len);
2057		fin->fin_dlen = fin->fin_plen - hlen;
2058		ipf_pr_ipv4hdr(fin);
2059#ifdef	USE_INET6
2060	} else if (v == 6) {
2061		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2062		fin->fin_dlen = fin->fin_plen;
2063		fin->fin_plen += hlen;
2064
2065		ipf_pr_ipv6hdr(fin);
2066#endif
2067	}
2068	if (fin->fin_ip == NULL) {
2069		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2070		return -1;
2071	}
2072	return 0;
2073}
2074
2075
2076/* ------------------------------------------------------------------------ */
2077/* Function:    ipf_portcheck                                               */
2078/* Returns:     int - 1 == port matched, 0 == port match failed             */
2079/* Parameters:  frp(I) - pointer to port check `expression'                 */
2080/*              pop(I) - port number to evaluate                            */
2081/*                                                                          */
2082/* Perform a comparison of a port number against some other(s), using a     */
2083/* structure with compare information stored in it.                         */
2084/* ------------------------------------------------------------------------ */
2085static INLINE int
2086ipf_portcheck(frp, pop)
2087	frpcmp_t *frp;
2088	u_32_t pop;
2089{
2090	int err = 1;
2091	u_32_t po;
2092
2093	po = frp->frp_port;
2094
2095	/*
2096	 * Do opposite test to that required and continue if that succeeds.
2097	 */
2098	switch (frp->frp_cmp)
2099	{
2100	case FR_EQUAL :
2101		if (pop != po) /* EQUAL */
2102			err = 0;
2103		break;
2104	case FR_NEQUAL :
2105		if (pop == po) /* NOTEQUAL */
2106			err = 0;
2107		break;
2108	case FR_LESST :
2109		if (pop >= po) /* LESSTHAN */
2110			err = 0;
2111		break;
2112	case FR_GREATERT :
2113		if (pop <= po) /* GREATERTHAN */
2114			err = 0;
2115		break;
2116	case FR_LESSTE :
2117		if (pop > po) /* LT or EQ */
2118			err = 0;
2119		break;
2120	case FR_GREATERTE :
2121		if (pop < po) /* GT or EQ */
2122			err = 0;
2123		break;
2124	case FR_OUTRANGE :
2125		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2126			err = 0;
2127		break;
2128	case FR_INRANGE :
2129		if (pop <= po || pop >= frp->frp_top) /* In range */
2130			err = 0;
2131		break;
2132	case FR_INCRANGE :
2133		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2134			err = 0;
2135		break;
2136	default :
2137		break;
2138	}
2139	return err;
2140}
2141
2142
2143/* ------------------------------------------------------------------------ */
2144/* Function:    ipf_tcpudpchk                                               */
2145/* Returns:     int - 1 == protocol matched, 0 == check failed              */
2146/* Parameters:  fda(I) - pointer to packet information                      */
2147/*              ft(I)  - pointer to structure with comparison data          */
2148/*                                                                          */
2149/* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2150/* structure containing information that we want to match against.          */
2151/* ------------------------------------------------------------------------ */
2152int
2153ipf_tcpudpchk(fi, ft)
2154	fr_ip_t *fi;
2155	frtuc_t *ft;
2156{
2157	int err = 1;
2158
2159	/*
2160	 * Both ports should *always* be in the first fragment.
2161	 * So far, I cannot find any cases where they can not be.
2162	 *
2163	 * compare destination ports
2164	 */
2165	if (ft->ftu_dcmp)
2166		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2167
2168	/*
2169	 * compare source ports
2170	 */
2171	if (err && ft->ftu_scmp)
2172		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2173
2174	/*
2175	 * If we don't have all the TCP/UDP header, then how can we
2176	 * expect to do any sort of match on it ?  If we were looking for
2177	 * TCP flags, then NO match.  If not, then match (which should
2178	 * satisfy the "short" class too).
2179	 */
2180	if (err && (fi->fi_p == IPPROTO_TCP)) {
2181		if (fi->fi_flx & FI_SHORT)
2182			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2183		/*
2184		 * Match the flags ?  If not, abort this match.
2185		 */
2186		if (ft->ftu_tcpfm &&
2187		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2188			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2189				 ft->ftu_tcpfm, ft->ftu_tcpf));
2190			err = 0;
2191		}
2192	}
2193	return err;
2194}
2195
2196
2197/* ------------------------------------------------------------------------ */
2198/* Function:    ipf_check_ipf                                               */
2199/* Returns:     int - 0 == match, else no match                             */
2200/* Parameters:  fin(I)     - pointer to packet information                  */
2201/*              fr(I)      - pointer to filter rule                         */
2202/*              portcmp(I) - flag indicating whether to attempt matching on */
2203/*                           TCP/UDP port data.                             */
2204/*                                                                          */
2205/* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2206/* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2207/* this function.                                                           */
2208/* ------------------------------------------------------------------------ */
2209static INLINE int
2210ipf_check_ipf(fin, fr, portcmp)
2211	fr_info_t *fin;
2212	frentry_t *fr;
2213	int portcmp;
2214{
2215	u_32_t	*ld, *lm, *lip;
2216	fripf_t *fri;
2217	fr_ip_t *fi;
2218	int i;
2219
2220	fi = &fin->fin_fi;
2221	fri = fr->fr_ipf;
2222	lip = (u_32_t *)fi;
2223	lm = (u_32_t *)&fri->fri_mip;
2224	ld = (u_32_t *)&fri->fri_ip;
2225
2226	/*
2227	 * first 32 bits to check coversion:
2228	 * IP version, TOS, TTL, protocol
2229	 */
2230	i = ((*lip & *lm) != *ld);
2231	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2232		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2233	if (i)
2234		return 1;
2235
2236	/*
2237	 * Next 32 bits is a constructed bitmask indicating which IP options
2238	 * are present (if any) in this packet.
2239	 */
2240	lip++, lm++, ld++;
2241	i = ((*lip & *lm) != *ld);
2242	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2243		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2244	if (i != 0)
2245		return 1;
2246
2247	lip++, lm++, ld++;
2248	/*
2249	 * Unrolled loops (4 each, for 32 bits) for address checks.
2250	 */
2251	/*
2252	 * Check the source address.
2253	 */
2254	if (fr->fr_satype == FRI_LOOKUP) {
2255		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2256				      fi->fi_v, lip, fin->fin_plen);
2257		if (i == -1)
2258			return 1;
2259		lip += 3;
2260		lm += 3;
2261		ld += 3;
2262	} else {
2263		i = ((*lip & *lm) != *ld);
2264		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2265			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2266		if (fi->fi_v == 6) {
2267			lip++, lm++, ld++;
2268			i |= ((*lip & *lm) != *ld);
2269			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2270				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271			lip++, lm++, ld++;
2272			i |= ((*lip & *lm) != *ld);
2273			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2274				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2275			lip++, lm++, ld++;
2276			i |= ((*lip & *lm) != *ld);
2277			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2278				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2279		} else {
2280			lip += 3;
2281			lm += 3;
2282			ld += 3;
2283		}
2284	}
2285	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2286	if (i != 0)
2287		return 1;
2288
2289	/*
2290	 * Check the destination address.
2291	 */
2292	lip++, lm++, ld++;
2293	if (fr->fr_datype == FRI_LOOKUP) {
2294		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2295				      fi->fi_v, lip, fin->fin_plen);
2296		if (i == -1)
2297			return 1;
2298		lip += 3;
2299		lm += 3;
2300		ld += 3;
2301	} else {
2302		i = ((*lip & *lm) != *ld);
2303		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2304			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2305		if (fi->fi_v == 6) {
2306			lip++, lm++, ld++;
2307			i |= ((*lip & *lm) != *ld);
2308			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2309				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310			lip++, lm++, ld++;
2311			i |= ((*lip & *lm) != *ld);
2312			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2313				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2314			lip++, lm++, ld++;
2315			i |= ((*lip & *lm) != *ld);
2316			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2317				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2318		} else {
2319			lip += 3;
2320			lm += 3;
2321			ld += 3;
2322		}
2323	}
2324	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2325	if (i != 0)
2326		return 1;
2327	/*
2328	 * IP addresses matched.  The next 32bits contains:
2329	 * mast of old IP header security & authentication bits.
2330	 */
2331	lip++, lm++, ld++;
2332	i = (*ld - (*lip & *lm));
2333	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2334
2335	/*
2336	 * Next we have 32 bits of packet flags.
2337	 */
2338	lip++, lm++, ld++;
2339	i |= (*ld - (*lip & *lm));
2340	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2341
2342	if (i == 0) {
2343		/*
2344		 * If a fragment, then only the first has what we're
2345		 * looking for here...
2346		 */
2347		if (portcmp) {
2348			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2349				i = 1;
2350		} else {
2351			if (fr->fr_dcmp || fr->fr_scmp ||
2352			    fr->fr_tcpf || fr->fr_tcpfm)
2353				i = 1;
2354			if (fr->fr_icmpm || fr->fr_icmp) {
2355				if (((fi->fi_p != IPPROTO_ICMP) &&
2356				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2357				    fin->fin_off || (fin->fin_dlen < 2))
2358					i = 1;
2359				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2360					 fr->fr_icmp) {
2361					FR_DEBUG(("i. %#x & %#x != %#x\n",
2362						 fin->fin_data[0],
2363						 fr->fr_icmpm, fr->fr_icmp));
2364					i = 1;
2365				}
2366			}
2367		}
2368	}
2369	return i;
2370}
2371
2372
2373/* ------------------------------------------------------------------------ */
2374/* Function:    ipf_scanlist                                                */
2375/* Returns:     int - result flags of scanning filter list                  */
2376/* Parameters:  fin(I) - pointer to packet information                      */
2377/*              pass(I) - default result to return for filtering            */
2378/*                                                                          */
2379/* Check the input/output list of rules for a match to the current packet.  */
2380/* If a match is found, the value of fr_flags from the rule becomes the     */
2381/* return value and fin->fin_fr points to the matched rule.                 */
2382/*                                                                          */
2383/* This function may be called recusively upto 16 times (limit inbuilt.)    */
2384/* When unwinding, it should finish up with fin_depth as 0.                 */
2385/*                                                                          */
2386/* Could be per interface, but this gets real nasty when you don't have,    */
2387/* or can't easily change, the kernel source code to .                      */
2388/* ------------------------------------------------------------------------ */
2389int
2390ipf_scanlist(fin, pass)
2391	fr_info_t *fin;
2392	u_32_t pass;
2393{
2394	ipf_main_softc_t *softc = fin->fin_main_soft;
2395	int rulen, portcmp, off, skip;
2396	struct frentry *fr, *fnext;
2397	u_32_t passt, passo;
2398
2399	/*
2400	 * Do not allow nesting deeper than 16 levels.
2401	 */
2402	if (fin->fin_depth >= 16)
2403		return pass;
2404
2405	fr = fin->fin_fr;
2406
2407	/*
2408	 * If there are no rules in this list, return now.
2409	 */
2410	if (fr == NULL)
2411		return pass;
2412
2413	skip = 0;
2414	portcmp = 0;
2415	fin->fin_depth++;
2416	fin->fin_fr = NULL;
2417	off = fin->fin_off;
2418
2419	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2420		portcmp = 1;
2421
2422	for (rulen = 0; fr; fr = fnext, rulen++) {
2423		fnext = fr->fr_next;
2424		if (skip != 0) {
2425			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2426			skip--;
2427			continue;
2428		}
2429
2430		/*
2431		 * In all checks below, a null (zero) value in the
2432		 * filter struture is taken to mean a wildcard.
2433		 *
2434		 * check that we are working for the right interface
2435		 */
2436#ifdef	_KERNEL
2437		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2438			continue;
2439#else
2440		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2441			printf("\n");
2442		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2443				  FR_ISPASS(pass) ? 'p' :
2444				  FR_ISACCOUNT(pass) ? 'A' :
2445				  FR_ISAUTH(pass) ? 'a' :
2446				  (pass & FR_NOMATCH) ? 'n' :'b'));
2447		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2448			continue;
2449		FR_VERBOSE((":i"));
2450#endif
2451
2452		switch (fr->fr_type)
2453		{
2454		case FR_T_IPF :
2455		case FR_T_IPF_BUILTIN :
2456			if (ipf_check_ipf(fin, fr, portcmp))
2457				continue;
2458			break;
2459#if defined(IPFILTER_BPF)
2460		case FR_T_BPFOPC :
2461		case FR_T_BPFOPC_BUILTIN :
2462		    {
2463			u_char *mc;
2464			int wlen;
2465
2466			if (*fin->fin_mp == NULL)
2467				continue;
2468			if (fin->fin_family != fr->fr_family)
2469				continue;
2470			mc = (u_char *)fin->fin_m;
2471			wlen = fin->fin_dlen + fin->fin_hlen;
2472			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2473				continue;
2474			break;
2475		    }
2476#endif
2477		case FR_T_CALLFUNC_BUILTIN :
2478		    {
2479			frentry_t *f;
2480
2481			f = (*fr->fr_func)(fin, &pass);
2482			if (f != NULL)
2483				fr = f;
2484			else
2485				continue;
2486			break;
2487		    }
2488
2489		case FR_T_IPFEXPR :
2490		case FR_T_IPFEXPR_BUILTIN :
2491			if (fin->fin_family != fr->fr_family)
2492				continue;
2493			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2494				continue;
2495			break;
2496
2497		default :
2498			break;
2499		}
2500
2501		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2502			if (fin->fin_nattag == NULL)
2503				continue;
2504			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2505				continue;
2506		}
2507		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2508
2509		passt = fr->fr_flags;
2510
2511		/*
2512		 * If the rule is a "call now" rule, then call the function
2513		 * in the rule, if it exists and use the results from that.
2514		 * If the function pointer is bad, just make like we ignore
2515		 * it, except for increasing the hit counter.
2516		 */
2517		if ((passt & FR_CALLNOW) != 0) {
2518			frentry_t *frs;
2519
2520			ATOMIC_INC64(fr->fr_hits);
2521			if ((fr->fr_func == NULL) ||
2522			    (fr->fr_func == (ipfunc_t)-1))
2523				continue;
2524
2525			frs = fin->fin_fr;
2526			fin->fin_fr = fr;
2527			fr = (*fr->fr_func)(fin, &passt);
2528			if (fr == NULL) {
2529				fin->fin_fr = frs;
2530				continue;
2531			}
2532			passt = fr->fr_flags;
2533		}
2534		fin->fin_fr = fr;
2535
2536#ifdef  IPFILTER_LOG
2537		/*
2538		 * Just log this packet...
2539		 */
2540		if ((passt & FR_LOGMASK) == FR_LOG) {
2541			if (ipf_log_pkt(fin, passt) == -1) {
2542				if (passt & FR_LOGORBLOCK) {
2543					DT(frb_logfail);
2544					passt &= ~FR_CMDMASK;
2545					passt |= FR_BLOCK|FR_QUICK;
2546					fin->fin_reason = FRB_LOGFAIL;
2547				}
2548			}
2549		}
2550#endif /* IPFILTER_LOG */
2551
2552		MUTEX_ENTER(&fr->fr_lock);
2553		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2554		fr->fr_hits++;
2555		MUTEX_EXIT(&fr->fr_lock);
2556		fin->fin_rule = rulen;
2557
2558		passo = pass;
2559		if (FR_ISSKIP(passt)) {
2560			skip = fr->fr_arg;
2561			continue;
2562		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2563			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2564			pass = passt;
2565		}
2566
2567		if (passt & (FR_RETICMP|FR_FAKEICMP))
2568			fin->fin_icode = fr->fr_icode;
2569
2570		if (fr->fr_group != -1) {
2571			(void) strncpy(fin->fin_group,
2572				       FR_NAME(fr, fr_group),
2573				       strlen(FR_NAME(fr, fr_group)));
2574		} else {
2575			fin->fin_group[0] = '\0';
2576		}
2577
2578		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2579
2580		if (fr->fr_grphead != NULL) {
2581			fin->fin_fr = fr->fr_grphead->fg_start;
2582			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2583
2584			if (FR_ISDECAPS(passt))
2585				passt = ipf_decaps(fin, pass, fr->fr_icode);
2586			else
2587				passt = ipf_scanlist(fin, pass);
2588
2589			if (fin->fin_fr == NULL) {
2590				fin->fin_rule = rulen;
2591				if (fr->fr_group != -1)
2592					(void) strncpy(fin->fin_group,
2593						       fr->fr_names +
2594						       fr->fr_group,
2595						       strlen(fr->fr_names +
2596							      fr->fr_group));
2597				fin->fin_fr = fr;
2598				passt = pass;
2599			}
2600			pass = passt;
2601		}
2602
2603		if (pass & FR_QUICK) {
2604			/*
2605			 * Finally, if we've asked to track state for this
2606			 * packet, set it up.  Add state for "quick" rules
2607			 * here so that if the action fails we can consider
2608			 * the rule to "not match" and keep on processing
2609			 * filter rules.
2610			 */
2611			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2612			    !(fin->fin_flx & FI_STATE)) {
2613				int out = fin->fin_out;
2614
2615				fin->fin_fr = fr;
2616				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2617					LBUMPD(ipf_stats[out], fr_ads);
2618				} else {
2619					LBUMPD(ipf_stats[out], fr_bads);
2620					pass = passo;
2621					continue;
2622				}
2623			}
2624			break;
2625		}
2626	}
2627	fin->fin_depth--;
2628	return pass;
2629}
2630
2631
2632/* ------------------------------------------------------------------------ */
2633/* Function:    ipf_acctpkt                                                 */
2634/* Returns:     frentry_t* - always returns NULL                            */
2635/* Parameters:  fin(I) - pointer to packet information                      */
2636/*              passp(IO) - pointer to current/new filter decision (unused) */
2637/*                                                                          */
2638/* Checks a packet against accounting rules, if there are any for the given */
2639/* IP protocol version.                                                     */
2640/*                                                                          */
2641/* N.B.: this function returns NULL to match the prototype used by other    */
2642/* functions called from the IPFilter "mainline" in ipf_check().            */
2643/* ------------------------------------------------------------------------ */
2644frentry_t *
2645ipf_acctpkt(fin, passp)
2646	fr_info_t *fin;
2647	u_32_t *passp;
2648{
2649	ipf_main_softc_t *softc = fin->fin_main_soft;
2650	char group[FR_GROUPLEN];
2651	frentry_t *fr, *frsave;
2652	u_32_t pass, rulen;
2653
2654	passp = passp;
2655	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2656
2657	if (fr != NULL) {
2658		frsave = fin->fin_fr;
2659		bcopy(fin->fin_group, group, FR_GROUPLEN);
2660		rulen = fin->fin_rule;
2661		fin->fin_fr = fr;
2662		pass = ipf_scanlist(fin, FR_NOMATCH);
2663		if (FR_ISACCOUNT(pass)) {
2664			LBUMPD(ipf_stats[0], fr_acct);
2665		}
2666		fin->fin_fr = frsave;
2667		bcopy(group, fin->fin_group, FR_GROUPLEN);
2668		fin->fin_rule = rulen;
2669	}
2670	return NULL;
2671}
2672
2673
2674/* ------------------------------------------------------------------------ */
2675/* Function:    ipf_firewall                                                */
2676/* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2677/*                           were found, returns NULL.                      */
2678/* Parameters:  fin(I) - pointer to packet information                      */
2679/*              passp(IO) - pointer to current/new filter decision (unused) */
2680/*                                                                          */
2681/* Applies an appropriate set of firewall rules to the packet, to see if    */
2682/* there are any matches.  The first check is to see if a match can be seen */
2683/* in the cache.  If not, then search an appropriate list of rules.  Once a */
2684/* matching rule is found, take any appropriate actions as defined by the   */
2685/* rule - except logging.                                                   */
2686/* ------------------------------------------------------------------------ */
2687static frentry_t *
2688ipf_firewall(fin, passp)
2689	fr_info_t *fin;
2690	u_32_t *passp;
2691{
2692	ipf_main_softc_t *softc = fin->fin_main_soft;
2693	frentry_t *fr;
2694	u_32_t pass;
2695	int out;
2696
2697	out = fin->fin_out;
2698	pass = *passp;
2699
2700	/*
2701	 * This rule cache will only affect packets that are not being
2702	 * statefully filtered.
2703	 */
2704	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2705	if (fin->fin_fr != NULL)
2706		pass = ipf_scanlist(fin, softc->ipf_pass);
2707
2708	if ((pass & FR_NOMATCH)) {
2709		LBUMPD(ipf_stats[out], fr_nom);
2710	}
2711	fr = fin->fin_fr;
2712
2713	/*
2714	 * Apply packets per second rate-limiting to a rule as required.
2715	 */
2716	if ((fr != NULL) && (fr->fr_pps != 0) &&
2717	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2718		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2719		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2720		pass |= FR_BLOCK;
2721		LBUMPD(ipf_stats[out], fr_ppshit);
2722		fin->fin_reason = FRB_PPSRATE;
2723	}
2724
2725	/*
2726	 * If we fail to add a packet to the authorization queue, then we
2727	 * drop the packet later.  However, if it was added then pretend
2728	 * we've dropped it already.
2729	 */
2730	if (FR_ISAUTH(pass)) {
2731		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2732			DT1(frb_authnew, fr_info_t *, fin);
2733			fin->fin_m = *fin->fin_mp = NULL;
2734			fin->fin_reason = FRB_AUTHNEW;
2735			fin->fin_error = 0;
2736		} else {
2737			IPFERROR(1);
2738			fin->fin_error = ENOSPC;
2739		}
2740	}
2741
2742	if ((fr != NULL) && (fr->fr_func != NULL) &&
2743	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2744		(void) (*fr->fr_func)(fin, &pass);
2745
2746	/*
2747	 * If a rule is a pre-auth rule, check again in the list of rules
2748	 * loaded for authenticated use.  It does not particulary matter
2749	 * if this search fails because a "preauth" result, from a rule,
2750	 * is treated as "not a pass", hence the packet is blocked.
2751	 */
2752	if (FR_ISPREAUTH(pass)) {
2753		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2754	}
2755
2756	/*
2757	 * If the rule has "keep frag" and the packet is actually a fragment,
2758	 * then create a fragment state entry.
2759	 */
2760	if (pass & FR_KEEPFRAG) {
2761		if (fin->fin_flx & FI_FRAG) {
2762			if (ipf_frag_new(softc, fin, pass) == -1) {
2763				LBUMP(ipf_stats[out].fr_bnfr);
2764			} else {
2765				LBUMP(ipf_stats[out].fr_nfr);
2766			}
2767		} else {
2768			LBUMP(ipf_stats[out].fr_cfr);
2769		}
2770	}
2771
2772	fr = fin->fin_fr;
2773	*passp = pass;
2774
2775	return fr;
2776}
2777
2778
2779/* ------------------------------------------------------------------------ */
2780/* Function:    ipf_check                                                   */
2781/* Returns:     int -  0 == packet allowed through,                         */
2782/*              User space:                                                 */
2783/*                    -1 == packet blocked                                  */
2784/*                     1 == packet not matched                              */
2785/*                    -2 == requires authentication                         */
2786/*              Kernel:                                                     */
2787/*                   > 0 == filter error # for packet                       */
2788/* Parameters: ctx(I)  - pointer to the instance context                    */
2789/*             ip(I)   - pointer to start of IPv4/6 packet                  */
2790/*             hlen(I) - length of header                                   */
2791/*             ifp(I)  - pointer to interface this packet is on             */
2792/*             out(I)  - 0 == packet going in, 1 == packet going out        */
2793/*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2794/*                       IP packet.                                         */
2795/* Solaris:                                                                 */
2796/*             qpi(I)  - pointer to STREAMS queue information for this      */
2797/*                       interface & direction.                             */
2798/*                                                                          */
2799/* ipf_check() is the master function for all IPFilter packet processing.   */
2800/* It orchestrates: Network Address Translation (NAT), checking for packet  */
2801/* authorisation (or pre-authorisation), presence of related state info.,   */
2802/* generating log entries, IP packet accounting, routing of packets as      */
2803/* directed by firewall rules and of course whether or not to allow the     */
2804/* packet to be further processed by the kernel.                            */
2805/*                                                                          */
2806/* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2807/* freed.  Packets passed may be returned with the pointer pointed to by    */
2808/* by "mp" changed to a new buffer.                                         */
2809/* ------------------------------------------------------------------------ */
2810int
2811ipf_check(ctx, ip, hlen, ifp, out
2812#if defined(_KERNEL) && defined(MENTAT)
2813	, qif, mp)
2814	void *qif;
2815#else
2816	, mp)
2817#endif
2818	mb_t **mp;
2819	ip_t *ip;
2820	int hlen;
2821	struct ifnet *ifp;
2822	int out;
2823	void *ctx;
2824{
2825	/*
2826	 * The above really sucks, but short of writing a diff
2827	 */
2828	ipf_main_softc_t *softc = ctx;
2829	fr_info_t frinfo;
2830	fr_info_t *fin = &frinfo;
2831	u_32_t pass = softc->ipf_pass;
2832	frentry_t *fr = NULL;
2833	int v = IP_V(ip);
2834	mb_t *mc = NULL;
2835	mb_t *m;
2836	/*
2837	 * The first part of ipf_check() deals with making sure that what goes
2838	 * into the filtering engine makes some sense.  Information about the
2839	 * the packet is distilled, collected into a fr_info_t structure and
2840	 * the an attempt to ensure the buffer the packet is in is big enough
2841	 * to hold all the required packet headers.
2842	 */
2843#ifdef	_KERNEL
2844# ifdef MENTAT
2845	qpktinfo_t *qpi = qif;
2846
2847#  ifdef __sparc
2848	if ((u_int)ip & 0x3)
2849		return 2;
2850#  endif
2851# else
2852	SPL_INT(s);
2853# endif
2854
2855	if (softc->ipf_running <= 0) {
2856		return 0;
2857	}
2858
2859	bzero((char *)fin, sizeof(*fin));
2860
2861# ifdef MENTAT
2862	if (qpi->qpi_flags & QF_BROADCAST)
2863		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2864	if (qpi->qpi_flags & QF_MULTICAST)
2865		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2866	m = qpi->qpi_m;
2867	fin->fin_qfm = m;
2868	fin->fin_qpi = qpi;
2869# else /* MENTAT */
2870
2871	m = *mp;
2872
2873#  if defined(M_MCAST)
2874	if ((m->m_flags & M_MCAST) != 0)
2875		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2876#  endif
2877#  if defined(M_MLOOP)
2878	if ((m->m_flags & M_MLOOP) != 0)
2879		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2880#  endif
2881#  if defined(M_BCAST)
2882	if ((m->m_flags & M_BCAST) != 0)
2883		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2884#  endif
2885#  ifdef M_CANFASTFWD
2886	/*
2887	 * XXX For now, IP Filter and fast-forwarding of cached flows
2888	 * XXX are mutually exclusive.  Eventually, IP Filter should
2889	 * XXX get a "can-fast-forward" filter rule.
2890	 */
2891	m->m_flags &= ~M_CANFASTFWD;
2892#  endif /* M_CANFASTFWD */
2893#  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2894	/*
2895	 * disable delayed checksums.
2896	 */
2897	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2898		in_delayed_cksum(m);
2899		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2900	}
2901#  endif /* CSUM_DELAY_DATA */
2902# endif /* MENTAT */
2903#else
2904	bzero((char *)fin, sizeof(*fin));
2905	m = *mp;
2906# if defined(M_MCAST)
2907	if ((m->m_flags & M_MCAST) != 0)
2908		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2909# endif
2910# if defined(M_MLOOP)
2911	if ((m->m_flags & M_MLOOP) != 0)
2912		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2913# endif
2914# if defined(M_BCAST)
2915	if ((m->m_flags & M_BCAST) != 0)
2916		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2917# endif
2918#endif /* _KERNEL */
2919
2920	fin->fin_v = v;
2921	fin->fin_m = m;
2922	fin->fin_ip = ip;
2923	fin->fin_mp = mp;
2924	fin->fin_out = out;
2925	fin->fin_ifp = ifp;
2926	fin->fin_error = ENETUNREACH;
2927	fin->fin_hlen = (u_short)hlen;
2928	fin->fin_dp = (char *)ip + hlen;
2929	fin->fin_main_soft = softc;
2930
2931	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2932
2933	SPL_NET(s);
2934
2935#ifdef	USE_INET6
2936	if (v == 6) {
2937		LBUMP(ipf_stats[out].fr_ipv6);
2938		/*
2939		 * Jumbo grams are quite likely too big for internal buffer
2940		 * structures to handle comfortably, for now, so just drop
2941		 * them.
2942		 */
2943		if (((ip6_t *)ip)->ip6_plen == 0) {
2944			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2945			pass = FR_BLOCK|FR_NOMATCH;
2946			fin->fin_reason = FRB_JUMBO;
2947			goto finished;
2948		}
2949		fin->fin_family = AF_INET6;
2950	} else
2951#endif
2952	{
2953		fin->fin_family = AF_INET;
2954	}
2955
2956	if (ipf_makefrip(hlen, ip, fin) == -1) {
2957		DT1(frb_makefrip, fr_info_t *, fin);
2958		pass = FR_BLOCK|FR_NOMATCH;
2959		fin->fin_reason = FRB_MAKEFRIP;
2960		goto finished;
2961	}
2962
2963	/*
2964	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2965	 * becomes NULL and so we have no packet to free.
2966	 */
2967	if (*fin->fin_mp == NULL)
2968		goto finished;
2969
2970	if (!out) {
2971		if (v == 4) {
2972			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2973				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2974				fin->fin_flx |= FI_BADSRC;
2975			}
2976			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2977				LBUMPD(ipf_stats[0], fr_v4_badttl);
2978				fin->fin_flx |= FI_LOWTTL;
2979			}
2980		}
2981#ifdef USE_INET6
2982		else  if (v == 6) {
2983			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2984				LBUMPD(ipf_stats[0], fr_v6_badttl);
2985				fin->fin_flx |= FI_LOWTTL;
2986			}
2987		}
2988#endif
2989	}
2990
2991	if (fin->fin_flx & FI_SHORT) {
2992		LBUMPD(ipf_stats[out], fr_short);
2993	}
2994
2995	READ_ENTER(&softc->ipf_mutex);
2996
2997	if (!out) {
2998		switch (fin->fin_v)
2999		{
3000		case 4 :
3001			if (ipf_nat_checkin(fin, &pass) == -1) {
3002				goto filterdone;
3003			}
3004			break;
3005#ifdef USE_INET6
3006		case 6 :
3007			if (ipf_nat6_checkin(fin, &pass) == -1) {
3008				goto filterdone;
3009			}
3010			break;
3011#endif
3012		default :
3013			break;
3014		}
3015	}
3016	/*
3017	 * Check auth now.
3018	 * If a packet is found in the auth table, then skip checking
3019	 * the access lists for permission but we do need to consider
3020	 * the result as if it were from the ACL's.  In addition, being
3021	 * found in the auth table means it has been seen before, so do
3022	 * not pass it through accounting (again), lest it be counted twice.
3023	 */
3024	fr = ipf_auth_check(fin, &pass);
3025	if (!out && (fr == NULL))
3026		(void) ipf_acctpkt(fin, NULL);
3027
3028	if (fr == NULL) {
3029		if ((fin->fin_flx & FI_FRAG) != 0)
3030			fr = ipf_frag_known(fin, &pass);
3031
3032		if (fr == NULL)
3033			fr = ipf_state_check(fin, &pass);
3034	}
3035
3036	if ((pass & FR_NOMATCH) || (fr == NULL))
3037		fr = ipf_firewall(fin, &pass);
3038
3039	/*
3040	 * If we've asked to track state for this packet, set it up.
3041	 * Here rather than ipf_firewall because ipf_checkauth may decide
3042	 * to return a packet for "keep state"
3043	 */
3044	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3045	    !(fin->fin_flx & FI_STATE)) {
3046		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3047			LBUMP(ipf_stats[out].fr_ads);
3048		} else {
3049			LBUMP(ipf_stats[out].fr_bads);
3050			if (FR_ISPASS(pass)) {
3051				DT(frb_stateadd);
3052				pass &= ~FR_CMDMASK;
3053				pass |= FR_BLOCK;
3054				fin->fin_reason = FRB_STATEADD;
3055			}
3056		}
3057	}
3058
3059	fin->fin_fr = fr;
3060	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3061		fin->fin_dif = &fr->fr_dif;
3062		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3063	}
3064
3065	/*
3066	 * Only count/translate packets which will be passed on, out the
3067	 * interface.
3068	 */
3069	if (out && FR_ISPASS(pass)) {
3070		(void) ipf_acctpkt(fin, NULL);
3071
3072		switch (fin->fin_v)
3073		{
3074		case 4 :
3075			if (ipf_nat_checkout(fin, &pass) == -1) {
3076				;
3077			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3078				if (ipf_updateipid(fin) == -1) {
3079					DT(frb_updateipid);
3080					LBUMP(ipf_stats[1].fr_ipud);
3081					pass &= ~FR_CMDMASK;
3082					pass |= FR_BLOCK;
3083					fin->fin_reason = FRB_UPDATEIPID;
3084				} else {
3085					LBUMP(ipf_stats[0].fr_ipud);
3086				}
3087			}
3088			break;
3089#ifdef USE_INET6
3090		case 6 :
3091			(void) ipf_nat6_checkout(fin, &pass);
3092			break;
3093#endif
3094		default :
3095			break;
3096		}
3097	}
3098
3099filterdone:
3100#ifdef	IPFILTER_LOG
3101	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3102		(void) ipf_dolog(fin, &pass);
3103	}
3104#endif
3105
3106	/*
3107	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3108	 * will work when called from inside of fr_fastroute.  Although
3109	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3110	 * impact on code execution.
3111	 */
3112	fin->fin_flx &= ~FI_STATE;
3113
3114#if defined(FASTROUTE_RECURSION)
3115	/*
3116	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3117	 * a packet below can sometimes cause a recursive call into IPFilter.
3118	 * On those platforms where that does happen, we need to hang onto
3119	 * the filter rule just in case someone decides to remove or flush it
3120	 * in the meantime.
3121	 */
3122	if (fr != NULL) {
3123		MUTEX_ENTER(&fr->fr_lock);
3124		fr->fr_ref++;
3125		MUTEX_EXIT(&fr->fr_lock);
3126	}
3127
3128	RWLOCK_EXIT(&softc->ipf_mutex);
3129#endif
3130
3131	if ((pass & FR_RETMASK) != 0) {
3132		/*
3133		 * Should we return an ICMP packet to indicate error
3134		 * status passing through the packet filter ?
3135		 * WARNING: ICMP error packets AND TCP RST packets should
3136		 * ONLY be sent in repsonse to incoming packets.  Sending
3137		 * them in response to outbound packets can result in a
3138		 * panic on some operating systems.
3139		 */
3140		if (!out) {
3141			if (pass & FR_RETICMP) {
3142				int dst;
3143
3144				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3145					dst = 1;
3146				else
3147					dst = 0;
3148				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3149							 dst);
3150				LBUMP(ipf_stats[0].fr_ret);
3151			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3152				   !(fin->fin_flx & FI_SHORT)) {
3153				if (((fin->fin_flx & FI_OOW) != 0) ||
3154				    (ipf_send_reset(fin) == 0)) {
3155					LBUMP(ipf_stats[1].fr_ret);
3156				}
3157			}
3158
3159			/*
3160			 * When using return-* with auth rules, the auth code
3161			 * takes over disposing of this packet.
3162			 */
3163			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3164				DT1(frb_authcapture, fr_info_t *, fin);
3165				fin->fin_m = *fin->fin_mp = NULL;
3166				fin->fin_reason = FRB_AUTHCAPTURE;
3167				m = NULL;
3168			}
3169		} else {
3170			if (pass & FR_RETRST) {
3171				fin->fin_error = ECONNRESET;
3172			}
3173		}
3174	}
3175
3176	/*
3177	 * After the above so that ICMP unreachables and TCP RSTs get
3178	 * created properly.
3179	 */
3180	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3181		ipf_nat_uncreate(fin);
3182
3183	/*
3184	 * If we didn't drop off the bottom of the list of rules (and thus
3185	 * the 'current' rule fr is not NULL), then we may have some extra
3186	 * instructions about what to do with a packet.
3187	 * Once we're finished return to our caller, freeing the packet if
3188	 * we are dropping it.
3189	 */
3190	if (fr != NULL) {
3191		frdest_t *fdp;
3192
3193		/*
3194		 * Generate a duplicated packet first because ipf_fastroute
3195		 * can lead to fin_m being free'd... not good.
3196		 */
3197		fdp = fin->fin_dif;
3198		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3199		    (fdp->fd_ptr != (void *)-1)) {
3200			mc = M_COPY(fin->fin_m);
3201			if (mc != NULL)
3202				ipf_fastroute(mc, &mc, fin, fdp);
3203		}
3204
3205		fdp = fin->fin_tif;
3206		if (!out && (pass & FR_FASTROUTE)) {
3207			/*
3208			 * For fastroute rule, no destination interface defined
3209			 * so pass NULL as the frdest_t parameter
3210			 */
3211			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3212			m = *mp = NULL;
3213		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3214			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3215			/* this is for to rules: */
3216			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3217			m = *mp = NULL;
3218		}
3219
3220#if defined(FASTROUTE_RECURSION)
3221		(void) ipf_derefrule(softc, &fr);
3222#endif
3223	}
3224#if !defined(FASTROUTE_RECURSION)
3225	RWLOCK_EXIT(&softc->ipf_mutex);
3226#endif
3227
3228finished:
3229	if (!FR_ISPASS(pass)) {
3230		LBUMP(ipf_stats[out].fr_block);
3231		if (*mp != NULL) {
3232#ifdef _KERNEL
3233			FREE_MB_T(*mp);
3234#endif
3235			m = *mp = NULL;
3236		}
3237	} else {
3238		LBUMP(ipf_stats[out].fr_pass);
3239	}
3240
3241	SPL_X(s);
3242
3243#ifdef _KERNEL
3244	if (FR_ISPASS(pass))
3245		return 0;
3246	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3247	return fin->fin_error;
3248#else /* _KERNEL */
3249	if (*mp != NULL)
3250		(*mp)->mb_ifp = fin->fin_ifp;
3251	blockreason = fin->fin_reason;
3252	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3253	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3254		if ((pass & FR_NOMATCH) != 0)
3255			return 1;
3256
3257	if ((pass & FR_RETMASK) != 0)
3258		switch (pass & FR_RETMASK)
3259		{
3260		case FR_RETRST :
3261			return 3;
3262		case FR_RETICMP :
3263			return 4;
3264		case FR_FAKEICMP :
3265			return 5;
3266		}
3267
3268	switch (pass & FR_CMDMASK)
3269	{
3270	case FR_PASS :
3271		return 0;
3272	case FR_BLOCK :
3273		return -1;
3274	case FR_AUTH :
3275		return -2;
3276	case FR_ACCOUNT :
3277		return -3;
3278	case FR_PREAUTH :
3279		return -4;
3280	}
3281	return 2;
3282#endif /* _KERNEL */
3283}
3284
3285
3286#ifdef	IPFILTER_LOG
3287/* ------------------------------------------------------------------------ */
3288/* Function:    ipf_dolog                                                   */
3289/* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3290/* Parameters:  fin(I) - pointer to packet information                      */
3291/*              passp(IO) - pointer to current/new filter decision (unused) */
3292/*                                                                          */
3293/* Checks flags set to see how a packet should be logged, if it is to be    */
3294/* logged.  Adjust statistics based on its success or not.                  */
3295/* ------------------------------------------------------------------------ */
3296frentry_t *
3297ipf_dolog(fin, passp)
3298	fr_info_t *fin;
3299	u_32_t *passp;
3300{
3301	ipf_main_softc_t *softc = fin->fin_main_soft;
3302	u_32_t pass;
3303	int out;
3304
3305	out = fin->fin_out;
3306	pass = *passp;
3307
3308	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3309		pass |= FF_LOGNOMATCH;
3310		LBUMPD(ipf_stats[out], fr_npkl);
3311		goto logit;
3312
3313	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3314	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3315		if ((pass & FR_LOGMASK) != FR_LOGP)
3316			pass |= FF_LOGPASS;
3317		LBUMPD(ipf_stats[out], fr_ppkl);
3318		goto logit;
3319
3320	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3321		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3322		if ((pass & FR_LOGMASK) != FR_LOGB)
3323			pass |= FF_LOGBLOCK;
3324		LBUMPD(ipf_stats[out], fr_bpkl);
3325
3326logit:
3327		if (ipf_log_pkt(fin, pass) == -1) {
3328			/*
3329			 * If the "or-block" option has been used then
3330			 * block the packet if we failed to log it.
3331			 */
3332			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3333				DT1(frb_logfail2, u_int, pass);
3334				pass &= ~FR_CMDMASK;
3335				pass |= FR_BLOCK;
3336				fin->fin_reason = FRB_LOGFAIL2;
3337			}
3338		}
3339		*passp = pass;
3340	}
3341
3342	return fin->fin_fr;
3343}
3344#endif /* IPFILTER_LOG */
3345
3346
3347/* ------------------------------------------------------------------------ */
3348/* Function:    ipf_cksum                                                   */
3349/* Returns:     u_short - IP header checksum                                */
3350/* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3351/*              len(I)  - length of buffer in bytes                         */
3352/*                                                                          */
3353/* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3354/*                                                                          */
3355/* N.B.: addr should be 16bit aligned.                                      */
3356/* ------------------------------------------------------------------------ */
3357u_short
3358ipf_cksum(addr, len)
3359	u_short *addr;
3360	int len;
3361{
3362	u_32_t sum = 0;
3363
3364	for (sum = 0; len > 1; len -= 2)
3365		sum += *addr++;
3366
3367	/* mop up an odd byte, if necessary */
3368	if (len == 1)
3369		sum += *(u_char *)addr;
3370
3371	/*
3372	 * add back carry outs from top 16 bits to low 16 bits
3373	 */
3374	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3375	sum += (sum >> 16);			/* add carry */
3376	return (u_short)(~sum);
3377}
3378
3379
3380/* ------------------------------------------------------------------------ */
3381/* Function:    fr_cksum                                                    */
3382/* Returns:     u_short - layer 4 checksum                                  */
3383/* Parameters:  fin(I)     - pointer to packet information                  */
3384/*              ip(I)      - pointer to IP header                           */
3385/*              l4proto(I) - protocol to caclulate checksum for             */
3386/*              l4hdr(I)   - pointer to layer 4 header                      */
3387/*                                                                          */
3388/* Calculates the TCP checksum for the packet held in "m", using the data   */
3389/* in the IP header "ip" to seed it.                                        */
3390/*                                                                          */
3391/* NB: This function assumes we've pullup'd enough for all of the IP header */
3392/* and the TCP header.  We also assume that data blocks aren't allocated in */
3393/* odd sizes.                                                               */
3394/*                                                                          */
3395/* Expects ip_len and ip_off to be in network byte order when called.       */
3396/* ------------------------------------------------------------------------ */
3397u_short
3398fr_cksum(fin, ip, l4proto, l4hdr)
3399	fr_info_t *fin;
3400	ip_t *ip;
3401	int l4proto;
3402	void *l4hdr;
3403{
3404	u_short *sp, slen, sumsave, *csump;
3405	u_int sum, sum2;
3406	int hlen;
3407	int off;
3408#ifdef	USE_INET6
3409	ip6_t *ip6;
3410#endif
3411
3412	csump = NULL;
3413	sumsave = 0;
3414	sp = NULL;
3415	slen = 0;
3416	hlen = 0;
3417	sum = 0;
3418
3419	sum = htons((u_short)l4proto);
3420	/*
3421	 * Add up IP Header portion
3422	 */
3423#ifdef	USE_INET6
3424	if (IP_V(ip) == 4) {
3425#endif
3426		hlen = IP_HL(ip) << 2;
3427		off = hlen;
3428		sp = (u_short *)&ip->ip_src;
3429		sum += *sp++;	/* ip_src */
3430		sum += *sp++;
3431		sum += *sp++;	/* ip_dst */
3432		sum += *sp++;
3433		slen = fin->fin_plen - off;
3434		sum += htons(slen);
3435#ifdef	USE_INET6
3436	} else if (IP_V(ip) == 6) {
3437		mb_t *m;
3438
3439		m = fin->fin_m;
3440		ip6 = (ip6_t *)ip;
3441		off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3442		int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3443		return(ipf_pcksum6(fin, ip6, off, len));
3444	} else {
3445		return 0xffff;
3446	}
3447#endif
3448
3449	switch (l4proto)
3450	{
3451	case IPPROTO_UDP :
3452		csump = &((udphdr_t *)l4hdr)->uh_sum;
3453		break;
3454
3455	case IPPROTO_TCP :
3456		csump = &((tcphdr_t *)l4hdr)->th_sum;
3457		break;
3458	case IPPROTO_ICMP :
3459		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3460		sum = 0;	/* Pseudo-checksum is not included */
3461		break;
3462#ifdef USE_INET6
3463	case IPPROTO_ICMPV6 :
3464		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3465		break;
3466#endif
3467	default :
3468		break;
3469	}
3470
3471	if (csump != NULL) {
3472		sumsave = *csump;
3473		*csump = 0;
3474	}
3475
3476	sum2 = ipf_pcksum(fin, off, sum);
3477	if (csump != NULL)
3478		*csump = sumsave;
3479	return sum2;
3480}
3481
3482
3483/* ------------------------------------------------------------------------ */
3484/* Function:    ipf_findgroup                                               */
3485/* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3486/* Parameters:  softc(I) - pointer to soft context main structure           */
3487/*              group(I) - group name to search for                         */
3488/*              unit(I)  - device to which this group belongs               */
3489/*              set(I)   - which set of rules (inactive/inactive) this is   */
3490/*              fgpp(O)  - pointer to place to store pointer to the pointer */
3491/*                         to where to add the next (last) group or where   */
3492/*                         to delete group from.                            */
3493/*                                                                          */
3494/* Search amongst the defined groups for a particular group number.         */
3495/* ------------------------------------------------------------------------ */
3496frgroup_t *
3497ipf_findgroup(softc, group, unit, set, fgpp)
3498	ipf_main_softc_t *softc;
3499	char *group;
3500	minor_t unit;
3501	int set;
3502	frgroup_t ***fgpp;
3503{
3504	frgroup_t *fg, **fgp;
3505
3506	/*
3507	 * Which list of groups to search in is dependent on which list of
3508	 * rules are being operated on.
3509	 */
3510	fgp = &softc->ipf_groups[unit][set];
3511
3512	while ((fg = *fgp) != NULL) {
3513		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3514			break;
3515		else
3516			fgp = &fg->fg_next;
3517	}
3518	if (fgpp != NULL)
3519		*fgpp = fgp;
3520	return fg;
3521}
3522
3523
3524/* ------------------------------------------------------------------------ */
3525/* Function:    ipf_group_add                                               */
3526/* Returns:     frgroup_t * - NULL == did not create group,                 */
3527/*                            != NULL == pointer to the group               */
3528/* Parameters:  softc(I) - pointer to soft context main structure           */
3529/*              num(I)   - group number to add                              */
3530/*              head(I)  - rule pointer that is using this as the head      */
3531/*              flags(I) - rule flags which describe the type of rule it is */
3532/*              unit(I)  - device to which this group will belong to        */
3533/*              set(I)   - which set of rules (inactive/inactive) this is   */
3534/* Write Locks: ipf_mutex                                                   */
3535/*                                                                          */
3536/* Add a new group head, or if it already exists, increase the reference    */
3537/* count to it.                                                             */
3538/* ------------------------------------------------------------------------ */
3539frgroup_t *
3540ipf_group_add(softc, group, head, flags, unit, set)
3541	ipf_main_softc_t *softc;
3542	char *group;
3543	void *head;
3544	u_32_t flags;
3545	minor_t unit;
3546	int set;
3547{
3548	frgroup_t *fg, **fgp;
3549	u_32_t gflags;
3550
3551	if (group == NULL)
3552		return NULL;
3553
3554	if (unit == IPL_LOGIPF && *group == '\0')
3555		return NULL;
3556
3557	fgp = NULL;
3558	gflags = flags & FR_INOUT;
3559
3560	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3561	if (fg != NULL) {
3562		if (fg->fg_head == NULL && head != NULL)
3563			fg->fg_head = head;
3564		if (fg->fg_flags == 0)
3565			fg->fg_flags = gflags;
3566		else if (gflags != fg->fg_flags)
3567			return NULL;
3568		fg->fg_ref++;
3569		return fg;
3570	}
3571
3572	KMALLOC(fg, frgroup_t *);
3573	if (fg != NULL) {
3574		fg->fg_head = head;
3575		fg->fg_start = NULL;
3576		fg->fg_next = *fgp;
3577		bcopy(group, fg->fg_name, strlen(group) + 1);
3578		fg->fg_flags = gflags;
3579		fg->fg_ref = 1;
3580		fg->fg_set = &softc->ipf_groups[unit][set];
3581		*fgp = fg;
3582	}
3583	return fg;
3584}
3585
3586
3587/* ------------------------------------------------------------------------ */
3588/* Function:    ipf_group_del                                               */
3589/* Returns:     int      - number of rules deleted                          */
3590/* Parameters:  softc(I) - pointer to soft context main structure           */
3591/*              group(I) - group name to delete                             */
3592/*              fr(I)    - filter rule from which group is referenced       */
3593/* Write Locks: ipf_mutex                                                   */
3594/*                                                                          */
3595/* This function is called whenever a reference to a group is to be dropped */
3596/* and thus its reference count needs to be lowered and the group free'd if */
3597/* the reference count reaches zero. Passing in fr is really for the sole   */
3598/* purpose of knowing when the head rule is being deleted.                  */
3599/* ------------------------------------------------------------------------ */
3600void
3601ipf_group_del(softc, group, fr)
3602	ipf_main_softc_t *softc;
3603	frgroup_t *group;
3604	frentry_t *fr;
3605{
3606
3607	if (group->fg_head == fr)
3608		group->fg_head = NULL;
3609
3610	group->fg_ref--;
3611	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3612		ipf_group_free(group);
3613}
3614
3615
3616/* ------------------------------------------------------------------------ */
3617/* Function:    ipf_group_free                                              */
3618/* Returns:     Nil                                                         */
3619/* Parameters:  group(I) - pointer to filter rule group                     */
3620/*                                                                          */
3621/* Remove the group from the list of groups and free it.                    */
3622/* ------------------------------------------------------------------------ */
3623static void
3624ipf_group_free(group)
3625	frgroup_t *group;
3626{
3627	frgroup_t **gp;
3628
3629	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3630		if (*gp == group) {
3631			*gp = group->fg_next;
3632			break;
3633		}
3634	}
3635	KFREE(group);
3636}
3637
3638
3639/* ------------------------------------------------------------------------ */
3640/* Function:    ipf_group_flush                                             */
3641/* Returns:     int      - number of rules flush from group                 */
3642/* Parameters:  softc(I) - pointer to soft context main structure           */
3643/* Parameters:  group(I) - pointer to filter rule group                     */
3644/*                                                                          */
3645/* Remove all of the rules that currently are listed under the given group. */
3646/* ------------------------------------------------------------------------ */
3647static int
3648ipf_group_flush(softc, group)
3649	ipf_main_softc_t *softc;
3650	frgroup_t *group;
3651{
3652	int gone = 0;
3653
3654	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3655
3656	return gone;
3657}
3658
3659
3660/* ------------------------------------------------------------------------ */
3661/* Function:    ipf_getrulen                                                */
3662/* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3663/* Parameters:  softc(I) - pointer to soft context main structure           */
3664/* Parameters:  unit(I)  - device for which to count the rule's number      */
3665/*              flags(I) - which set of rules to find the rule in           */
3666/*              group(I) - group name                                       */
3667/*              n(I)     - rule number to find                              */
3668/*                                                                          */
3669/* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3670/* group # g doesn't exist or there are less than n rules in the group.     */
3671/* ------------------------------------------------------------------------ */
3672frentry_t *
3673ipf_getrulen(softc, unit, group, n)
3674	ipf_main_softc_t *softc;
3675	int unit;
3676	char *group;
3677	u_32_t n;
3678{
3679	frentry_t *fr;
3680	frgroup_t *fg;
3681
3682	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3683	if (fg == NULL)
3684		return NULL;
3685	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3686		;
3687	if (n != 0)
3688		return NULL;
3689	return fr;
3690}
3691
3692
3693/* ------------------------------------------------------------------------ */
3694/* Function:    ipf_flushlist                                               */
3695/* Returns:     int - >= 0 - number of flushed rules                        */
3696/* Parameters:  softc(I)   - pointer to soft context main structure         */
3697/*              nfreedp(O) - pointer to int where flush count is stored     */
3698/*              listp(I)   - pointer to list to flush pointer               */
3699/* Write Locks: ipf_mutex                                                   */
3700/*                                                                          */
3701/* Recursively flush rules from the list, descending groups as they are     */
3702/* encountered.  if a rule is the head of a group and it has lost all its   */
3703/* group members, then also delete the group reference.  nfreedp is needed  */
3704/* to store the accumulating count of rules removed, whereas the returned   */
3705/* value is just the number removed from the current list.  The latter is   */
3706/* needed to correctly adjust reference counts on rules that define groups. */
3707/*                                                                          */
3708/* NOTE: Rules not loaded from user space cannot be flushed.                */
3709/* ------------------------------------------------------------------------ */
3710static int
3711ipf_flushlist(softc, nfreedp, listp)
3712	ipf_main_softc_t *softc;
3713	int *nfreedp;
3714	frentry_t **listp;
3715{
3716	int freed = 0;
3717	frentry_t *fp;
3718
3719	while ((fp = *listp) != NULL) {
3720		if ((fp->fr_type & FR_T_BUILTIN) ||
3721		    !(fp->fr_flags & FR_COPIED)) {
3722			listp = &fp->fr_next;
3723			continue;
3724		}
3725		*listp = fp->fr_next;
3726		if (fp->fr_next != NULL)
3727			fp->fr_next->fr_pnext = fp->fr_pnext;
3728		fp->fr_pnext = NULL;
3729
3730		if (fp->fr_grphead != NULL) {
3731			freed += ipf_group_flush(softc, fp->fr_grphead);
3732			fp->fr_names[fp->fr_grhead] = '\0';
3733		}
3734
3735		if (fp->fr_icmpgrp != NULL) {
3736			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3737			fp->fr_names[fp->fr_icmphead] = '\0';
3738		}
3739
3740		if (fp->fr_srctrack.ht_max_nodes)
3741			ipf_rb_ht_flush(&fp->fr_srctrack);
3742
3743		fp->fr_next = NULL;
3744
3745		ASSERT(fp->fr_ref > 0);
3746		if (ipf_derefrule(softc, &fp) == 0)
3747			freed++;
3748	}
3749	*nfreedp += freed;
3750	return freed;
3751}
3752
3753
3754/* ------------------------------------------------------------------------ */
3755/* Function:    ipf_flush                                                   */
3756/* Returns:     int - >= 0 - number of flushed rules                        */
3757/* Parameters:  softc(I) - pointer to soft context main structure           */
3758/*              unit(I)  - device for which to flush rules                  */
3759/*              flags(I) - which set of rules to flush                      */
3760/*                                                                          */
3761/* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3762/* and IPv6) as defined by the value of flags.                              */
3763/* ------------------------------------------------------------------------ */
3764int
3765ipf_flush(softc, unit, flags)
3766	ipf_main_softc_t *softc;
3767	minor_t unit;
3768	int flags;
3769{
3770	int flushed = 0, set;
3771
3772	WRITE_ENTER(&softc->ipf_mutex);
3773
3774	set = softc->ipf_active;
3775	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3776		set = 1 - set;
3777
3778	if (flags & FR_OUTQUE) {
3779		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3780		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3781	}
3782	if (flags & FR_INQUE) {
3783		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3784		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3785	}
3786
3787	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3788				    flags & (FR_INQUE|FR_OUTQUE));
3789
3790	RWLOCK_EXIT(&softc->ipf_mutex);
3791
3792	if (unit == IPL_LOGIPF) {
3793		int tmp;
3794
3795		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3796		if (tmp >= 0)
3797			flushed += tmp;
3798	}
3799	return flushed;
3800}
3801
3802
3803/* ------------------------------------------------------------------------ */
3804/* Function:    ipf_flush_groups                                            */
3805/* Returns:     int - >= 0 - number of flushed rules                        */
3806/* Parameters:  softc(I)  - soft context pointerto work with                */
3807/*              grhead(I) - pointer to the start of the group list to flush */
3808/*              flags(I)  - which set of rules to flush                     */
3809/*                                                                          */
3810/* Walk through all of the groups under the given group head and remove all */
3811/* of those that match the flags passed in. The for loop here is bit more   */
3812/* complicated than usual because the removal of a rule with ipf_derefrule  */
3813/* may end up removing not only the structure pointed to by "fg" but also   */
3814/* what is fg_next and fg_next after that. So if a filter rule is actually  */
3815/* removed from the group then it is necessary to start again.              */
3816/* ------------------------------------------------------------------------ */
3817static int
3818ipf_flush_groups(softc, grhead, flags)
3819	ipf_main_softc_t *softc;
3820	frgroup_t **grhead;
3821	int flags;
3822{
3823	frentry_t *fr, **frp;
3824	frgroup_t *fg, **fgp;
3825	int flushed = 0;
3826	int removed = 0;
3827
3828	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3829		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3830			fg = fg->fg_next;
3831		if (fg == NULL)
3832			break;
3833		removed = 0;
3834		frp = &fg->fg_start;
3835		while ((removed == 0) && ((fr = *frp) != NULL)) {
3836			if ((fr->fr_flags & flags) == 0) {
3837				frp = &fr->fr_next;
3838			} else {
3839				if (fr->fr_next != NULL)
3840					fr->fr_next->fr_pnext = fr->fr_pnext;
3841				*frp = fr->fr_next;
3842				fr->fr_pnext = NULL;
3843				fr->fr_next = NULL;
3844				(void) ipf_derefrule(softc, &fr);
3845				flushed++;
3846				removed++;
3847			}
3848		}
3849		if (removed == 0)
3850			fgp = &fg->fg_next;
3851	}
3852	return flushed;
3853}
3854
3855
3856/* ------------------------------------------------------------------------ */
3857/* Function:    memstr                                                      */
3858/* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3859/* Parameters:  src(I)  - pointer to byte sequence to match                 */
3860/*              dst(I)  - pointer to byte sequence to search                */
3861/*              slen(I) - match length                                      */
3862/*              dlen(I) - length available to search in                     */
3863/*                                                                          */
3864/* Search dst for a sequence of bytes matching those at src and extend for  */
3865/* slen bytes.                                                              */
3866/* ------------------------------------------------------------------------ */
3867char *
3868memstr(src, dst, slen, dlen)
3869	const char *src;
3870	char *dst;
3871	size_t slen, dlen;
3872{
3873	char *s = NULL;
3874
3875	while (dlen >= slen) {
3876		if (bcmp(src, dst, slen) == 0) {
3877			s = dst;
3878			break;
3879		}
3880		dst++;
3881		dlen--;
3882	}
3883	return s;
3884}
3885/* ------------------------------------------------------------------------ */
3886/* Function:    ipf_fixskip                                                 */
3887/* Returns:     Nil                                                         */
3888/* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3889/*              rp(I)        - rule added/removed with skip in it.          */
3890/*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3891/*                             depending on whether a rule was just added   */
3892/*                             or removed.                                  */
3893/*                                                                          */
3894/* Adjust all the rules in a list which would have skip'd past the position */
3895/* where we are inserting to skip to the right place given the change.      */
3896/* ------------------------------------------------------------------------ */
3897void
3898ipf_fixskip(listp, rp, addremove)
3899	frentry_t **listp, *rp;
3900	int addremove;
3901{
3902	int rules, rn;
3903	frentry_t *fp;
3904
3905	rules = 0;
3906	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3907		rules++;
3908
3909	if (fp == NULL)
3910		return;
3911
3912	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3913		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3914			fp->fr_arg += addremove;
3915}
3916
3917
3918#ifdef	_KERNEL
3919/* ------------------------------------------------------------------------ */
3920/* Function:    count4bits                                                  */
3921/* Returns:     int - >= 0 - number of consecutive bits in input            */
3922/* Parameters:  ip(I) - 32bit IP address                                    */
3923/*                                                                          */
3924/* IPv4 ONLY                                                                */
3925/* count consecutive 1's in bit mask.  If the mask generated by counting    */
3926/* consecutive 1's is different to that passed, return -1, else return #    */
3927/* of bits.                                                                 */
3928/* ------------------------------------------------------------------------ */
3929int
3930count4bits(ip)
3931	u_32_t	ip;
3932{
3933	u_32_t	ipn;
3934	int	cnt = 0, i, j;
3935
3936	ip = ipn = ntohl(ip);
3937	for (i = 32; i; i--, ipn *= 2)
3938		if (ipn & 0x80000000)
3939			cnt++;
3940		else
3941			break;
3942	ipn = 0;
3943	for (i = 32, j = cnt; i; i--, j--) {
3944		ipn *= 2;
3945		if (j > 0)
3946			ipn++;
3947	}
3948	if (ipn == ip)
3949		return cnt;
3950	return -1;
3951}
3952
3953
3954/* ------------------------------------------------------------------------ */
3955/* Function:    count6bits                                                  */
3956/* Returns:     int - >= 0 - number of consecutive bits in input            */
3957/* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3958/*                                                                          */
3959/* IPv6 ONLY                                                                */
3960/* count consecutive 1's in bit mask.                                       */
3961/* ------------------------------------------------------------------------ */
3962# ifdef USE_INET6
3963int
3964count6bits(msk)
3965	u_32_t *msk;
3966{
3967	int i = 0, k;
3968	u_32_t j;
3969
3970	for (k = 3; k >= 0; k--)
3971		if (msk[k] == 0xffffffff)
3972			i += 32;
3973		else {
3974			for (j = msk[k]; j; j <<= 1)
3975				if (j & 0x80000000)
3976					i++;
3977		}
3978	return i;
3979}
3980# endif
3981#endif /* _KERNEL */
3982
3983
3984/* ------------------------------------------------------------------------ */
3985/* Function:    ipf_synclist                                                */
3986/* Returns:     int    - 0 = no failures, else indication of first failure  */
3987/* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3988/*              ifp(I) - interface pointer for limiting sync lookups        */
3989/* Write Locks: ipf_mutex                                                   */
3990/*                                                                          */
3991/* Walk through a list of filter rules and resolve any interface names into */
3992/* pointers.  Where dynamic addresses are used, also update the IP address  */
3993/* used in the rule.  The interface pointer is used to limit the lookups to */
3994/* a specific set of matching names if it is non-NULL.                      */
3995/* Errors can occur when resolving the destination name of to/dup-to fields */
3996/* when the name points to a pool and that pool doest not exist. If this    */
3997/* does happen then it is necessary to check if there are any lookup refs   */
3998/* that need to be dropped before returning with an error.                  */
3999/* ------------------------------------------------------------------------ */
4000static int
4001ipf_synclist(softc, fr, ifp)
4002	ipf_main_softc_t *softc;
4003	frentry_t *fr;
4004	void *ifp;
4005{
4006	frentry_t *frt, *start = fr;
4007	frdest_t *fdp;
4008	char *name;
4009	int error;
4010	void *ifa;
4011	int v, i;
4012
4013	error = 0;
4014
4015	for (; fr; fr = fr->fr_next) {
4016		if (fr->fr_family == AF_INET)
4017			v = 4;
4018		else if (fr->fr_family == AF_INET6)
4019			v = 6;
4020		else
4021			v = 0;
4022
4023		/*
4024		 * Lookup all the interface names that are part of the rule.
4025		 */
4026		for (i = 0; i < 4; i++) {
4027			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4028				continue;
4029			if (fr->fr_ifnames[i] == -1)
4030				continue;
4031			name = FR_NAME(fr, fr_ifnames[i]);
4032			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4033		}
4034
4035		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4036			if (fr->fr_satype != FRI_NORMAL &&
4037			    fr->fr_satype != FRI_LOOKUP) {
4038				ifa = ipf_resolvenic(softc, fr->fr_names +
4039						     fr->fr_sifpidx, v);
4040				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4041					    &fr->fr_src6, &fr->fr_smsk6);
4042			}
4043			if (fr->fr_datype != FRI_NORMAL &&
4044			    fr->fr_datype != FRI_LOOKUP) {
4045				ifa = ipf_resolvenic(softc, fr->fr_names +
4046						     fr->fr_sifpidx, v);
4047				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4048					    &fr->fr_dst6, &fr->fr_dmsk6);
4049			}
4050		}
4051
4052		fdp = &fr->fr_tifs[0];
4053		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4054			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4055			if (error != 0)
4056				goto unwind;
4057		}
4058
4059		fdp = &fr->fr_tifs[1];
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_dif;
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		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4074		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4075			fr->fr_srcptr = ipf_lookup_res_num(softc,
4076							   fr->fr_srctype,
4077							   IPL_LOGIPF,
4078							   fr->fr_srcnum,
4079							   &fr->fr_srcfunc);
4080		}
4081		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4082		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4083			fr->fr_dstptr = ipf_lookup_res_num(softc,
4084							   fr->fr_dsttype,
4085							   IPL_LOGIPF,
4086							   fr->fr_dstnum,
4087							   &fr->fr_dstfunc);
4088		}
4089	}
4090	return 0;
4091
4092unwind:
4093	for (frt = start; frt != fr; fr = fr->fr_next) {
4094		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4095		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4096				ipf_lookup_deref(softc, frt->fr_srctype,
4097						 frt->fr_srcptr);
4098		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4099		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4100				ipf_lookup_deref(softc, frt->fr_dsttype,
4101						 frt->fr_dstptr);
4102	}
4103	return error;
4104}
4105
4106
4107/* ------------------------------------------------------------------------ */
4108/* Function:    ipf_sync                                                    */
4109/* Returns:     void                                                        */
4110/* Parameters:  Nil                                                         */
4111/*                                                                          */
4112/* ipf_sync() is called when we suspect that the interface list or          */
4113/* information about interfaces (like IP#) has changed.  Go through all     */
4114/* filter rules, NAT entries and the state table and check if anything      */
4115/* needs to be changed/updated.                                             */
4116/* ------------------------------------------------------------------------ */
4117int
4118ipf_sync(softc, ifp)
4119	ipf_main_softc_t *softc;
4120	void *ifp;
4121{
4122	int i;
4123
4124# if !SOLARIS
4125	ipf_nat_sync(softc, ifp);
4126	ipf_state_sync(softc, ifp);
4127	ipf_lookup_sync(softc, ifp);
4128# endif
4129
4130	WRITE_ENTER(&softc->ipf_mutex);
4131	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4132	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4133	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4134	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4135
4136	for (i = 0; i < IPL_LOGSIZE; i++) {
4137		frgroup_t *g;
4138
4139		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4140			(void) ipf_synclist(softc, g->fg_start, ifp);
4141		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4142			(void) ipf_synclist(softc, g->fg_start, ifp);
4143	}
4144	RWLOCK_EXIT(&softc->ipf_mutex);
4145
4146	return 0;
4147}
4148
4149
4150/*
4151 * In the functions below, bcopy() is called because the pointer being
4152 * copied _from_ in this instance is a pointer to a char buf (which could
4153 * end up being unaligned) and on the kernel's local stack.
4154 */
4155/* ------------------------------------------------------------------------ */
4156/* Function:    copyinptr                                                   */
4157/* Returns:     int - 0 = success, else failure                             */
4158/* Parameters:  src(I)  - pointer to the source address                     */
4159/*              dst(I)  - destination address                               */
4160/*              size(I) - number of bytes to copy                           */
4161/*                                                                          */
4162/* Copy a block of data in from user space, given a pointer to the pointer  */
4163/* to start copying from (src) and a pointer to where to store it (dst).    */
4164/* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4165/* ------------------------------------------------------------------------ */
4166int
4167copyinptr(softc, src, dst, size)
4168	ipf_main_softc_t *softc;
4169	void *src, *dst;
4170	size_t size;
4171{
4172	caddr_t ca;
4173	int error;
4174
4175# if SOLARIS
4176	error = COPYIN(src, &ca, sizeof(ca));
4177	if (error != 0)
4178		return error;
4179# else
4180	bcopy(src, (caddr_t)&ca, sizeof(ca));
4181# endif
4182	error = COPYIN(ca, dst, size);
4183	if (error != 0) {
4184		IPFERROR(3);
4185		error = EFAULT;
4186	}
4187	return error;
4188}
4189
4190
4191/* ------------------------------------------------------------------------ */
4192/* Function:    copyoutptr                                                  */
4193/* Returns:     int - 0 = success, else failure                             */
4194/* Parameters:  src(I)  - pointer to the source address                     */
4195/*              dst(I)  - destination address                               */
4196/*              size(I) - number of bytes to copy                           */
4197/*                                                                          */
4198/* Copy a block of data out to user space, given a pointer to the pointer   */
4199/* to start copying from (src) and a pointer to where to store it (dst).    */
4200/* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4201/* ------------------------------------------------------------------------ */
4202int
4203copyoutptr(softc, src, dst, size)
4204	ipf_main_softc_t *softc;
4205	void *src, *dst;
4206	size_t size;
4207{
4208	caddr_t ca;
4209	int error;
4210
4211	bcopy(dst, (caddr_t)&ca, sizeof(ca));
4212	error = COPYOUT(src, ca, size);
4213	if (error != 0) {
4214		IPFERROR(4);
4215		error = EFAULT;
4216	}
4217	return error;
4218}
4219
4220
4221/* ------------------------------------------------------------------------ */
4222/* Function:    ipf_lock                                                    */
4223/* Returns:     int      - 0 = success, else error                          */
4224/* Parameters:  data(I)  - pointer to lock value to set                     */
4225/*              lockp(O) - pointer to location to store old lock value      */
4226/*                                                                          */
4227/* Get the new value for the lock integer, set it and return the old value  */
4228/* in *lockp.                                                               */
4229/* ------------------------------------------------------------------------ */
4230int
4231ipf_lock(data, lockp)
4232	caddr_t data;
4233	int *lockp;
4234{
4235	int arg, err;
4236
4237	err = BCOPYIN(data, &arg, sizeof(arg));
4238	if (err != 0)
4239		return EFAULT;
4240	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4241	if (err != 0)
4242		return EFAULT;
4243	*lockp = arg;
4244	return 0;
4245}
4246
4247
4248/* ------------------------------------------------------------------------ */
4249/* Function:    ipf_getstat                                                 */
4250/* Returns:     Nil                                                         */
4251/* Parameters:  softc(I) - pointer to soft context main structure           */
4252/*              fiop(I)  - pointer to ipfilter stats structure              */
4253/*              rev(I)   - version claim by program doing ioctl             */
4254/*                                                                          */
4255/* Stores a copy of current pointers, counters, etc, in the friostat        */
4256/* structure.                                                               */
4257/* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4258/* program is looking for. This ensure that validation of the version it    */
4259/* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4260/* allow older binaries to work but kernels without it will not.            */
4261/* ------------------------------------------------------------------------ */
4262/*ARGSUSED*/
4263static void
4264ipf_getstat(softc, fiop, rev)
4265	ipf_main_softc_t *softc;
4266	friostat_t *fiop;
4267	int rev;
4268{
4269	int i;
4270
4271	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4272	      sizeof(ipf_statistics_t) * 2);
4273	fiop->f_locks[IPL_LOGSTATE] = -1;
4274	fiop->f_locks[IPL_LOGNAT] = -1;
4275	fiop->f_locks[IPL_LOGIPF] = -1;
4276	fiop->f_locks[IPL_LOGAUTH] = -1;
4277
4278	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4279	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4280	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4281	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4282	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4283	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4284	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4285	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4286
4287	fiop->f_ticks = softc->ipf_ticks;
4288	fiop->f_active = softc->ipf_active;
4289	fiop->f_froute[0] = softc->ipf_frouteok[0];
4290	fiop->f_froute[1] = softc->ipf_frouteok[1];
4291	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4292	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4293
4294	fiop->f_running = softc->ipf_running;
4295	for (i = 0; i < IPL_LOGSIZE; i++) {
4296		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4297		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4298	}
4299#ifdef  IPFILTER_LOG
4300	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4301	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4302	fiop->f_logging = 1;
4303#else
4304	fiop->f_log_ok = 0;
4305	fiop->f_log_fail = 0;
4306	fiop->f_logging = 0;
4307#endif
4308	fiop->f_defpass = softc->ipf_pass;
4309	fiop->f_features = ipf_features;
4310
4311#ifdef IPFILTER_COMPAT
4312	sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4313		(rev / 1000000) % 100,
4314		(rev / 10000) % 100,
4315		(rev / 100) % 100);
4316#else
4317	rev = rev;
4318	(void) strncpy(fiop->f_version, ipfilter_version,
4319		       sizeof(fiop->f_version));
4320#endif
4321}
4322
4323
4324#ifdef	USE_INET6
4325int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4326	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4327	-1,			/* 1: UNUSED */
4328	-1,			/* 2: UNUSED */
4329	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4330	-1,			/* 4: ICMP_SOURCEQUENCH */
4331	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4332	-1,			/* 6: UNUSED */
4333	-1,			/* 7: UNUSED */
4334	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4335	-1,			/* 9: UNUSED */
4336	-1,			/* 10: UNUSED */
4337	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4338	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4339	-1,			/* 13: ICMP_TSTAMP */
4340	-1,			/* 14: ICMP_TSTAMPREPLY */
4341	-1,			/* 15: ICMP_IREQ */
4342	-1,			/* 16: ICMP_IREQREPLY */
4343	-1,			/* 17: ICMP_MASKREQ */
4344	-1,			/* 18: ICMP_MASKREPLY */
4345};
4346
4347
4348int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4349	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4350	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4351	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4352	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4353	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4354	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4355	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4356	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4357	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4358	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4359	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4360	-1,				/* 11: ICMP_UNREACH_TOSNET */
4361	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4362	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4363};
4364int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4365#endif
4366
4367int	icmpreplytype4[ICMP_MAXTYPE + 1];
4368
4369
4370/* ------------------------------------------------------------------------ */
4371/* Function:    ipf_matchicmpqueryreply                                     */
4372/* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4373/* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4374/*              ic(I)   - ICMP information                                  */
4375/*              icmp(I) - ICMP packet header                                */
4376/*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4377/*                                                                          */
4378/* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4379/* reply to one as described by what's in ic.  If it is a match, return 1,  */
4380/* else return 0 for no match.                                              */
4381/* ------------------------------------------------------------------------ */
4382int
4383ipf_matchicmpqueryreply(v, ic, icmp, rev)
4384	int v;
4385	icmpinfo_t *ic;
4386	icmphdr_t *icmp;
4387	int rev;
4388{
4389	int ictype;
4390
4391	ictype = ic->ici_type;
4392
4393	if (v == 4) {
4394		/*
4395		 * If we matched its type on the way in, then when going out
4396		 * it will still be the same type.
4397		 */
4398		if ((!rev && (icmp->icmp_type == ictype)) ||
4399		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4400			if (icmp->icmp_type != ICMP_ECHOREPLY)
4401				return 1;
4402			if (icmp->icmp_id == ic->ici_id)
4403				return 1;
4404		}
4405	}
4406#ifdef	USE_INET6
4407	else if (v == 6) {
4408		if ((!rev && (icmp->icmp_type == ictype)) ||
4409		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4410			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4411				return 1;
4412			if (icmp->icmp_id == ic->ici_id)
4413				return 1;
4414		}
4415	}
4416#endif
4417	return 0;
4418}
4419
4420
4421/* ------------------------------------------------------------------------ */
4422/* Function:    ipf_rule_compare                                            */
4423/* Parameters:  fr1(I) - first rule structure to compare                    */
4424/*              fr2(I) - second rule structure to compare                   */
4425/* Returns:     int    - 0 == rules are the same, else mismatch             */
4426/*                                                                          */
4427/* Compare two rules and return 0 if they match or a number indicating      */
4428/* which of the individual checks failed.                                   */
4429/* ------------------------------------------------------------------------ */
4430static int
4431ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4432{
4433	if (fr1->fr_cksum != fr2->fr_cksum)
4434		return 1;
4435	if (fr1->fr_size != fr2->fr_size)
4436		return 2;
4437	if (fr1->fr_dsize != fr2->fr_dsize)
4438		return 3;
4439	if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4440		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4441		return 4;
4442	if (fr1->fr_data && !fr2->fr_data)
4443		return 5;
4444	if (!fr1->fr_data && fr2->fr_data)
4445		return 6;
4446	if (fr1->fr_data) {
4447		if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4448			return 7;
4449	}
4450	return 0;
4451}
4452
4453
4454/* ------------------------------------------------------------------------ */
4455/* Function:    frrequest                                                   */
4456/* Returns:     int - 0 == success, > 0 == errno value                      */
4457/* Parameters:  unit(I)     - device for which this is for                  */
4458/*              req(I)      - ioctl command (SIOC*)                         */
4459/*              data(I)     - pointr to ioctl data                          */
4460/*              set(I)      - 1 or 0 (filter set)                           */
4461/*              makecopy(I) - flag indicating whether data points to a rule */
4462/*                            in kernel space & hence doesn't need copying. */
4463/*                                                                          */
4464/* This function handles all the requests which operate on the list of      */
4465/* filter rules.  This includes adding, deleting, insertion.  It is also    */
4466/* responsible for creating groups when a "head" rule is loaded.  Interface */
4467/* names are resolved here and other sanity checks are made on the content  */
4468/* of the rule structure being loaded.  If a rule has user defined timeouts */
4469/* then make sure they are created and initialised before exiting.          */
4470/* ------------------------------------------------------------------------ */
4471int
4472frrequest(softc, unit, req, data, set, makecopy)
4473	ipf_main_softc_t *softc;
4474	int unit;
4475	ioctlcmd_t req;
4476	int set, makecopy;
4477	caddr_t data;
4478{
4479	int error = 0, in, family, addrem, need_free = 0;
4480	frentry_t frd, *fp, *f, **fprev, **ftail;
4481	void *ptr, *uptr, *cptr;
4482	u_int *p, *pp;
4483	frgroup_t *fg;
4484	char *group;
4485
4486	ptr = NULL;
4487	cptr = NULL;
4488	fg = NULL;
4489	fp = &frd;
4490	if (makecopy != 0) {
4491		bzero(fp, sizeof(frd));
4492		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4493		if (error) {
4494			return error;
4495		}
4496		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4497			IPFERROR(6);
4498			return EINVAL;
4499		}
4500		KMALLOCS(f, frentry_t *, fp->fr_size);
4501		if (f == NULL) {
4502			IPFERROR(131);
4503			return ENOMEM;
4504		}
4505		bzero(f, fp->fr_size);
4506		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4507				    fp->fr_size);
4508		if (error) {
4509			KFREES(f, fp->fr_size);
4510			return error;
4511		}
4512
4513		fp = f;
4514		f = NULL;
4515		fp->fr_next = NULL;
4516		fp->fr_dnext = NULL;
4517		fp->fr_pnext = NULL;
4518		fp->fr_pdnext = NULL;
4519		fp->fr_grp = NULL;
4520		fp->fr_grphead = NULL;
4521		fp->fr_icmpgrp = NULL;
4522		fp->fr_isc = (void *)-1;
4523		fp->fr_ptr = NULL;
4524		fp->fr_ref = 0;
4525		fp->fr_flags |= FR_COPIED;
4526	} else {
4527		fp = (frentry_t *)data;
4528		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4529			IPFERROR(7);
4530			return EINVAL;
4531		}
4532		fp->fr_flags &= ~FR_COPIED;
4533	}
4534
4535	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4536	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4537		IPFERROR(8);
4538		error = EINVAL;
4539		goto donenolock;
4540	}
4541
4542	family = fp->fr_family;
4543	uptr = fp->fr_data;
4544
4545	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4546	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4547		addrem = 0;
4548	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4549		addrem = 1;
4550	else if (req == (ioctlcmd_t)SIOCZRLST)
4551		addrem = 2;
4552	else {
4553		IPFERROR(9);
4554		error = EINVAL;
4555		goto donenolock;
4556	}
4557
4558	/*
4559	 * Only filter rules for IPv4 or IPv6 are accepted.
4560	 */
4561	if (family == AF_INET) {
4562		/*EMPTY*/;
4563#ifdef	USE_INET6
4564	} else if (family == AF_INET6) {
4565		/*EMPTY*/;
4566#endif
4567	} else if (family != 0) {
4568		IPFERROR(10);
4569		error = EINVAL;
4570		goto donenolock;
4571	}
4572
4573	/*
4574	 * If the rule is being loaded from user space, i.e. we had to copy it
4575	 * into kernel space, then do not trust the function pointer in the
4576	 * rule.
4577	 */
4578	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4579		if (ipf_findfunc(fp->fr_func) == NULL) {
4580			IPFERROR(11);
4581			error = ESRCH;
4582			goto donenolock;
4583		}
4584
4585		if (addrem == 0) {
4586			error = ipf_funcinit(softc, fp);
4587			if (error != 0)
4588				goto donenolock;
4589		}
4590	}
4591	if ((fp->fr_flags & FR_CALLNOW) &&
4592	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4593		IPFERROR(142);
4594		error = ESRCH;
4595		goto donenolock;
4596	}
4597	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4598	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4599		IPFERROR(143);
4600		error = ESRCH;
4601		goto donenolock;
4602	}
4603
4604	ptr = NULL;
4605	cptr = NULL;
4606
4607	if (FR_ISACCOUNT(fp->fr_flags))
4608		unit = IPL_LOGCOUNT;
4609
4610	/*
4611	 * Check that each group name in the rule has a start index that
4612	 * is valid.
4613	 */
4614	if (fp->fr_icmphead != -1) {
4615		if ((fp->fr_icmphead < 0) ||
4616		    (fp->fr_icmphead >= fp->fr_namelen)) {
4617			IPFERROR(136);
4618			error = EINVAL;
4619			goto donenolock;
4620		}
4621		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4622			fp->fr_names[fp->fr_icmphead] = '\0';
4623	}
4624
4625	if (fp->fr_grhead != -1) {
4626		if ((fp->fr_grhead < 0) ||
4627		    (fp->fr_grhead >= fp->fr_namelen)) {
4628			IPFERROR(137);
4629			error = EINVAL;
4630			goto donenolock;
4631		}
4632		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4633			fp->fr_names[fp->fr_grhead] = '\0';
4634	}
4635
4636	if (fp->fr_group != -1) {
4637		if ((fp->fr_group < 0) ||
4638		    (fp->fr_group >= fp->fr_namelen)) {
4639			IPFERROR(138);
4640			error = EINVAL;
4641			goto donenolock;
4642		}
4643		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4644			/*
4645			 * Allow loading rules that are in groups to cause
4646			 * them to be created if they don't already exit.
4647			 */
4648			group = FR_NAME(fp, fr_group);
4649			if (addrem == 0) {
4650				fg = ipf_group_add(softc, group, NULL,
4651						   fp->fr_flags, unit, set);
4652				fp->fr_grp = fg;
4653			} else {
4654				fg = ipf_findgroup(softc, group, unit,
4655						   set, NULL);
4656				if (fg == NULL) {
4657					IPFERROR(12);
4658					error = ESRCH;
4659					goto donenolock;
4660				}
4661			}
4662
4663			if (fg->fg_flags == 0) {
4664				fg->fg_flags = fp->fr_flags & FR_INOUT;
4665			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4666				IPFERROR(13);
4667				error = ESRCH;
4668				goto donenolock;
4669			}
4670		}
4671	} else {
4672		/*
4673		 * If a rule is going to be part of a group then it does
4674		 * not matter whether it is an in or out rule, but if it
4675		 * isn't in a group, then it does...
4676		 */
4677		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4678			IPFERROR(14);
4679			error = EINVAL;
4680			goto donenolock;
4681		}
4682	}
4683	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4684
4685	/*
4686	 * Work out which rule list this change is being applied to.
4687	 */
4688	ftail = NULL;
4689	fprev = NULL;
4690	if (unit == IPL_LOGAUTH) {
4691                if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4692		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4693		    (fp->fr_dif.fd_ptr != NULL) ||
4694		    (fp->fr_flags & FR_FASTROUTE)) {
4695			softc->ipf_interror = 145;
4696			error = EINVAL;
4697			goto donenolock;
4698		}
4699		fprev = ipf_auth_rulehead(softc);
4700	} else {
4701		if (FR_ISACCOUNT(fp->fr_flags))
4702			fprev = &softc->ipf_acct[in][set];
4703		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4704			fprev = &softc->ipf_rules[in][set];
4705	}
4706	if (fprev == NULL) {
4707		IPFERROR(15);
4708		error = ESRCH;
4709		goto donenolock;
4710	}
4711
4712	if (fg != NULL)
4713		fprev = &fg->fg_start;
4714
4715	/*
4716	 * Copy in extra data for the rule.
4717	 */
4718	if (fp->fr_dsize != 0) {
4719		if (makecopy != 0) {
4720			KMALLOCS(ptr, void *, fp->fr_dsize);
4721			if (ptr == NULL) {
4722				IPFERROR(16);
4723				error = ENOMEM;
4724				goto donenolock;
4725			}
4726
4727			/*
4728			 * The bcopy case is for when the data is appended
4729			 * to the rule by ipf_in_compat().
4730			 */
4731			if (uptr >= (void *)fp &&
4732			    uptr < (void *)((char *)fp + fp->fr_size)) {
4733				bcopy(uptr, ptr, fp->fr_dsize);
4734				error = 0;
4735			} else {
4736				error = COPYIN(uptr, ptr, fp->fr_dsize);
4737				if (error != 0) {
4738					IPFERROR(17);
4739					error = EFAULT;
4740					goto donenolock;
4741				}
4742			}
4743		} else {
4744			ptr = uptr;
4745		}
4746		fp->fr_data = ptr;
4747	} else {
4748		fp->fr_data = NULL;
4749	}
4750
4751	/*
4752	 * Perform per-rule type sanity checks of their members.
4753	 * All code after this needs to be aware that allocated memory
4754	 * may need to be free'd before exiting.
4755	 */
4756	switch (fp->fr_type & ~FR_T_BUILTIN)
4757	{
4758#if defined(IPFILTER_BPF)
4759	case FR_T_BPFOPC :
4760		if (fp->fr_dsize == 0) {
4761			IPFERROR(19);
4762			error = EINVAL;
4763			break;
4764		}
4765		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4766			IPFERROR(20);
4767			error = EINVAL;
4768			break;
4769		}
4770		break;
4771#endif
4772	case FR_T_IPF :
4773		/*
4774		 * Preparation for error case at the bottom of this function.
4775		 */
4776		if (fp->fr_datype == FRI_LOOKUP)
4777			fp->fr_dstptr = NULL;
4778		if (fp->fr_satype == FRI_LOOKUP)
4779			fp->fr_srcptr = NULL;
4780
4781		if (fp->fr_dsize != sizeof(fripf_t)) {
4782			IPFERROR(21);
4783			error = EINVAL;
4784			break;
4785		}
4786
4787		/*
4788		 * Allowing a rule with both "keep state" and "with oow" is
4789		 * pointless because adding a state entry to the table will
4790		 * fail with the out of window (oow) flag set.
4791		 */
4792		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4793			IPFERROR(22);
4794			error = EINVAL;
4795			break;
4796		}
4797
4798		switch (fp->fr_satype)
4799		{
4800		case FRI_BROADCAST :
4801		case FRI_DYNAMIC :
4802		case FRI_NETWORK :
4803		case FRI_NETMASKED :
4804		case FRI_PEERADDR :
4805			if (fp->fr_sifpidx < 0) {
4806				IPFERROR(23);
4807				error = EINVAL;
4808			}
4809			break;
4810		case FRI_LOOKUP :
4811			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4812						       &fp->fr_src6,
4813						       &fp->fr_smsk6);
4814			if (fp->fr_srcfunc == NULL) {
4815				IPFERROR(132);
4816				error = ESRCH;
4817				break;
4818			}
4819			break;
4820		case FRI_NORMAL :
4821			break;
4822		default :
4823			IPFERROR(133);
4824			error = EINVAL;
4825			break;
4826		}
4827		if (error != 0)
4828			break;
4829
4830		switch (fp->fr_datype)
4831		{
4832		case FRI_BROADCAST :
4833		case FRI_DYNAMIC :
4834		case FRI_NETWORK :
4835		case FRI_NETMASKED :
4836		case FRI_PEERADDR :
4837			if (fp->fr_difpidx < 0) {
4838				IPFERROR(24);
4839				error = EINVAL;
4840			}
4841			break;
4842		case FRI_LOOKUP :
4843			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4844						       &fp->fr_dst6,
4845						       &fp->fr_dmsk6);
4846			if (fp->fr_dstfunc == NULL) {
4847				IPFERROR(134);
4848				error = ESRCH;
4849			}
4850			break;
4851		case FRI_NORMAL :
4852			break;
4853		default :
4854			IPFERROR(135);
4855			error = EINVAL;
4856		}
4857		break;
4858
4859	case FR_T_NONE :
4860	case FR_T_CALLFUNC :
4861	case FR_T_COMPIPF :
4862		break;
4863
4864	case FR_T_IPFEXPR :
4865		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4866			IPFERROR(25);
4867			error = EINVAL;
4868		}
4869		break;
4870
4871	default :
4872		IPFERROR(26);
4873		error = EINVAL;
4874		break;
4875	}
4876	if (error != 0)
4877		goto donenolock;
4878
4879	if (fp->fr_tif.fd_name != -1) {
4880		if ((fp->fr_tif.fd_name < 0) ||
4881		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4882			IPFERROR(139);
4883			error = EINVAL;
4884			goto donenolock;
4885		}
4886	}
4887
4888	if (fp->fr_dif.fd_name != -1) {
4889		if ((fp->fr_dif.fd_name < 0) ||
4890		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4891			IPFERROR(140);
4892			error = EINVAL;
4893			goto donenolock;
4894		}
4895	}
4896
4897	if (fp->fr_rif.fd_name != -1) {
4898		if ((fp->fr_rif.fd_name < 0) ||
4899		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4900			IPFERROR(141);
4901			error = EINVAL;
4902			goto donenolock;
4903		}
4904	}
4905
4906	/*
4907	 * Lookup all the interface names that are part of the rule.
4908	 */
4909	error = ipf_synclist(softc, fp, NULL);
4910	if (error != 0)
4911		goto donenolock;
4912	fp->fr_statecnt = 0;
4913	if (fp->fr_srctrack.ht_max_nodes != 0)
4914		ipf_rb_ht_init(&fp->fr_srctrack);
4915
4916	/*
4917	 * Look for an existing matching filter rule, but don't include the
4918	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4919	 * This elminates rules which are indentical being loaded.  Checksum
4920	 * the constant part of the filter rule to make comparisons quicker
4921	 * (this meaning no pointers are included).
4922	 */
4923	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4924	     p < pp; p++)
4925		fp->fr_cksum += *p;
4926	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4927	for (p = (u_int *)fp->fr_data; p < pp; p++)
4928		fp->fr_cksum += *p;
4929
4930	WRITE_ENTER(&softc->ipf_mutex);
4931
4932	/*
4933	 * Now that the filter rule lists are locked, we can walk the
4934	 * chain of them without fear.
4935	 */
4936	ftail = fprev;
4937	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4938		if (fp->fr_collect <= f->fr_collect) {
4939			ftail = fprev;
4940			f = NULL;
4941			break;
4942		}
4943		fprev = ftail;
4944	}
4945
4946	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4947		if (ipf_rule_compare(fp, f) == 0)
4948			break;
4949	}
4950
4951	/*
4952	 * If zero'ing statistics, copy current to caller and zero.
4953	 */
4954	if (addrem == 2) {
4955		if (f == NULL) {
4956			IPFERROR(27);
4957			error = ESRCH;
4958		} else {
4959			/*
4960			 * Copy and reduce lock because of impending copyout.
4961			 * Well we should, but if we do then the atomicity of
4962			 * this call and the correctness of fr_hits and
4963			 * fr_bytes cannot be guaranteed.  As it is, this code
4964			 * only resets them to 0 if they are successfully
4965			 * copied out into user space.
4966			 */
4967			bcopy((char *)f, (char *)fp, f->fr_size);
4968			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4969
4970			/*
4971			 * When we copy this rule back out, set the data
4972			 * pointer to be what it was in user space.
4973			 */
4974			fp->fr_data = uptr;
4975			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4976
4977			if (error == 0) {
4978				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4979					error = COPYOUT(f->fr_data, uptr,
4980							f->fr_dsize);
4981					if (error == 0) {
4982						f->fr_hits = 0;
4983						f->fr_bytes = 0;
4984					} else {
4985						IPFERROR(28);
4986						error = EFAULT;
4987					}
4988				}
4989			}
4990		}
4991
4992		if (makecopy != 0) {
4993			if (ptr != NULL) {
4994				KFREES(ptr, fp->fr_dsize);
4995			}
4996			KFREES(fp, fp->fr_size);
4997		}
4998		RWLOCK_EXIT(&softc->ipf_mutex);
4999		return error;
5000	}
5001
5002	if (f == NULL) {
5003		/*
5004		 * At the end of this, ftail must point to the place where the
5005		 * new rule is to be saved/inserted/added.
5006		 * For SIOCAD*FR, this should be the last rule in the group of
5007		 * rules that have equal fr_collect fields.
5008		 * For SIOCIN*FR, ...
5009		 */
5010		if (req == (ioctlcmd_t)SIOCADAFR ||
5011		    req == (ioctlcmd_t)SIOCADIFR) {
5012
5013			for (ftail = fprev; (f = *ftail) != NULL; ) {
5014				if (f->fr_collect > fp->fr_collect)
5015					break;
5016				ftail = &f->fr_next;
5017				fprev = ftail;
5018			}
5019			ftail = fprev;
5020			f = NULL;
5021			ptr = NULL;
5022		} else if (req == (ioctlcmd_t)SIOCINAFR ||
5023			   req == (ioctlcmd_t)SIOCINIFR) {
5024			while ((f = *fprev) != NULL) {
5025				if (f->fr_collect >= fp->fr_collect)
5026					break;
5027				fprev = &f->fr_next;
5028			}
5029  			ftail = fprev;
5030  			if (fp->fr_hits != 0) {
5031				while (fp->fr_hits && (f = *ftail)) {
5032					if (f->fr_collect != fp->fr_collect)
5033						break;
5034					fprev = ftail;
5035  					ftail = &f->fr_next;
5036					fp->fr_hits--;
5037				}
5038  			}
5039  			f = NULL;
5040  			ptr = NULL;
5041		}
5042	}
5043
5044	/*
5045	 * Request to remove a rule.
5046	 */
5047	if (addrem == 1) {
5048		if (f == NULL) {
5049			IPFERROR(29);
5050			error = ESRCH;
5051		} else {
5052			/*
5053			 * Do not allow activity from user space to interfere
5054			 * with rules not loaded that way.
5055			 */
5056			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5057				IPFERROR(30);
5058				error = EPERM;
5059				goto done;
5060			}
5061
5062			/*
5063			 * Return EBUSY if the rule is being reference by
5064			 * something else (eg state information.)
5065			 */
5066			if (f->fr_ref > 1) {
5067				IPFERROR(31);
5068				error = EBUSY;
5069				goto done;
5070			}
5071#ifdef	IPFILTER_SCAN
5072			if (f->fr_isctag != -1 &&
5073			    (f->fr_isc != (struct ipscan *)-1))
5074				ipf_scan_detachfr(f);
5075#endif
5076
5077			if (unit == IPL_LOGAUTH) {
5078				error = ipf_auth_precmd(softc, req, f, ftail);
5079				goto done;
5080			}
5081
5082			ipf_rule_delete(softc, f, unit, set);
5083
5084			need_free = makecopy;
5085		}
5086	} else {
5087		/*
5088		 * Not removing, so we must be adding/inserting a rule.
5089		 */
5090		if (f != NULL) {
5091			IPFERROR(32);
5092			error = EEXIST;
5093			goto done;
5094		}
5095		if (unit == IPL_LOGAUTH) {
5096			error = ipf_auth_precmd(softc, req, fp, ftail);
5097			goto done;
5098		}
5099
5100		MUTEX_NUKE(&fp->fr_lock);
5101		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5102		if (fp->fr_die != 0)
5103			ipf_rule_expire_insert(softc, fp, set);
5104
5105		fp->fr_hits = 0;
5106		if (makecopy != 0)
5107			fp->fr_ref = 1;
5108		fp->fr_pnext = ftail;
5109		fp->fr_next = *ftail;
5110		if (fp->fr_next != NULL)
5111			fp->fr_next->fr_pnext = &fp->fr_next;
5112		*ftail = fp;
5113		if (addrem == 0)
5114			ipf_fixskip(ftail, fp, 1);
5115
5116		fp->fr_icmpgrp = NULL;
5117		if (fp->fr_icmphead != -1) {
5118			group = FR_NAME(fp, fr_icmphead);
5119			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5120			fp->fr_icmpgrp = fg;
5121		}
5122
5123		fp->fr_grphead = NULL;
5124		if (fp->fr_grhead != -1) {
5125			group = FR_NAME(fp, fr_grhead);
5126			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5127					   unit, set);
5128			fp->fr_grphead = fg;
5129		}
5130	}
5131done:
5132	RWLOCK_EXIT(&softc->ipf_mutex);
5133donenolock:
5134	if (need_free || (error != 0)) {
5135		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5136			if ((fp->fr_satype == FRI_LOOKUP) &&
5137			    (fp->fr_srcptr != NULL))
5138				ipf_lookup_deref(softc, fp->fr_srctype,
5139						 fp->fr_srcptr);
5140			if ((fp->fr_datype == FRI_LOOKUP) &&
5141			    (fp->fr_dstptr != NULL))
5142				ipf_lookup_deref(softc, fp->fr_dsttype,
5143						 fp->fr_dstptr);
5144		}
5145		if (fp->fr_grp != NULL) {
5146			WRITE_ENTER(&softc->ipf_mutex);
5147			ipf_group_del(softc, fp->fr_grp, fp);
5148			RWLOCK_EXIT(&softc->ipf_mutex);
5149		}
5150		if ((ptr != NULL) && (makecopy != 0)) {
5151			KFREES(ptr, fp->fr_dsize);
5152		}
5153		KFREES(fp, fp->fr_size);
5154	}
5155	return (error);
5156}
5157
5158
5159/* ------------------------------------------------------------------------ */
5160/* Function:   ipf_rule_delete                                              */
5161/* Returns:    Nil                                                          */
5162/* Parameters: softc(I) - pointer to soft context main structure            */
5163/*             f(I)     - pointer to the rule being deleted                 */
5164/*             ftail(I) - pointer to the pointer to f                       */
5165/*             unit(I)  - device for which this is for                      */
5166/*             set(I)   - 1 or 0 (filter set)                               */
5167/*                                                                          */
5168/* This function attempts to do what it can to delete a filter rule: remove */
5169/* it from any linked lists and remove any groups it is responsible for.    */
5170/* But in the end, removing a rule can only drop the reference count - we   */
5171/* must use that as the guide for whether or not it can be freed.           */
5172/* ------------------------------------------------------------------------ */
5173static void
5174ipf_rule_delete(softc, f, unit, set)
5175	ipf_main_softc_t *softc;
5176	frentry_t *f;
5177	int unit, set;
5178{
5179
5180	/*
5181	 * If fr_pdnext is set, then the rule is on the expire list, so
5182	 * remove it from there.
5183	 */
5184	if (f->fr_pdnext != NULL) {
5185		*f->fr_pdnext = f->fr_dnext;
5186		if (f->fr_dnext != NULL)
5187			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5188		f->fr_pdnext = NULL;
5189		f->fr_dnext = NULL;
5190	}
5191
5192	ipf_fixskip(f->fr_pnext, f, -1);
5193	if (f->fr_pnext != NULL)
5194		*f->fr_pnext = f->fr_next;
5195	if (f->fr_next != NULL)
5196		f->fr_next->fr_pnext = f->fr_pnext;
5197	f->fr_pnext = NULL;
5198	f->fr_next = NULL;
5199
5200	(void) ipf_derefrule(softc, &f);
5201}
5202
5203/* ------------------------------------------------------------------------ */
5204/* Function:   ipf_rule_expire_insert                                       */
5205/* Returns:    Nil                                                          */
5206/* Parameters: softc(I) - pointer to soft context main structure            */
5207/*             f(I)     - pointer to rule to be added to expire list        */
5208/*             set(I)   - 1 or 0 (filter set)                               */
5209/*                                                                          */
5210/* If the new rule has a given expiration time, insert it into the list of  */
5211/* expiring rules with the ones to be removed first added to the front of   */
5212/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5213/* expiration interval checks.                                              */
5214/* ------------------------------------------------------------------------ */
5215static void
5216ipf_rule_expire_insert(softc, f, set)
5217	ipf_main_softc_t *softc;
5218	frentry_t *f;
5219	int set;
5220{
5221	frentry_t *fr;
5222
5223	/*
5224	 */
5225
5226	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5227	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5228	     fr = fr->fr_dnext) {
5229		if (f->fr_die < fr->fr_die)
5230			break;
5231		if (fr->fr_dnext == NULL) {
5232			/*
5233			 * We've got to the last rule and everything
5234			 * wanted to be expired before this new node,
5235			 * so we have to tack it on the end...
5236			 */
5237			fr->fr_dnext = f;
5238			f->fr_pdnext = &fr->fr_dnext;
5239			fr = NULL;
5240			break;
5241		}
5242	}
5243
5244	if (softc->ipf_rule_explist[set] == NULL) {
5245		softc->ipf_rule_explist[set] = f;
5246		f->fr_pdnext = &softc->ipf_rule_explist[set];
5247	} else if (fr != NULL) {
5248		f->fr_dnext = fr;
5249		f->fr_pdnext = fr->fr_pdnext;
5250		fr->fr_pdnext = &f->fr_dnext;
5251	}
5252}
5253
5254
5255/* ------------------------------------------------------------------------ */
5256/* Function:   ipf_findlookup                                               */
5257/* Returns:    NULL = failure, else success                                 */
5258/* Parameters: softc(I) - pointer to soft context main structure            */
5259/*             unit(I)  - ipf device we want to find match for              */
5260/*             fp(I)    - rule for which lookup is for                      */
5261/*             addrp(I) - pointer to lookup information in address struct   */
5262/*             maskp(O) - pointer to lookup information for storage         */
5263/*                                                                          */
5264/* When using pools and hash tables to store addresses for matching in      */
5265/* rules, it is necessary to resolve both the object referred to by the     */
5266/* name or address (and return that pointer) and also provide the means by  */
5267/* which to determine if an address belongs to that object to make the      */
5268/* packet matching quicker.                                                 */
5269/* ------------------------------------------------------------------------ */
5270static void *
5271ipf_findlookup(softc, unit, fr, addrp, maskp)
5272	ipf_main_softc_t *softc;
5273	int unit;
5274	frentry_t *fr;
5275	i6addr_t *addrp, *maskp;
5276{
5277	void *ptr = NULL;
5278
5279	switch (addrp->iplookupsubtype)
5280	{
5281	case 0 :
5282		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5283					 addrp->iplookupnum,
5284					 &maskp->iplookupfunc);
5285		break;
5286	case 1 :
5287		if (addrp->iplookupname < 0)
5288			break;
5289		if (addrp->iplookupname >= fr->fr_namelen)
5290			break;
5291		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5292					  fr->fr_names + addrp->iplookupname,
5293					  &maskp->iplookupfunc);
5294		break;
5295	default :
5296		break;
5297	}
5298
5299	return ptr;
5300}
5301
5302
5303/* ------------------------------------------------------------------------ */
5304/* Function:    ipf_funcinit                                                */
5305/* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5306/* Parameters:  softc(I) - pointer to soft context main structure           */
5307/*              fr(I)    - pointer to filter rule                           */
5308/*                                                                          */
5309/* If a rule is a call rule, then check if the function it points to needs  */
5310/* an init function to be called now the rule has been loaded.              */
5311/* ------------------------------------------------------------------------ */
5312static int
5313ipf_funcinit(softc, fr)
5314	ipf_main_softc_t *softc;
5315	frentry_t *fr;
5316{
5317	ipfunc_resolve_t *ft;
5318	int err;
5319
5320	IPFERROR(34);
5321	err = ESRCH;
5322
5323	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5324		if (ft->ipfu_addr == fr->fr_func) {
5325			err = 0;
5326			if (ft->ipfu_init != NULL)
5327				err = (*ft->ipfu_init)(softc, fr);
5328			break;
5329		}
5330	return err;
5331}
5332
5333
5334/* ------------------------------------------------------------------------ */
5335/* Function:    ipf_funcfini                                                */
5336/* Returns:     Nil                                                         */
5337/* Parameters:  softc(I) - pointer to soft context main structure           */
5338/*              fr(I)    - pointer to filter rule                           */
5339/*                                                                          */
5340/* For a given filter rule, call the matching "fini" function if the rule   */
5341/* is using a known function that would have resulted in the "init" being   */
5342/* called for ealier.                                                       */
5343/* ------------------------------------------------------------------------ */
5344static void
5345ipf_funcfini(softc, fr)
5346	ipf_main_softc_t *softc;
5347	frentry_t *fr;
5348{
5349	ipfunc_resolve_t *ft;
5350
5351	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5352		if (ft->ipfu_addr == fr->fr_func) {
5353			if (ft->ipfu_fini != NULL)
5354				(void) (*ft->ipfu_fini)(softc, fr);
5355			break;
5356		}
5357}
5358
5359
5360/* ------------------------------------------------------------------------ */
5361/* Function:    ipf_findfunc                                                */
5362/* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5363/* Parameters:  funcptr(I) - function pointer to lookup                     */
5364/*                                                                          */
5365/* Look for a function in the table of known functions.                     */
5366/* ------------------------------------------------------------------------ */
5367static ipfunc_t
5368ipf_findfunc(funcptr)
5369	ipfunc_t funcptr;
5370{
5371	ipfunc_resolve_t *ft;
5372
5373	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5374		if (ft->ipfu_addr == funcptr)
5375			return funcptr;
5376	return NULL;
5377}
5378
5379
5380/* ------------------------------------------------------------------------ */
5381/* Function:    ipf_resolvefunc                                             */
5382/* Returns:     int - 0 == success, else error                              */
5383/* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5384/*                                                                          */
5385/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5386/* This will either be the function name (if the pointer is set) or the     */
5387/* function pointer if the name is set.  When found, fill in the other one  */
5388/* so that the entire, complete, structure can be copied back to user space.*/
5389/* ------------------------------------------------------------------------ */
5390int
5391ipf_resolvefunc(softc, data)
5392	ipf_main_softc_t *softc;
5393	void *data;
5394{
5395	ipfunc_resolve_t res, *ft;
5396	int error;
5397
5398	error = BCOPYIN(data, &res, sizeof(res));
5399	if (error != 0) {
5400		IPFERROR(123);
5401		return EFAULT;
5402	}
5403
5404	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5405		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5406			if (strncmp(res.ipfu_name, ft->ipfu_name,
5407				    sizeof(res.ipfu_name)) == 0) {
5408				res.ipfu_addr = ft->ipfu_addr;
5409				res.ipfu_init = ft->ipfu_init;
5410				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5411					IPFERROR(35);
5412					return EFAULT;
5413				}
5414				return 0;
5415			}
5416	}
5417	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5418		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5419			if (ft->ipfu_addr == res.ipfu_addr) {
5420				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5421					       sizeof(res.ipfu_name));
5422				res.ipfu_init = ft->ipfu_init;
5423				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5424					IPFERROR(36);
5425					return EFAULT;
5426				}
5427				return 0;
5428			}
5429	}
5430	IPFERROR(37);
5431	return ESRCH;
5432}
5433
5434
5435#if !defined(_KERNEL) || SOLARIS
5436/*
5437 * From: NetBSD
5438 * ppsratecheck(): packets (or events) per second limitation.
5439 */
5440int
5441ppsratecheck(lasttime, curpps, maxpps)
5442	struct timeval *lasttime;
5443	int *curpps;
5444	int maxpps;	/* maximum pps allowed */
5445{
5446	struct timeval tv, delta;
5447	int rv;
5448
5449	GETKTIME(&tv);
5450
5451	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5452	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5453	if (delta.tv_usec < 0) {
5454		delta.tv_sec--;
5455		delta.tv_usec += 1000000;
5456	}
5457
5458	/*
5459	 * check for 0,0 is so that the message will be seen at least once.
5460	 * if more than one second have passed since the last update of
5461	 * lasttime, reset the counter.
5462	 *
5463	 * we do increment *curpps even in *curpps < maxpps case, as some may
5464	 * try to use *curpps for stat purposes as well.
5465	 */
5466	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5467	    delta.tv_sec >= 1) {
5468		*lasttime = tv;
5469		*curpps = 0;
5470		rv = 1;
5471	} else if (maxpps < 0)
5472		rv = 1;
5473	else if (*curpps < maxpps)
5474		rv = 1;
5475	else
5476		rv = 0;
5477	*curpps = *curpps + 1;
5478
5479	return (rv);
5480}
5481#endif
5482
5483
5484/* ------------------------------------------------------------------------ */
5485/* Function:    ipf_derefrule                                               */
5486/* Returns:     int   - 0 == rule freed up, else rule not freed             */
5487/* Parameters:  fr(I) - pointer to filter rule                              */
5488/*                                                                          */
5489/* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5490/* free it and any associated storage space being used by it.               */
5491/* ------------------------------------------------------------------------ */
5492int
5493ipf_derefrule(softc, frp)
5494	ipf_main_softc_t *softc;
5495	frentry_t **frp;
5496{
5497	frentry_t *fr;
5498	frdest_t *fdp;
5499
5500	fr = *frp;
5501	*frp = NULL;
5502
5503	MUTEX_ENTER(&fr->fr_lock);
5504	fr->fr_ref--;
5505	if (fr->fr_ref == 0) {
5506		MUTEX_EXIT(&fr->fr_lock);
5507		MUTEX_DESTROY(&fr->fr_lock);
5508
5509		ipf_funcfini(softc, fr);
5510
5511		fdp = &fr->fr_tif;
5512		if (fdp->fd_type == FRD_DSTLIST)
5513			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5514
5515		fdp = &fr->fr_rif;
5516		if (fdp->fd_type == FRD_DSTLIST)
5517			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5518
5519		fdp = &fr->fr_dif;
5520		if (fdp->fd_type == FRD_DSTLIST)
5521			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5522
5523		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5524		    fr->fr_satype == FRI_LOOKUP)
5525			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5526		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5527		    fr->fr_datype == FRI_LOOKUP)
5528			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5529
5530		if (fr->fr_grp != NULL)
5531			ipf_group_del(softc, fr->fr_grp, fr);
5532
5533		if (fr->fr_grphead != NULL)
5534			ipf_group_del(softc, fr->fr_grphead, fr);
5535
5536		if (fr->fr_icmpgrp != NULL)
5537			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5538
5539		if ((fr->fr_flags & FR_COPIED) != 0) {
5540			if (fr->fr_dsize) {
5541				KFREES(fr->fr_data, fr->fr_dsize);
5542			}
5543			KFREES(fr, fr->fr_size);
5544			return 0;
5545		}
5546		return 1;
5547	} else {
5548		MUTEX_EXIT(&fr->fr_lock);
5549	}
5550	return -1;
5551}
5552
5553
5554/* ------------------------------------------------------------------------ */
5555/* Function:    ipf_grpmapinit                                              */
5556/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5557/* Parameters:  fr(I) - pointer to rule to find hash table for              */
5558/*                                                                          */
5559/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5560/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5561/* ------------------------------------------------------------------------ */
5562static int
5563ipf_grpmapinit(softc, fr)
5564	ipf_main_softc_t *softc;
5565	frentry_t *fr;
5566{
5567	char name[FR_GROUPLEN];
5568	iphtable_t *iph;
5569
5570#if defined(SNPRINTF) && defined(_KERNEL)
5571	SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5572#else
5573	(void) sprintf(name, "%d", fr->fr_arg);
5574#endif
5575	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5576	if (iph == NULL) {
5577		IPFERROR(38);
5578		return ESRCH;
5579	}
5580	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5581		IPFERROR(39);
5582		return ESRCH;
5583	}
5584	iph->iph_ref++;
5585	fr->fr_ptr = iph;
5586	return 0;
5587}
5588
5589
5590/* ------------------------------------------------------------------------ */
5591/* Function:    ipf_grpmapfini                                              */
5592/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5593/* Parameters:  softc(I) - pointer to soft context main structure           */
5594/*              fr(I)    - pointer to rule to release hash table for        */
5595/*                                                                          */
5596/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5597/* be called to undo what ipf_grpmapinit caused to be done.                 */
5598/* ------------------------------------------------------------------------ */
5599static int
5600ipf_grpmapfini(softc, fr)
5601	ipf_main_softc_t *softc;
5602	frentry_t *fr;
5603{
5604	iphtable_t *iph;
5605	iph = fr->fr_ptr;
5606	if (iph != NULL)
5607		ipf_lookup_deref(softc, IPLT_HASH, iph);
5608	return 0;
5609}
5610
5611
5612/* ------------------------------------------------------------------------ */
5613/* Function:    ipf_srcgrpmap                                               */
5614/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5615/* Parameters:  fin(I)    - pointer to packet information                   */
5616/*              passp(IO) - pointer to current/new filter decision (unused) */
5617/*                                                                          */
5618/* Look for a rule group head in a hash table, using the source address as  */
5619/* the key, and descend into that group and continue matching rules against */
5620/* the packet.                                                              */
5621/* ------------------------------------------------------------------------ */
5622frentry_t *
5623ipf_srcgrpmap(fin, passp)
5624	fr_info_t *fin;
5625	u_32_t *passp;
5626{
5627	frgroup_t *fg;
5628	void *rval;
5629
5630	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5631				 &fin->fin_src);
5632	if (rval == NULL)
5633		return NULL;
5634
5635	fg = rval;
5636	fin->fin_fr = fg->fg_start;
5637	(void) ipf_scanlist(fin, *passp);
5638	return fin->fin_fr;
5639}
5640
5641
5642/* ------------------------------------------------------------------------ */
5643/* Function:    ipf_dstgrpmap                                               */
5644/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5645/* Parameters:  fin(I)    - pointer to packet information                   */
5646/*              passp(IO) - pointer to current/new filter decision (unused) */
5647/*                                                                          */
5648/* Look for a rule group head in a hash table, using the destination        */
5649/* address as the key, and descend into that group and continue matching    */
5650/* rules against  the packet.                                               */
5651/* ------------------------------------------------------------------------ */
5652frentry_t *
5653ipf_dstgrpmap(fin, passp)
5654	fr_info_t *fin;
5655	u_32_t *passp;
5656{
5657	frgroup_t *fg;
5658	void *rval;
5659
5660	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5661				 &fin->fin_dst);
5662	if (rval == NULL)
5663		return NULL;
5664
5665	fg = rval;
5666	fin->fin_fr = fg->fg_start;
5667	(void) ipf_scanlist(fin, *passp);
5668	return fin->fin_fr;
5669}
5670
5671/*
5672 * Queue functions
5673 * ===============
5674 * These functions manage objects on queues for efficient timeouts.  There
5675 * are a number of system defined queues as well as user defined timeouts.
5676 * It is expected that a lock is held in the domain in which the queue
5677 * belongs (i.e. either state or NAT) when calling any of these functions
5678 * that prevents ipf_freetimeoutqueue() from being called at the same time
5679 * as any other.
5680 */
5681
5682
5683/* ------------------------------------------------------------------------ */
5684/* Function:    ipf_addtimeoutqueue                                         */
5685/* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5686/*                               timeout queue with given interval.         */
5687/* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5688/*                           of interface queues.                           */
5689/*              seconds(I) - timeout value in seconds for this queue.       */
5690/*                                                                          */
5691/* This routine first looks for a timeout queue that matches the interval   */
5692/* being requested.  If it finds one, increments the reference counter and  */
5693/* returns a pointer to it.  If none are found, it allocates a new one and  */
5694/* inserts it at the top of the list.                                       */
5695/*                                                                          */
5696/* Locking.                                                                 */
5697/* It is assumed that the caller of this function has an appropriate lock   */
5698/* held (exclusively) in the domain that encompases 'parent'.               */
5699/* ------------------------------------------------------------------------ */
5700ipftq_t *
5701ipf_addtimeoutqueue(softc, parent, seconds)
5702	ipf_main_softc_t *softc;
5703	ipftq_t **parent;
5704	u_int seconds;
5705{
5706	ipftq_t *ifq;
5707	u_int period;
5708
5709	period = seconds * IPF_HZ_DIVIDE;
5710
5711	MUTEX_ENTER(&softc->ipf_timeoutlock);
5712	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5713		if (ifq->ifq_ttl == period) {
5714			/*
5715			 * Reset the delete flag, if set, so the structure
5716			 * gets reused rather than freed and reallocated.
5717			 */
5718			MUTEX_ENTER(&ifq->ifq_lock);
5719			ifq->ifq_flags &= ~IFQF_DELETE;
5720			ifq->ifq_ref++;
5721			MUTEX_EXIT(&ifq->ifq_lock);
5722			MUTEX_EXIT(&softc->ipf_timeoutlock);
5723
5724			return ifq;
5725		}
5726	}
5727
5728	KMALLOC(ifq, ipftq_t *);
5729	if (ifq != NULL) {
5730		MUTEX_NUKE(&ifq->ifq_lock);
5731		IPFTQ_INIT(ifq, period, "ipftq mutex");
5732		ifq->ifq_next = *parent;
5733		ifq->ifq_pnext = parent;
5734		ifq->ifq_flags = IFQF_USER;
5735		ifq->ifq_ref++;
5736		*parent = ifq;
5737		softc->ipf_userifqs++;
5738	}
5739	MUTEX_EXIT(&softc->ipf_timeoutlock);
5740	return ifq;
5741}
5742
5743
5744/* ------------------------------------------------------------------------ */
5745/* Function:    ipf_deletetimeoutqueue                                      */
5746/* Returns:     int    - new reference count value of the timeout queue     */
5747/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5748/* Locks:       ifq->ifq_lock                                               */
5749/*                                                                          */
5750/* This routine must be called when we're discarding a pointer to a timeout */
5751/* queue object, taking care of the reference counter.                      */
5752/*                                                                          */
5753/* Now that this just sets a DELETE flag, it requires the expire code to    */
5754/* check the list of user defined timeout queues and call the free function */
5755/* below (currently commented out) to stop memory leaking.  It is done this */
5756/* way because the locking may not be sufficient to safely do a free when   */
5757/* this function is called.                                                 */
5758/* ------------------------------------------------------------------------ */
5759int
5760ipf_deletetimeoutqueue(ifq)
5761	ipftq_t *ifq;
5762{
5763
5764	ifq->ifq_ref--;
5765	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5766		ifq->ifq_flags |= IFQF_DELETE;
5767	}
5768
5769	return ifq->ifq_ref;
5770}
5771
5772
5773/* ------------------------------------------------------------------------ */
5774/* Function:    ipf_freetimeoutqueue                                        */
5775/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5776/* Returns:     Nil                                                         */
5777/*                                                                          */
5778/* Locking:                                                                 */
5779/* It is assumed that the caller of this function has an appropriate lock   */
5780/* held (exclusively) in the domain that encompases the callers "domain".   */
5781/* The ifq_lock for this structure should not be held.                      */
5782/*                                                                          */
5783/* Remove a user defined timeout queue from the list of queues it is in and */
5784/* tidy up after this is done.                                              */
5785/* ------------------------------------------------------------------------ */
5786void
5787ipf_freetimeoutqueue(softc, ifq)
5788	ipf_main_softc_t *softc;
5789	ipftq_t *ifq;
5790{
5791
5792	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5793	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5794		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5795		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5796		       ifq->ifq_ref);
5797		return;
5798	}
5799
5800	/*
5801	 * Remove from its position in the list.
5802	 */
5803	*ifq->ifq_pnext = ifq->ifq_next;
5804	if (ifq->ifq_next != NULL)
5805		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5806	ifq->ifq_next = NULL;
5807	ifq->ifq_pnext = NULL;
5808
5809	MUTEX_DESTROY(&ifq->ifq_lock);
5810	ATOMIC_DEC(softc->ipf_userifqs);
5811	KFREE(ifq);
5812}
5813
5814
5815/* ------------------------------------------------------------------------ */
5816/* Function:    ipf_deletequeueentry                                        */
5817/* Returns:     Nil                                                         */
5818/* Parameters:  tqe(I) - timeout queue entry to delete                      */
5819/*                                                                          */
5820/* Remove a tail queue entry from its queue and make it an orphan.          */
5821/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5822/* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5823/* the correct lock(s) may not be held that would make it safe to do so.    */
5824/* ------------------------------------------------------------------------ */
5825void
5826ipf_deletequeueentry(tqe)
5827	ipftqent_t *tqe;
5828{
5829	ipftq_t *ifq;
5830
5831	ifq = tqe->tqe_ifq;
5832
5833	MUTEX_ENTER(&ifq->ifq_lock);
5834
5835	if (tqe->tqe_pnext != NULL) {
5836		*tqe->tqe_pnext = tqe->tqe_next;
5837		if (tqe->tqe_next != NULL)
5838			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5839		else    /* we must be the tail anyway */
5840			ifq->ifq_tail = tqe->tqe_pnext;
5841
5842		tqe->tqe_pnext = NULL;
5843		tqe->tqe_ifq = NULL;
5844	}
5845
5846	(void) ipf_deletetimeoutqueue(ifq);
5847	ASSERT(ifq->ifq_ref > 0);
5848
5849	MUTEX_EXIT(&ifq->ifq_lock);
5850}
5851
5852
5853/* ------------------------------------------------------------------------ */
5854/* Function:    ipf_queuefront                                              */
5855/* Returns:     Nil                                                         */
5856/* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5857/*                                                                          */
5858/* Move a queue entry to the front of the queue, if it isn't already there. */
5859/* ------------------------------------------------------------------------ */
5860void
5861ipf_queuefront(tqe)
5862	ipftqent_t *tqe;
5863{
5864	ipftq_t *ifq;
5865
5866	ifq = tqe->tqe_ifq;
5867	if (ifq == NULL)
5868		return;
5869
5870	MUTEX_ENTER(&ifq->ifq_lock);
5871	if (ifq->ifq_head != tqe) {
5872		*tqe->tqe_pnext = tqe->tqe_next;
5873		if (tqe->tqe_next)
5874			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5875		else
5876			ifq->ifq_tail = tqe->tqe_pnext;
5877
5878		tqe->tqe_next = ifq->ifq_head;
5879		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5880		ifq->ifq_head = tqe;
5881		tqe->tqe_pnext = &ifq->ifq_head;
5882	}
5883	MUTEX_EXIT(&ifq->ifq_lock);
5884}
5885
5886
5887/* ------------------------------------------------------------------------ */
5888/* Function:    ipf_queueback                                               */
5889/* Returns:     Nil                                                         */
5890/* Parameters:  ticks(I) - ipf tick time to use with this call              */
5891/*              tqe(I)   - pointer to timeout queue entry                   */
5892/*                                                                          */
5893/* Move a queue entry to the back of the queue, if it isn't already there.  */
5894/* We use use ticks to calculate the expiration and mark for when we last   */
5895/* touched the structure.                                                   */
5896/* ------------------------------------------------------------------------ */
5897void
5898ipf_queueback(ticks, tqe)
5899	u_long ticks;
5900	ipftqent_t *tqe;
5901{
5902	ipftq_t *ifq;
5903
5904	ifq = tqe->tqe_ifq;
5905	if (ifq == NULL)
5906		return;
5907	tqe->tqe_die = ticks + ifq->ifq_ttl;
5908	tqe->tqe_touched = ticks;
5909
5910	MUTEX_ENTER(&ifq->ifq_lock);
5911	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5912		/*
5913		 * Remove from list
5914		 */
5915		*tqe->tqe_pnext = tqe->tqe_next;
5916		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5917
5918		/*
5919		 * Make it the last entry.
5920		 */
5921		tqe->tqe_next = NULL;
5922		tqe->tqe_pnext = ifq->ifq_tail;
5923		*ifq->ifq_tail = tqe;
5924		ifq->ifq_tail = &tqe->tqe_next;
5925	}
5926	MUTEX_EXIT(&ifq->ifq_lock);
5927}
5928
5929
5930/* ------------------------------------------------------------------------ */
5931/* Function:    ipf_queueappend                                             */
5932/* Returns:     Nil                                                         */
5933/* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5934/*              tqe(I)    - pointer to timeout queue entry                  */
5935/*              ifq(I)    - pointer to timeout queue                        */
5936/*              parent(I) - owing object pointer                            */
5937/*                                                                          */
5938/* Add a new item to this queue and put it on the very end.                 */
5939/* We use use ticks to calculate the expiration and mark for when we last   */
5940/* touched the structure.                                                   */
5941/* ------------------------------------------------------------------------ */
5942void
5943ipf_queueappend(ticks, tqe, ifq, parent)
5944	u_long ticks;
5945	ipftqent_t *tqe;
5946	ipftq_t *ifq;
5947	void *parent;
5948{
5949
5950	MUTEX_ENTER(&ifq->ifq_lock);
5951	tqe->tqe_parent = parent;
5952	tqe->tqe_pnext = ifq->ifq_tail;
5953	*ifq->ifq_tail = tqe;
5954	ifq->ifq_tail = &tqe->tqe_next;
5955	tqe->tqe_next = NULL;
5956	tqe->tqe_ifq = ifq;
5957	tqe->tqe_die = ticks + ifq->ifq_ttl;
5958	tqe->tqe_touched = ticks;
5959	ifq->ifq_ref++;
5960	MUTEX_EXIT(&ifq->ifq_lock);
5961}
5962
5963
5964/* ------------------------------------------------------------------------ */
5965/* Function:    ipf_movequeue                                               */
5966/* Returns:     Nil                                                         */
5967/* Parameters:  tq(I)   - pointer to timeout queue information              */
5968/*              oifp(I) - old timeout queue entry was on                    */
5969/*              nifp(I) - new timeout queue to put entry on                 */
5970/*                                                                          */
5971/* Move a queue entry from one timeout queue to another timeout queue.      */
5972/* If it notices that the current entry is already last and does not need   */
5973/* to move queue, the return.                                               */
5974/* ------------------------------------------------------------------------ */
5975void
5976ipf_movequeue(ticks, tqe, oifq, nifq)
5977	u_long ticks;
5978	ipftqent_t *tqe;
5979	ipftq_t *oifq, *nifq;
5980{
5981
5982	/*
5983	 * If the queue hasn't changed and we last touched this entry at the
5984	 * same ipf time, then we're not going to achieve anything by either
5985	 * changing the ttl or moving it on the queue.
5986	 */
5987	if (oifq == nifq && tqe->tqe_touched == ticks)
5988		return;
5989
5990	/*
5991	 * For any of this to be outside the lock, there is a risk that two
5992	 * packets entering simultaneously, with one changing to a different
5993	 * queue and one not, could end up with things in a bizarre state.
5994	 */
5995	MUTEX_ENTER(&oifq->ifq_lock);
5996
5997	tqe->tqe_touched = ticks;
5998	tqe->tqe_die = ticks + nifq->ifq_ttl;
5999	/*
6000	 * Is the operation here going to be a no-op ?
6001	 */
6002	if (oifq == nifq) {
6003		if ((tqe->tqe_next == NULL) ||
6004		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6005			MUTEX_EXIT(&oifq->ifq_lock);
6006			return;
6007		}
6008	}
6009
6010	/*
6011	 * Remove from the old queue
6012	 */
6013	*tqe->tqe_pnext = tqe->tqe_next;
6014	if (tqe->tqe_next)
6015		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6016	else
6017		oifq->ifq_tail = tqe->tqe_pnext;
6018	tqe->tqe_next = NULL;
6019
6020	/*
6021	 * If we're moving from one queue to another, release the
6022	 * lock on the old queue and get a lock on the new queue.
6023	 * For user defined queues, if we're moving off it, call
6024	 * delete in case it can now be freed.
6025	 */
6026	if (oifq != nifq) {
6027		tqe->tqe_ifq = NULL;
6028
6029		(void) ipf_deletetimeoutqueue(oifq);
6030
6031		MUTEX_EXIT(&oifq->ifq_lock);
6032
6033		MUTEX_ENTER(&nifq->ifq_lock);
6034
6035		tqe->tqe_ifq = nifq;
6036		nifq->ifq_ref++;
6037	}
6038
6039	/*
6040	 * Add to the bottom of the new queue
6041	 */
6042	tqe->tqe_pnext = nifq->ifq_tail;
6043	*nifq->ifq_tail = tqe;
6044	nifq->ifq_tail = &tqe->tqe_next;
6045	MUTEX_EXIT(&nifq->ifq_lock);
6046}
6047
6048
6049/* ------------------------------------------------------------------------ */
6050/* Function:    ipf_updateipid                                              */
6051/* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6052/* Parameters:  fin(I) - pointer to packet information                      */
6053/*                                                                          */
6054/* When we are doing NAT, change the IP of every packet to represent a      */
6055/* single sequence of packets coming from the host, hiding any host         */
6056/* specific sequencing that might otherwise be revealed.  If the packet is  */
6057/* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6058/* the fragment cache for non-leading fragments.  If a non-leading fragment */
6059/* has no match in the cache, return an error.                              */
6060/* ------------------------------------------------------------------------ */
6061static int
6062ipf_updateipid(fin)
6063	fr_info_t *fin;
6064{
6065	u_short id, ido, sums;
6066	u_32_t sumd, sum;
6067	ip_t *ip;
6068
6069	ip = fin->fin_ip;
6070	ido = ntohs(ip->ip_id);
6071	if (fin->fin_off != 0) {
6072		sum = ipf_frag_ipidknown(fin);
6073		if (sum == 0xffffffff)
6074			return -1;
6075		sum &= 0xffff;
6076		id = (u_short)sum;
6077		ip->ip_id = htons(id);
6078	} else {
6079		ip_fillid(ip);
6080		id = ntohs(ip->ip_id);
6081		if ((fin->fin_flx & FI_FRAG) != 0)
6082			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
6083	}
6084
6085	if (id == ido)
6086		return 0;
6087	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
6088	sum = (~ntohs(ip->ip_sum)) & 0xffff;
6089	sum += sumd;
6090	sum = (sum >> 16) + (sum & 0xffff);
6091	sum = (sum >> 16) + (sum & 0xffff);
6092	sums = ~(u_short)sum;
6093	ip->ip_sum = htons(sums);
6094	return 0;
6095}
6096
6097
6098#ifdef	NEED_FRGETIFNAME
6099/* ------------------------------------------------------------------------ */
6100/* Function:    ipf_getifname                                               */
6101/* Returns:     char *    - pointer to interface name                       */
6102/* Parameters:  ifp(I)    - pointer to network interface                    */
6103/*              buffer(O) - pointer to where to store interface name        */
6104/*                                                                          */
6105/* Constructs an interface name in the buffer passed.  The buffer passed is */
6106/* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6107/* as a NULL pointer then return a pointer to a static array.               */
6108/* ------------------------------------------------------------------------ */
6109char *
6110ipf_getifname(ifp, buffer)
6111	struct ifnet *ifp;
6112	char *buffer;
6113{
6114	static char namebuf[LIFNAMSIZ];
6115# if defined(MENTAT) || defined(__FreeBSD__)
6116	int unit, space;
6117	char temp[20];
6118	char *s;
6119# endif
6120
6121	if (buffer == NULL)
6122		buffer = namebuf;
6123	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6124	buffer[LIFNAMSIZ - 1] = '\0';
6125# if defined(MENTAT) || defined(__FreeBSD__)
6126	for (s = buffer; *s; s++)
6127		;
6128	unit = ifp->if_unit;
6129	space = LIFNAMSIZ - (s - buffer);
6130	if ((space > 0) && (unit >= 0)) {
6131#  if defined(SNPRINTF) && defined(_KERNEL)
6132		SNPRINTF(temp, sizeof(temp), "%d", unit);
6133#  else
6134		(void) sprintf(temp, "%d", unit);
6135#  endif
6136		(void) strncpy(s, temp, space);
6137	}
6138# endif
6139	return buffer;
6140}
6141#endif
6142
6143
6144/* ------------------------------------------------------------------------ */
6145/* Function:    ipf_ioctlswitch                                             */
6146/* Returns:     int     - -1 continue processing, else ioctl return value   */
6147/* Parameters:  unit(I) - device unit opened                                */
6148/*              data(I) - pointer to ioctl data                             */
6149/*              cmd(I)  - ioctl command                                     */
6150/*              mode(I) - mode value                                        */
6151/*              uid(I)  - uid making the ioctl call                         */
6152/*              ctx(I)  - pointer to context data                           */
6153/*                                                                          */
6154/* Based on the value of unit, call the appropriate ioctl handler or return */
6155/* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6156/* for the device in order to execute the ioctl.  A special case is made    */
6157/* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6158/* The context data pointer is passed through as this is used as the key    */
6159/* for locating a matching token for continued access for walking lists,    */
6160/* etc.                                                                     */
6161/* ------------------------------------------------------------------------ */
6162int
6163ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6164	ipf_main_softc_t *softc;
6165	int unit, mode, uid;
6166	ioctlcmd_t cmd;
6167	void *data, *ctx;
6168{
6169	int error = 0;
6170
6171	switch (cmd)
6172	{
6173	case SIOCIPFINTERROR :
6174		error = BCOPYOUT(&softc->ipf_interror, data,
6175				 sizeof(softc->ipf_interror));
6176		if (error != 0) {
6177			IPFERROR(40);
6178			error = EFAULT;
6179		}
6180		return error;
6181	default :
6182		break;
6183	}
6184
6185	switch (unit)
6186	{
6187	case IPL_LOGIPF :
6188		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6189		break;
6190	case IPL_LOGNAT :
6191		if (softc->ipf_running > 0) {
6192			error = ipf_nat_ioctl(softc, data, cmd, mode,
6193					      uid, ctx);
6194		} else {
6195			IPFERROR(42);
6196			error = EIO;
6197		}
6198		break;
6199	case IPL_LOGSTATE :
6200		if (softc->ipf_running > 0) {
6201			error = ipf_state_ioctl(softc, data, cmd, mode,
6202						uid, ctx);
6203		} else {
6204			IPFERROR(43);
6205			error = EIO;
6206		}
6207		break;
6208	case IPL_LOGAUTH :
6209		if (softc->ipf_running > 0) {
6210			error = ipf_auth_ioctl(softc, data, cmd, mode,
6211					       uid, ctx);
6212		} else {
6213			IPFERROR(44);
6214			error = EIO;
6215		}
6216		break;
6217	case IPL_LOGSYNC :
6218		if (softc->ipf_running > 0) {
6219			error = ipf_sync_ioctl(softc, data, cmd, mode,
6220					       uid, ctx);
6221		} else {
6222			error = EIO;
6223			IPFERROR(45);
6224		}
6225		break;
6226	case IPL_LOGSCAN :
6227#ifdef IPFILTER_SCAN
6228		if (softc->ipf_running > 0)
6229			error = ipf_scan_ioctl(softc, data, cmd, mode,
6230					       uid, ctx);
6231		else
6232#endif
6233		{
6234			error = EIO;
6235			IPFERROR(46);
6236		}
6237		break;
6238	case IPL_LOGLOOKUP :
6239		if (softc->ipf_running > 0) {
6240			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6241						 uid, ctx);
6242		} else {
6243			error = EIO;
6244			IPFERROR(47);
6245		}
6246		break;
6247	default :
6248		IPFERROR(48);
6249		error = EIO;
6250		break;
6251	}
6252
6253	return error;
6254}
6255
6256
6257/*
6258 * This array defines the expected size of objects coming into the kernel
6259 * for the various recognised object types. The first column is flags (see
6260 * below), 2nd column is current size, 3rd column is the version number of
6261 * when the current size became current.
6262 * Flags:
6263 * 1 = minimum size, not absolute size
6264 */
6265static const int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6266	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6267	{ 1,	sizeof(struct friostat),	5010000 },
6268	{ 0,	sizeof(struct fr_info),		5010000 },
6269	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6270	{ 0,	sizeof(struct ipfrstat),	5010000 },
6271	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6272	{ 0,	sizeof(struct natstat),		5010000 },
6273	{ 0,	sizeof(struct ipstate_save),	5010000 },
6274	{ 1,	sizeof(struct nat_save),	5010000 },
6275	{ 0,	sizeof(struct natlookup),	5010000 },
6276	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6277	{ 0,	sizeof(struct ips_stat),	5010000 },
6278	{ 0,	sizeof(struct frauth),		5010000 },
6279	{ 0,	sizeof(struct ipftune),		4010100 },
6280	{ 0,	sizeof(struct nat),		5010000 },
6281	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6282	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6283	{ 0,	sizeof(struct ipftable),	4011400 },
6284	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6285	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6286	{ 1,	0,				0	}, /* IPFEXPR */
6287	{ 0,	0,				0	}, /* PROXYCTL */
6288	{ 0,	sizeof (struct fripf),		5010000	}
6289};
6290
6291
6292/* ------------------------------------------------------------------------ */
6293/* Function:    ipf_inobj                                                   */
6294/* Returns:     int     - 0 = success, else failure                         */
6295/* Parameters:  softc(I) - soft context pointerto work with                 */
6296/*              data(I)  - pointer to ioctl data                            */
6297/*              objp(O)  - where to store ipfobj structure                  */
6298/*              ptr(I)   - pointer to data to copy out                      */
6299/*              type(I)  - type of structure being moved                    */
6300/*                                                                          */
6301/* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6302/* add things to check for version numbers, sizes, etc, to make it backward */
6303/* compatible at the ABI for user land.                                     */
6304/* If objp is not NULL then we assume that the caller wants to see what is  */
6305/* in the ipfobj_t structure being copied in. As an example, this can tell  */
6306/* the caller what version of ipfilter the ioctl program was written to.    */
6307/* ------------------------------------------------------------------------ */
6308int
6309ipf_inobj(softc, data, objp, ptr, type)
6310	ipf_main_softc_t *softc;
6311	void *data;
6312	ipfobj_t *objp;
6313	void *ptr;
6314	int type;
6315{
6316	ipfobj_t obj;
6317	int error;
6318	int size;
6319
6320	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6321		IPFERROR(49);
6322		return EINVAL;
6323	}
6324
6325	if (objp == NULL)
6326		objp = &obj;
6327	error = BCOPYIN(data, objp, sizeof(*objp));
6328	if (error != 0) {
6329		IPFERROR(124);
6330		return EFAULT;
6331	}
6332
6333	if (objp->ipfo_type != type) {
6334		IPFERROR(50);
6335		return EINVAL;
6336	}
6337
6338	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6339		if ((ipf_objbytes[type][0] & 1) != 0) {
6340			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6341				IPFERROR(51);
6342				return EINVAL;
6343			}
6344			size =  ipf_objbytes[type][1];
6345		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6346			size =  objp->ipfo_size;
6347		} else {
6348			IPFERROR(52);
6349			return EINVAL;
6350		}
6351		error = COPYIN(objp->ipfo_ptr, ptr, size);
6352		if (error != 0) {
6353			IPFERROR(55);
6354			error = EFAULT;
6355		}
6356	} else {
6357#ifdef  IPFILTER_COMPAT
6358		error = ipf_in_compat(softc, objp, ptr, 0);
6359#else
6360		IPFERROR(54);
6361		error = EINVAL;
6362#endif
6363	}
6364	return error;
6365}
6366
6367
6368/* ------------------------------------------------------------------------ */
6369/* Function:    ipf_inobjsz                                                 */
6370/* Returns:     int     - 0 = success, else failure                         */
6371/* Parameters:  softc(I) - soft context pointerto work with                 */
6372/*              data(I)  - pointer to ioctl data                            */
6373/*              ptr(I)   - pointer to store real data in                    */
6374/*              type(I)  - type of structure being moved                    */
6375/*              sz(I)    - size of data to copy                             */
6376/*                                                                          */
6377/* As per ipf_inobj, except the size of the object to copy in is passed in  */
6378/* but it must not be smaller than the size defined for the type and the    */
6379/* type must allow for varied sized objects.  The extra requirement here is */
6380/* that sz must match the size of the object being passed in - this is not  */
6381/* not possible nor required in ipf_inobj().                                */
6382/* ------------------------------------------------------------------------ */
6383int
6384ipf_inobjsz(softc, data, ptr, type, sz)
6385	ipf_main_softc_t *softc;
6386	void *data;
6387	void *ptr;
6388	int type, sz;
6389{
6390	ipfobj_t obj;
6391	int error;
6392
6393	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6394		IPFERROR(56);
6395		return EINVAL;
6396	}
6397
6398	error = BCOPYIN(data, &obj, sizeof(obj));
6399	if (error != 0) {
6400		IPFERROR(125);
6401		return EFAULT;
6402	}
6403
6404	if (obj.ipfo_type != type) {
6405		IPFERROR(58);
6406		return EINVAL;
6407	}
6408
6409	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6410		if (((ipf_objbytes[type][0] & 1) == 0) ||
6411		    (sz < ipf_objbytes[type][1])) {
6412			IPFERROR(57);
6413			return EINVAL;
6414		}
6415		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6416		if (error != 0) {
6417			IPFERROR(61);
6418			error = EFAULT;
6419		}
6420	} else {
6421#ifdef	IPFILTER_COMPAT
6422		error = ipf_in_compat(softc, &obj, ptr, sz);
6423#else
6424		IPFERROR(60);
6425		error = EINVAL;
6426#endif
6427	}
6428	return error;
6429}
6430
6431
6432/* ------------------------------------------------------------------------ */
6433/* Function:    ipf_outobjsz                                                */
6434/* Returns:     int     - 0 = success, else failure                         */
6435/* Parameters:  data(I) - pointer to ioctl data                             */
6436/*              ptr(I)  - pointer to store real data in                     */
6437/*              type(I) - type of structure being moved                     */
6438/*              sz(I)   - size of data to copy                              */
6439/*                                                                          */
6440/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6441/* but it must not be smaller than the size defined for the type and the    */
6442/* type must allow for varied sized objects.  The extra requirement here is */
6443/* that sz must match the size of the object being passed in - this is not  */
6444/* not possible nor required in ipf_outobj().                               */
6445/* ------------------------------------------------------------------------ */
6446int
6447ipf_outobjsz(softc, data, ptr, type, sz)
6448	ipf_main_softc_t *softc;
6449	void *data;
6450	void *ptr;
6451	int type, sz;
6452{
6453	ipfobj_t obj;
6454	int error;
6455
6456	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6457		IPFERROR(62);
6458		return EINVAL;
6459	}
6460
6461	error = BCOPYIN(data, &obj, sizeof(obj));
6462	if (error != 0) {
6463		IPFERROR(127);
6464		return EFAULT;
6465	}
6466
6467	if (obj.ipfo_type != type) {
6468		IPFERROR(63);
6469		return EINVAL;
6470	}
6471
6472	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6473		if (((ipf_objbytes[type][0] & 1) == 0) ||
6474		    (sz < ipf_objbytes[type][1])) {
6475			IPFERROR(146);
6476			return EINVAL;
6477		}
6478		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6479		if (error != 0) {
6480			IPFERROR(66);
6481			error = EFAULT;
6482		}
6483	} else {
6484#ifdef	IPFILTER_COMPAT
6485		error = ipf_out_compat(softc, &obj, ptr);
6486#else
6487		IPFERROR(65);
6488		error = EINVAL;
6489#endif
6490	}
6491	return error;
6492}
6493
6494
6495/* ------------------------------------------------------------------------ */
6496/* Function:    ipf_outobj                                                  */
6497/* Returns:     int     - 0 = success, else failure                         */
6498/* Parameters:  data(I) - pointer to ioctl data                             */
6499/*              ptr(I)  - pointer to store real data in                     */
6500/*              type(I) - type of structure being moved                     */
6501/*                                                                          */
6502/* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6503/* future, we add things to check for version numbers, sizes, etc, to make  */
6504/* it backward  compatible at the ABI for user land.                        */
6505/* ------------------------------------------------------------------------ */
6506int
6507ipf_outobj(softc, data, ptr, type)
6508	ipf_main_softc_t *softc;
6509	void *data;
6510	void *ptr;
6511	int type;
6512{
6513	ipfobj_t obj;
6514	int error;
6515
6516	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6517		IPFERROR(67);
6518		return EINVAL;
6519	}
6520
6521	error = BCOPYIN(data, &obj, sizeof(obj));
6522	if (error != 0) {
6523		IPFERROR(126);
6524		return EFAULT;
6525	}
6526
6527	if (obj.ipfo_type != type) {
6528		IPFERROR(68);
6529		return EINVAL;
6530	}
6531
6532	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6533		if ((ipf_objbytes[type][0] & 1) != 0) {
6534			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6535				IPFERROR(69);
6536				return EINVAL;
6537			}
6538		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6539			IPFERROR(70);
6540			return EINVAL;
6541		}
6542
6543		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6544		if (error != 0) {
6545			IPFERROR(73);
6546			error = EFAULT;
6547		}
6548	} else {
6549#ifdef	IPFILTER_COMPAT
6550		error = ipf_out_compat(softc, &obj, ptr);
6551#else
6552		IPFERROR(72);
6553		error = EINVAL;
6554#endif
6555	}
6556	return error;
6557}
6558
6559
6560/* ------------------------------------------------------------------------ */
6561/* Function:    ipf_outobjk                                                 */
6562/* Returns:     int     - 0 = success, else failure                         */
6563/* Parameters:  obj(I)  - pointer to data description structure             */
6564/*              ptr(I)  - pointer to kernel data to copy out                */
6565/*                                                                          */
6566/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6567/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6568/* already populated with information and now we just need to use it.       */
6569/* There is no need for this function to have a "type" parameter as there   */
6570/* is no point in validating information that comes from the kernel with    */
6571/* itself.                                                                  */
6572/* ------------------------------------------------------------------------ */
6573int
6574ipf_outobjk(softc, obj, ptr)
6575	ipf_main_softc_t *softc;
6576	ipfobj_t *obj;
6577	void *ptr;
6578{
6579	int type = obj->ipfo_type;
6580	int error;
6581
6582	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6583		IPFERROR(147);
6584		return EINVAL;
6585	}
6586
6587	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6588		if ((ipf_objbytes[type][0] & 1) != 0) {
6589			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6590				IPFERROR(148);
6591				return EINVAL;
6592			}
6593
6594		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6595			IPFERROR(149);
6596			return EINVAL;
6597		}
6598
6599		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6600		if (error != 0) {
6601			IPFERROR(150);
6602			error = EFAULT;
6603		}
6604	} else {
6605#ifdef  IPFILTER_COMPAT
6606		error = ipf_out_compat(softc, obj, ptr);
6607#else
6608		IPFERROR(151);
6609		error = EINVAL;
6610#endif
6611	}
6612	return error;
6613}
6614
6615
6616/* ------------------------------------------------------------------------ */
6617/* Function:    ipf_checkl4sum                                              */
6618/* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6619/* Parameters:  fin(I) - pointer to packet information                      */
6620/*                                                                          */
6621/* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6622/* not possible, return without indicating a failure or success but in a    */
6623/* way that is ditinguishable. This function should only be called by the   */
6624/* ipf_checkv6sum() for each platform.                                      */
6625/* ------------------------------------------------------------------------ */
6626INLINE int
6627ipf_checkl4sum(fin)
6628	fr_info_t *fin;
6629{
6630	u_short sum, hdrsum, *csump;
6631	udphdr_t *udp;
6632	int dosum;
6633
6634	/*
6635	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6636	 * isn't already considered "bad", then validate the checksum.  If
6637	 * this check fails then considered the packet to be "bad".
6638	 */
6639	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6640		return 1;
6641
6642	DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6643	if (fin->fin_out == 1) {
6644		fin->fin_cksum = FI_CK_SUMOK;
6645		return 0;
6646	}
6647
6648	csump = NULL;
6649	hdrsum = 0;
6650	dosum = 0;
6651	sum = 0;
6652
6653	switch (fin->fin_p)
6654	{
6655	case IPPROTO_TCP :
6656		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6657		dosum = 1;
6658		break;
6659
6660	case IPPROTO_UDP :
6661		udp = fin->fin_dp;
6662		if (udp->uh_sum != 0) {
6663			csump = &udp->uh_sum;
6664			dosum = 1;
6665		}
6666		break;
6667
6668#ifdef USE_INET6
6669	case IPPROTO_ICMPV6 :
6670		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6671		dosum = 1;
6672		break;
6673#endif
6674
6675	case IPPROTO_ICMP :
6676		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6677		dosum = 1;
6678		break;
6679
6680	default :
6681		return 1;
6682		/*NOTREACHED*/
6683	}
6684
6685	if (csump != NULL)
6686		hdrsum = *csump;
6687
6688	if (dosum) {
6689		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6690	}
6691#if !defined(_KERNEL)
6692	if (sum == hdrsum) {
6693		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6694	} else {
6695		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6696	}
6697#endif
6698	DT2(l4sums, u_short, hdrsum, u_short, sum);
6699#ifdef USE_INET6
6700	if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6701#else
6702	if (hdrsum == sum) {
6703#endif
6704		fin->fin_cksum = FI_CK_SUMOK;
6705		return 0;
6706	}
6707	fin->fin_cksum = FI_CK_BAD;
6708	return -1;
6709}
6710
6711
6712/* ------------------------------------------------------------------------ */
6713/* Function:    ipf_ifpfillv4addr                                           */
6714/* Returns:     int     - 0 = address update, -1 = address not updated      */
6715/* Parameters:  atype(I)   - type of network address update to perform      */
6716/*              sin(I)     - pointer to source of address information       */
6717/*              mask(I)    - pointer to source of netmask information       */
6718/*              inp(I)     - pointer to destination address store           */
6719/*              inpmask(I) - pointer to destination netmask store           */
6720/*                                                                          */
6721/* Given a type of network address update (atype) to perform, copy          */
6722/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6723/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6724/* which case the operation fails.  For all values of atype other than      */
6725/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6726/* value.                                                                   */
6727/* ------------------------------------------------------------------------ */
6728int
6729ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6730	int atype;
6731	struct sockaddr_in *sin, *mask;
6732	struct in_addr *inp, *inpmask;
6733{
6734	if (inpmask != NULL && atype != FRI_NETMASKED)
6735		inpmask->s_addr = 0xffffffff;
6736
6737	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6738		if (atype == FRI_NETMASKED) {
6739			if (inpmask == NULL)
6740				return -1;
6741			inpmask->s_addr = mask->sin_addr.s_addr;
6742		}
6743		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6744	} else {
6745		inp->s_addr = sin->sin_addr.s_addr;
6746	}
6747	return 0;
6748}
6749
6750
6751#ifdef	USE_INET6
6752/* ------------------------------------------------------------------------ */
6753/* Function:    ipf_ifpfillv6addr                                           */
6754/* Returns:     int     - 0 = address update, -1 = address not updated      */
6755/* Parameters:  atype(I)   - type of network address update to perform      */
6756/*              sin(I)     - pointer to source of address information       */
6757/*              mask(I)    - pointer to source of netmask information       */
6758/*              inp(I)     - pointer to destination address store           */
6759/*              inpmask(I) - pointer to destination netmask store           */
6760/*                                                                          */
6761/* Given a type of network address update (atype) to perform, copy          */
6762/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6763/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6764/* which case the operation fails.  For all values of atype other than      */
6765/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6766/* value.                                                                   */
6767/* ------------------------------------------------------------------------ */
6768int
6769ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6770	int atype;
6771	struct sockaddr_in6 *sin, *mask;
6772	i6addr_t *inp, *inpmask;
6773{
6774	i6addr_t *src, *and;
6775
6776	src = (i6addr_t *)&sin->sin6_addr;
6777	and = (i6addr_t *)&mask->sin6_addr;
6778
6779	if (inpmask != NULL && atype != FRI_NETMASKED) {
6780		inpmask->i6[0] = 0xffffffff;
6781		inpmask->i6[1] = 0xffffffff;
6782		inpmask->i6[2] = 0xffffffff;
6783		inpmask->i6[3] = 0xffffffff;
6784	}
6785
6786	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6787		if (atype == FRI_NETMASKED) {
6788			if (inpmask == NULL)
6789				return -1;
6790			inpmask->i6[0] = and->i6[0];
6791			inpmask->i6[1] = and->i6[1];
6792			inpmask->i6[2] = and->i6[2];
6793			inpmask->i6[3] = and->i6[3];
6794		}
6795
6796		inp->i6[0] = src->i6[0] & and->i6[0];
6797		inp->i6[1] = src->i6[1] & and->i6[1];
6798		inp->i6[2] = src->i6[2] & and->i6[2];
6799		inp->i6[3] = src->i6[3] & and->i6[3];
6800	} else {
6801		inp->i6[0] = src->i6[0];
6802		inp->i6[1] = src->i6[1];
6803		inp->i6[2] = src->i6[2];
6804		inp->i6[3] = src->i6[3];
6805	}
6806	return 0;
6807}
6808#endif
6809
6810
6811/* ------------------------------------------------------------------------ */
6812/* Function:    ipf_matchtag                                                */
6813/* Returns:     0 == mismatch, 1 == match.                                  */
6814/* Parameters:  tag1(I) - pointer to first tag to compare                   */
6815/*              tag2(I) - pointer to second tag to compare                  */
6816/*                                                                          */
6817/* Returns true (non-zero) or false(0) if the two tag structures can be     */
6818/* considered to be a match or not match, respectively.  The tag is 16      */
6819/* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6820/* compare the ints instead, for speed. tag1 is the master of the           */
6821/* comparison.  This function should only be called with both tag1 and tag2 */
6822/* as non-NULL pointers.                                                    */
6823/* ------------------------------------------------------------------------ */
6824int
6825ipf_matchtag(tag1, tag2)
6826	ipftag_t *tag1, *tag2;
6827{
6828	if (tag1 == tag2)
6829		return 1;
6830
6831	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6832		return 1;
6833
6834	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6835	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6836	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6837	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6838		return 1;
6839	return 0;
6840}
6841
6842
6843/* ------------------------------------------------------------------------ */
6844/* Function:    ipf_coalesce                                                */
6845/* Returns:     1 == success, -1 == failure, 0 == no change                 */
6846/* Parameters:  fin(I) - pointer to packet information                      */
6847/*                                                                          */
6848/* Attempt to get all of the packet data into a single, contiguous buffer.  */
6849/* If this call returns a failure then the buffers have also been freed.    */
6850/* ------------------------------------------------------------------------ */
6851int
6852ipf_coalesce(fin)
6853	fr_info_t *fin;
6854{
6855
6856	if ((fin->fin_flx & FI_COALESCE) != 0)
6857		return 1;
6858
6859	/*
6860	 * If the mbuf pointers indicate that there is no mbuf to work with,
6861	 * return but do not indicate success or failure.
6862	 */
6863	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6864		return 0;
6865
6866#if defined(_KERNEL)
6867	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6868		ipf_main_softc_t *softc = fin->fin_main_soft;
6869
6870		DT1(frb_coalesce, fr_info_t *, fin);
6871		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6872# ifdef MENTAT
6873		FREE_MB_T(*fin->fin_mp);
6874# endif
6875		fin->fin_reason = FRB_COALESCE;
6876		*fin->fin_mp = NULL;
6877		fin->fin_m = NULL;
6878		return -1;
6879	}
6880#else
6881	fin = fin;	/* LINT */
6882#endif
6883	return 1;
6884}
6885
6886
6887/*
6888 * The following table lists all of the tunable variables that can be
6889 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6890 * in the table below is as follows:
6891 *
6892 * pointer to value, name of value, minimum, maximum, size of the value's
6893 *     container, value attribute flags
6894 *
6895 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6896 * means the value can only be written to when IPFilter is loaded but disabled.
6897 * The obvious implication is if neither of these are set then the value can be
6898 * changed at any time without harm.
6899 */
6900
6901
6902/* ------------------------------------------------------------------------ */
6903/* Function:    ipf_tune_findbycookie                                       */
6904/* Returns:     NULL = search failed, else pointer to tune struct           */
6905/* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6906/*              next(O)   - pointer to place to store the cookie for the    */
6907/*                          "next" tuneable, if it is desired.              */
6908/*                                                                          */
6909/* This function is used to walk through all of the existing tunables with  */
6910/* successive calls.  It searches the known tunables for the one which has  */
6911/* a matching value for "cookie" - ie its address.  When returning a match, */
6912/* the next one to be found may be returned inside next.                    */
6913/* ------------------------------------------------------------------------ */
6914static ipftuneable_t *
6915ipf_tune_findbycookie(ptop, cookie, next)
6916	ipftuneable_t **ptop;
6917	void *cookie, **next;
6918{
6919	ipftuneable_t *ta, **tap;
6920
6921	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6922		if (ta == cookie) {
6923			if (next != NULL) {
6924				/*
6925				 * If the next entry in the array has a name
6926				 * present, then return a pointer to it for
6927				 * where to go next, else return a pointer to
6928				 * the dynaminc list as a key to search there
6929				 * next.  This facilitates a weak linking of
6930				 * the two "lists" together.
6931				 */
6932				if ((ta + 1)->ipft_name != NULL)
6933					*next = ta + 1;
6934				else
6935					*next = ptop;
6936			}
6937			return ta;
6938		}
6939
6940	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6941		if (tap == cookie) {
6942			if (next != NULL)
6943				*next = &ta->ipft_next;
6944			return ta;
6945		}
6946
6947	if (next != NULL)
6948		*next = NULL;
6949	return NULL;
6950}
6951
6952
6953/* ------------------------------------------------------------------------ */
6954/* Function:    ipf_tune_findbyname                                         */
6955/* Returns:     NULL = search failed, else pointer to tune struct           */
6956/* Parameters:  name(I) - name of the tuneable entry to find.               */
6957/*                                                                          */
6958/* Search the static array of tuneables and the list of dynamic tuneables   */
6959/* for an entry with a matching name.  If we can find one, return a pointer */
6960/* to the matching structure.                                               */
6961/* ------------------------------------------------------------------------ */
6962static ipftuneable_t *
6963ipf_tune_findbyname(top, name)
6964	ipftuneable_t *top;
6965	const char *name;
6966{
6967	ipftuneable_t *ta;
6968
6969	for (ta = top; ta != NULL; ta = ta->ipft_next)
6970		if (!strcmp(ta->ipft_name, name)) {
6971			return ta;
6972		}
6973
6974	return NULL;
6975}
6976
6977
6978/* ------------------------------------------------------------------------ */
6979/* Function:    ipf_tune_add_array                                          */
6980/* Returns:     int - 0 == success, else failure                            */
6981/* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6982/*                                                                          */
6983/* Appends tune structures from the array passed in (newtune) to the end of */
6984/* the current list of "dynamic" tuneable parameters.                       */
6985/* If any entry to be added is already present (by name) then the operation */
6986/* is aborted - entries that have been added are removed before returning.  */
6987/* An entry with no name (NULL) is used as the indication that the end of   */
6988/* the array has been reached.                                              */
6989/* ------------------------------------------------------------------------ */
6990int
6991ipf_tune_add_array(softc, newtune)
6992	ipf_main_softc_t *softc;
6993	ipftuneable_t *newtune;
6994{
6995	ipftuneable_t *nt, *dt;
6996	int error = 0;
6997
6998	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6999		error = ipf_tune_add(softc, nt);
7000		if (error != 0) {
7001			for (dt = newtune; dt != nt; dt++) {
7002				(void) ipf_tune_del(softc, dt);
7003			}
7004		}
7005	}
7006
7007	return error;
7008}
7009
7010
7011/* ------------------------------------------------------------------------ */
7012/* Function:    ipf_tune_array_link                                         */
7013/* Returns:     0 == success, -1 == failure                                 */
7014/* Parameters:  softc(I) - soft context pointerto work with                 */
7015/*              array(I) - pointer to an array of tuneables                 */
7016/*                                                                          */
7017/* Given an array of tunables (array), append them to the current list of   */
7018/* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7019/* the array for being appended to the list, initialise all of the next     */
7020/* pointers so we don't need to walk parts of it with ++ and others with    */
7021/* next. The array is expected to have an entry with a NULL name as the     */
7022/* terminator. Trying to add an array with no non-NULL names will return as */
7023/* a failure.                                                               */
7024/* ------------------------------------------------------------------------ */
7025int
7026ipf_tune_array_link(softc, array)
7027	ipf_main_softc_t *softc;
7028	ipftuneable_t *array;
7029{
7030	ipftuneable_t *t, **p;
7031
7032	t = array;
7033	if (t->ipft_name == NULL)
7034		return -1;
7035
7036	for (; t[1].ipft_name != NULL; t++)
7037		t[0].ipft_next = &t[1];
7038	t->ipft_next = NULL;
7039
7040	/*
7041	 * Since a pointer to the last entry isn't kept, we need to find it
7042	 * each time we want to add new variables to the list.
7043	 */
7044	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7045		if (t->ipft_name == NULL)
7046			break;
7047	*p = array;
7048
7049	return 0;
7050}
7051
7052
7053/* ------------------------------------------------------------------------ */
7054/* Function:    ipf_tune_array_unlink                                       */
7055/* Returns:     0 == success, -1 == failure                                 */
7056/* Parameters:  softc(I) - soft context pointerto work with                 */
7057/*              array(I) - pointer to an array of tuneables                 */
7058/*                                                                          */
7059/* ------------------------------------------------------------------------ */
7060int
7061ipf_tune_array_unlink(softc, array)
7062	ipf_main_softc_t *softc;
7063	ipftuneable_t *array;
7064{
7065	ipftuneable_t *t, **p;
7066
7067	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7068		if (t == array)
7069			break;
7070	if (t == NULL)
7071		return -1;
7072
7073	for (; t[1].ipft_name != NULL; t++)
7074		;
7075
7076	*p = t->ipft_next;
7077
7078	return 0;
7079}
7080
7081
7082/* ------------------------------------------------------------------------ */
7083/* Function:   ipf_tune_array_copy                                          */
7084/* Returns:    NULL = failure, else pointer to new array                    */
7085/* Parameters: base(I)     - pointer to structure base                      */
7086/*             size(I)     - size of the array at template                  */
7087/*             template(I) - original array to copy                         */
7088/*                                                                          */
7089/* Allocate memory for a new set of tuneable values and copy everything     */
7090/* from template into the new region of memory.  The new region is full of  */
7091/* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7092/*                                                                          */
7093/* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7094/* In the array template, ipftp_offset is the offset (in bytes) of the      */
7095/* location of the tuneable value inside the structure pointed to by base.  */
7096/* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7097/* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7098/* ipftp_void that points to the stored value.                              */
7099/* ------------------------------------------------------------------------ */
7100ipftuneable_t *
7101ipf_tune_array_copy(base, size, template)
7102	void *base;
7103	size_t size;
7104	ipftuneable_t *template;
7105{
7106	ipftuneable_t *copy;
7107	int i;
7108
7109
7110	KMALLOCS(copy, ipftuneable_t *, size);
7111	if (copy == NULL) {
7112		return NULL;
7113	}
7114	bcopy(template, copy, size);
7115
7116	for (i = 0; copy[i].ipft_name; i++) {
7117		copy[i].ipft_una.ipftp_offset += (u_long)base;
7118		copy[i].ipft_next = copy + i + 1;
7119	}
7120
7121	return copy;
7122}
7123
7124
7125/* ------------------------------------------------------------------------ */
7126/* Function:    ipf_tune_add                                                */
7127/* Returns:     int - 0 == success, else failure                            */
7128/* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7129/*                                                                          */
7130/* Appends tune structures from the array passed in (newtune) to the end of */
7131/* the current list of "dynamic" tuneable parameters.  Once added, the      */
7132/* owner of the object is not expected to ever change "ipft_next".          */
7133/* ------------------------------------------------------------------------ */
7134int
7135ipf_tune_add(softc, newtune)
7136	ipf_main_softc_t *softc;
7137	ipftuneable_t *newtune;
7138{
7139	ipftuneable_t *ta, **tap;
7140
7141	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7142	if (ta != NULL) {
7143		IPFERROR(74);
7144		return EEXIST;
7145	}
7146
7147	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7148		;
7149
7150	newtune->ipft_next = NULL;
7151	*tap = newtune;
7152	return 0;
7153}
7154
7155
7156/* ------------------------------------------------------------------------ */
7157/* Function:    ipf_tune_del                                                */
7158/* Returns:     int - 0 == success, else failure                            */
7159/* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7160/*                        current dynamic tuneables                         */
7161/*                                                                          */
7162/* Search for the tune structure, by pointer, in the list of those that are */
7163/* dynamically added at run time.  If found, adjust the list so that this   */
7164/* structure is no longer part of it.                                       */
7165/* ------------------------------------------------------------------------ */
7166int
7167ipf_tune_del(softc, oldtune)
7168	ipf_main_softc_t *softc;
7169	ipftuneable_t *oldtune;
7170{
7171	ipftuneable_t *ta, **tap;
7172	int error = 0;
7173
7174	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7175	     tap = &ta->ipft_next) {
7176		if (ta == oldtune) {
7177			*tap = oldtune->ipft_next;
7178			oldtune->ipft_next = NULL;
7179			break;
7180		}
7181	}
7182
7183	if (ta == NULL) {
7184		error = ESRCH;
7185		IPFERROR(75);
7186	}
7187	return error;
7188}
7189
7190
7191/* ------------------------------------------------------------------------ */
7192/* Function:    ipf_tune_del_array                                          */
7193/* Returns:     int - 0 == success, else failure                            */
7194/* Parameters:  oldtune - pointer to tuneables array                        */
7195/*                                                                          */
7196/* Remove each tuneable entry in the array from the list of "dynamic"       */
7197/* tunables.  If one entry should fail to be found, an error will be        */
7198/* returned and no further ones removed.                                    */
7199/* An entry with a NULL name is used as the indicator of the last entry in  */
7200/* the array.                                                               */
7201/* ------------------------------------------------------------------------ */
7202int
7203ipf_tune_del_array(softc, oldtune)
7204	ipf_main_softc_t *softc;
7205	ipftuneable_t *oldtune;
7206{
7207	ipftuneable_t *ot;
7208	int error = 0;
7209
7210	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7211		error = ipf_tune_del(softc, ot);
7212		if (error != 0)
7213			break;
7214	}
7215
7216	return error;
7217
7218}
7219
7220
7221/* ------------------------------------------------------------------------ */
7222/* Function:    ipf_tune                                                    */
7223/* Returns:     int - 0 == success, else failure                            */
7224/* Parameters:  cmd(I)  - ioctl command number                              */
7225/*              data(I) - pointer to ioctl data structure                   */
7226/*                                                                          */
7227/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7228/* three ioctls provide the means to access and control global variables    */
7229/* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7230/* changed without rebooting, reloading or recompiling.  The initialisation */
7231/* and 'destruction' routines of the various components of ipfilter are all */
7232/* each responsible for handling their own values being too big.            */
7233/* ------------------------------------------------------------------------ */
7234int
7235ipf_ipftune(softc, cmd, data)
7236	ipf_main_softc_t *softc;
7237	ioctlcmd_t cmd;
7238	void *data;
7239{
7240	ipftuneable_t *ta;
7241	ipftune_t tu;
7242	void *cookie;
7243	int error;
7244
7245	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7246	if (error != 0)
7247		return error;
7248
7249	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7250	cookie = tu.ipft_cookie;
7251	ta = NULL;
7252
7253	switch (cmd)
7254	{
7255	case SIOCIPFGETNEXT :
7256		/*
7257		 * If cookie is non-NULL, assume it to be a pointer to the last
7258		 * entry we looked at, so find it (if possible) and return a
7259		 * pointer to the next one after it.  The last entry in the
7260		 * the table is a NULL entry, so when we get to it, set cookie
7261		 * to NULL and return that, indicating end of list, erstwhile
7262		 * if we come in with cookie set to NULL, we are starting anew
7263		 * at the front of the list.
7264		 */
7265		if (cookie != NULL) {
7266			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7267						   cookie, &tu.ipft_cookie);
7268		} else {
7269			ta = softc->ipf_tuners;
7270			tu.ipft_cookie = ta + 1;
7271		}
7272		if (ta != NULL) {
7273			/*
7274			 * Entry found, but does the data pointed to by that
7275			 * row fit in what we can return?
7276			 */
7277			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7278				IPFERROR(76);
7279				return EINVAL;
7280			}
7281
7282			tu.ipft_vlong = 0;
7283			if (ta->ipft_sz == sizeof(u_long))
7284				tu.ipft_vlong = *ta->ipft_plong;
7285			else if (ta->ipft_sz == sizeof(u_int))
7286				tu.ipft_vint = *ta->ipft_pint;
7287			else if (ta->ipft_sz == sizeof(u_short))
7288				tu.ipft_vshort = *ta->ipft_pshort;
7289			else if (ta->ipft_sz == sizeof(u_char))
7290				tu.ipft_vchar = *ta->ipft_pchar;
7291
7292			tu.ipft_sz = ta->ipft_sz;
7293			tu.ipft_min = ta->ipft_min;
7294			tu.ipft_max = ta->ipft_max;
7295			tu.ipft_flags = ta->ipft_flags;
7296			bcopy(ta->ipft_name, tu.ipft_name,
7297			      MIN(sizeof(tu.ipft_name),
7298				  strlen(ta->ipft_name) + 1));
7299		}
7300		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7301		break;
7302
7303	case SIOCIPFGET :
7304	case SIOCIPFSET :
7305		/*
7306		 * Search by name or by cookie value for a particular entry
7307		 * in the tuning paramter table.
7308		 */
7309		IPFERROR(77);
7310		error = ESRCH;
7311		if (cookie != NULL) {
7312			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7313						   cookie, NULL);
7314			if (ta != NULL)
7315				error = 0;
7316		} else if (tu.ipft_name[0] != '\0') {
7317			ta = ipf_tune_findbyname(softc->ipf_tuners,
7318						 tu.ipft_name);
7319			if (ta != NULL)
7320				error = 0;
7321		}
7322		if (error != 0)
7323			break;
7324
7325		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7326			/*
7327			 * Fetch the tuning parameters for a particular value
7328			 */
7329			tu.ipft_vlong = 0;
7330			if (ta->ipft_sz == sizeof(u_long))
7331				tu.ipft_vlong = *ta->ipft_plong;
7332			else if (ta->ipft_sz == sizeof(u_int))
7333				tu.ipft_vint = *ta->ipft_pint;
7334			else if (ta->ipft_sz == sizeof(u_short))
7335				tu.ipft_vshort = *ta->ipft_pshort;
7336			else if (ta->ipft_sz == sizeof(u_char))
7337				tu.ipft_vchar = *ta->ipft_pchar;
7338			tu.ipft_cookie = ta;
7339			tu.ipft_sz = ta->ipft_sz;
7340			tu.ipft_min = ta->ipft_min;
7341			tu.ipft_max = ta->ipft_max;
7342			tu.ipft_flags = ta->ipft_flags;
7343			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7344
7345		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7346			/*
7347			 * Set an internal parameter.  The hard part here is
7348			 * getting the new value safely and correctly out of
7349			 * the kernel (given we only know its size, not type.)
7350			 */
7351			u_long in;
7352
7353			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7354			    (softc->ipf_running > 0)) {
7355				IPFERROR(78);
7356				error = EBUSY;
7357				break;
7358			}
7359
7360			in = tu.ipft_vlong;
7361			if (in < ta->ipft_min || in > ta->ipft_max) {
7362				IPFERROR(79);
7363				error = EINVAL;
7364				break;
7365			}
7366
7367			if (ta->ipft_func != NULL) {
7368				SPL_INT(s);
7369
7370				SPL_NET(s);
7371				error = (*ta->ipft_func)(softc, ta,
7372							 &tu.ipft_un);
7373				SPL_X(s);
7374
7375			} else if (ta->ipft_sz == sizeof(u_long)) {
7376				tu.ipft_vlong = *ta->ipft_plong;
7377				*ta->ipft_plong = in;
7378
7379			} else if (ta->ipft_sz == sizeof(u_int)) {
7380				tu.ipft_vint = *ta->ipft_pint;
7381				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7382
7383			} else if (ta->ipft_sz == sizeof(u_short)) {
7384				tu.ipft_vshort = *ta->ipft_pshort;
7385				*ta->ipft_pshort = (u_short)(in & 0xffff);
7386
7387			} else if (ta->ipft_sz == sizeof(u_char)) {
7388				tu.ipft_vchar = *ta->ipft_pchar;
7389				*ta->ipft_pchar = (u_char)(in & 0xff);
7390			}
7391			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7392		}
7393		break;
7394
7395	default :
7396		IPFERROR(80);
7397		error = EINVAL;
7398		break;
7399	}
7400
7401	return error;
7402}
7403
7404
7405/* ------------------------------------------------------------------------ */
7406/* Function:    ipf_zerostats                                               */
7407/* Returns:     int - 0 = success, else failure                             */
7408/* Parameters:  data(O) - pointer to pointer for copying data back to       */
7409/*                                                                          */
7410/* Copies the current statistics out to userspace and then zero's the       */
7411/* current ones in the kernel. The lock is only held across the bzero() as  */
7412/* the copyout may result in paging (ie network activity.)                  */
7413/* ------------------------------------------------------------------------ */
7414int
7415ipf_zerostats(softc, data)
7416	ipf_main_softc_t *softc;
7417	caddr_t	data;
7418{
7419	friostat_t fio;
7420	ipfobj_t obj;
7421	int error;
7422
7423	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7424	if (error != 0)
7425		return error;
7426	ipf_getstat(softc, &fio, obj.ipfo_rev);
7427	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7428	if (error != 0)
7429		return error;
7430
7431	WRITE_ENTER(&softc->ipf_mutex);
7432	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7433	RWLOCK_EXIT(&softc->ipf_mutex);
7434
7435	return 0;
7436}
7437
7438
7439/* ------------------------------------------------------------------------ */
7440/* Function:    ipf_resolvedest                                             */
7441/* Returns:     Nil                                                         */
7442/* Parameters:  softc(I) - pointer to soft context main structure           */
7443/*              base(I)  - where strings are stored                         */
7444/*              fdp(IO)  - pointer to destination information to resolve    */
7445/*              v(I)     - IP protocol version to match                     */
7446/*                                                                          */
7447/* Looks up an interface name in the frdest structure pointed to by fdp and */
7448/* if a matching name can be found for the particular IP protocol version   */
7449/* then store the interface pointer in the frdest struct.  If no match is   */
7450/* found, then set the interface pointer to be -1 as NULL is considered to  */
7451/* indicate there is no information at all in the structure.                */
7452/* ------------------------------------------------------------------------ */
7453int
7454ipf_resolvedest(softc, base, fdp, v)
7455	ipf_main_softc_t *softc;
7456	char *base;
7457	frdest_t *fdp;
7458	int v;
7459{
7460	int errval = 0;
7461	void *ifp;
7462
7463	ifp = NULL;
7464
7465	if (fdp->fd_name != -1) {
7466		if (fdp->fd_type == FRD_DSTLIST) {
7467			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7468						  IPLT_DSTLIST,
7469						  base + fdp->fd_name,
7470						  NULL);
7471			if (ifp == NULL) {
7472				IPFERROR(144);
7473				errval = ESRCH;
7474			}
7475		} else {
7476			ifp = GETIFP(base + fdp->fd_name, v);
7477			if (ifp == NULL)
7478				ifp = (void *)-1;
7479		}
7480	}
7481	fdp->fd_ptr = ifp;
7482
7483	return errval;
7484}
7485
7486
7487/* ------------------------------------------------------------------------ */
7488/* Function:    ipf_resolvenic                                              */
7489/* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7490/*                      pointer to interface structure for NIC              */
7491/* Parameters:  softc(I)- pointer to soft context main structure            */
7492/*              name(I) - complete interface name                           */
7493/*              v(I)    - IP protocol version                               */
7494/*                                                                          */
7495/* Look for a network interface structure that firstly has a matching name  */
7496/* to that passed in and that is also being used for that IP protocol       */
7497/* version (necessary on some platforms where there are separate listings   */
7498/* for both IPv4 and IPv6 on the same physical NIC.                         */
7499/* ------------------------------------------------------------------------ */
7500void *
7501ipf_resolvenic(softc, name, v)
7502	ipf_main_softc_t *softc;
7503	char *name;
7504	int v;
7505{
7506	void *nic;
7507
7508	softc = softc;	/* gcc -Wextra */
7509	if (name[0] == '\0')
7510		return NULL;
7511
7512	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7513		return NULL;
7514	}
7515
7516	nic = GETIFP(name, v);
7517	if (nic == NULL)
7518		nic = (void *)-1;
7519	return nic;
7520}
7521
7522
7523/* ------------------------------------------------------------------------ */
7524/* Function:    ipf_token_expire                                            */
7525/* Returns:     None.                                                       */
7526/* Parameters:  softc(I) - pointer to soft context main structure           */
7527/*                                                                          */
7528/* This function is run every ipf tick to see if there are any tokens that  */
7529/* have been held for too long and need to be freed up.                     */
7530/* ------------------------------------------------------------------------ */
7531void
7532ipf_token_expire(softc)
7533	ipf_main_softc_t *softc;
7534{
7535	ipftoken_t *it;
7536
7537	WRITE_ENTER(&softc->ipf_tokens);
7538	while ((it = softc->ipf_token_head) != NULL) {
7539		if (it->ipt_die > softc->ipf_ticks)
7540			break;
7541
7542		ipf_token_deref(softc, it);
7543	}
7544	RWLOCK_EXIT(&softc->ipf_tokens);
7545}
7546
7547
7548/* ------------------------------------------------------------------------ */
7549/* Function:    ipf_token_flush                                             */
7550/* Returns:     None.                                                       */
7551/* Parameters:  softc(I) - pointer to soft context main structure           */
7552/*                                                                          */
7553/* Loop through all of the existing tokens and call deref to see if they    */
7554/* can be freed. Normally a function like this might just loop on           */
7555/* ipf_token_head but there is a chance that a token might have a ref count */
7556/* of greater than one and in that case the the reference would drop twice  */
7557/* by code that is only entitled to drop it once.                           */
7558/* ------------------------------------------------------------------------ */
7559static void
7560ipf_token_flush(softc)
7561	ipf_main_softc_t *softc;
7562{
7563	ipftoken_t *it, *next;
7564
7565	WRITE_ENTER(&softc->ipf_tokens);
7566	for (it = softc->ipf_token_head; it != NULL; it = next) {
7567		next = it->ipt_next;
7568		(void) ipf_token_deref(softc, it);
7569	}
7570	RWLOCK_EXIT(&softc->ipf_tokens);
7571}
7572
7573
7574/* ------------------------------------------------------------------------ */
7575/* Function:    ipf_token_del                                               */
7576/* Returns:     int     - 0 = success, else error                           */
7577/* Parameters:  softc(I)- pointer to soft context main structure            */
7578/*              type(I) - the token type to match                           */
7579/*              uid(I)  - uid owning the token                              */
7580/*              ptr(I)  - context pointer for the token                     */
7581/*                                                                          */
7582/* This function looks for a a token in the current list that matches up    */
7583/* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7584/* call ipf_token_dewref() to remove it from the list. In the event that    */
7585/* the token has a reference held elsewhere, setting ipt_complete to 2      */
7586/* enables debugging to distinguish between the two paths that ultimately   */
7587/* lead to a token to be deleted.                                           */
7588/* ------------------------------------------------------------------------ */
7589int
7590ipf_token_del(softc, type, uid, ptr)
7591	ipf_main_softc_t *softc;
7592	int type, uid;
7593	void *ptr;
7594{
7595	ipftoken_t *it;
7596	int error;
7597
7598	IPFERROR(82);
7599	error = ESRCH;
7600
7601	WRITE_ENTER(&softc->ipf_tokens);
7602	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7603		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7604		    uid == it->ipt_uid) {
7605			it->ipt_complete = 2;
7606			ipf_token_deref(softc, it);
7607			error = 0;
7608			break;
7609		}
7610	}
7611	RWLOCK_EXIT(&softc->ipf_tokens);
7612
7613	return error;
7614}
7615
7616
7617/* ------------------------------------------------------------------------ */
7618/* Function:    ipf_token_mark_complete                                     */
7619/* Returns:     None.                                                       */
7620/* Parameters:  token(I) - pointer to token structure                       */
7621/*                                                                          */
7622/* Mark a token as being ineligable for being found with ipf_token_find.    */
7623/* ------------------------------------------------------------------------ */
7624void
7625ipf_token_mark_complete(token)
7626	ipftoken_t *token;
7627{
7628	if (token->ipt_complete == 0)
7629		token->ipt_complete = 1;
7630}
7631
7632
7633/* ------------------------------------------------------------------------ */
7634/* Function:    ipf_token_find                                               */
7635/* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7636/* Parameters:  softc(I)- pointer to soft context main structure            */
7637/*              type(I) - the token type to match                           */
7638/*              uid(I)  - uid owning the token                              */
7639/*              ptr(I)  - context pointer for the token                     */
7640/*                                                                          */
7641/* This function looks for a live token in the list of current tokens that  */
7642/* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7643/* allocated.  If one is found then it is moved to the top of the list of   */
7644/* currently active tokens.                                                 */
7645/* ------------------------------------------------------------------------ */
7646ipftoken_t *
7647ipf_token_find(softc, type, uid, ptr)
7648	ipf_main_softc_t *softc;
7649	int type, uid;
7650	void *ptr;
7651{
7652	ipftoken_t *it, *new;
7653
7654	KMALLOC(new, ipftoken_t *);
7655	if (new != NULL)
7656		bzero((char *)new, sizeof(*new));
7657
7658	WRITE_ENTER(&softc->ipf_tokens);
7659	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7660		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7661		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7662			break;
7663	}
7664
7665	if (it == NULL) {
7666		it = new;
7667		new = NULL;
7668		if (it == NULL) {
7669			RWLOCK_EXIT(&softc->ipf_tokens);
7670			return NULL;
7671		}
7672		it->ipt_ctx = ptr;
7673		it->ipt_uid = uid;
7674		it->ipt_type = type;
7675		it->ipt_ref = 1;
7676	} else {
7677		if (new != NULL) {
7678			KFREE(new);
7679			new = NULL;
7680		}
7681
7682		if (it->ipt_complete > 0)
7683			it = NULL;
7684		else
7685			ipf_token_unlink(softc, it);
7686	}
7687
7688	if (it != NULL) {
7689		it->ipt_pnext = softc->ipf_token_tail;
7690		*softc->ipf_token_tail = it;
7691		softc->ipf_token_tail = &it->ipt_next;
7692		it->ipt_next = NULL;
7693		it->ipt_ref++;
7694
7695		it->ipt_die = softc->ipf_ticks + 20;
7696	}
7697
7698	RWLOCK_EXIT(&softc->ipf_tokens);
7699
7700	return it;
7701}
7702
7703
7704/* ------------------------------------------------------------------------ */
7705/* Function:    ipf_token_unlink                                            */
7706/* Returns:     None.                                                       */
7707/* Parameters:  softc(I) - pointer to soft context main structure           */
7708/*              token(I) - pointer to token structure                       */
7709/* Write Locks: ipf_tokens                                                  */
7710/*                                                                          */
7711/* This function unlinks a token structure from the linked list of tokens   */
7712/* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7713/* but the tail does due to the linked list implementation.                 */
7714/* ------------------------------------------------------------------------ */
7715static void
7716ipf_token_unlink(softc, token)
7717	ipf_main_softc_t *softc;
7718	ipftoken_t *token;
7719{
7720
7721	if (softc->ipf_token_tail == &token->ipt_next)
7722		softc->ipf_token_tail = token->ipt_pnext;
7723
7724	*token->ipt_pnext = token->ipt_next;
7725	if (token->ipt_next != NULL)
7726		token->ipt_next->ipt_pnext = token->ipt_pnext;
7727	token->ipt_next = NULL;
7728	token->ipt_pnext = NULL;
7729}
7730
7731
7732/* ------------------------------------------------------------------------ */
7733/* Function:    ipf_token_deref                                             */
7734/* Returns:     int      - 0 == token freed, else reference count           */
7735/* Parameters:  softc(I) - pointer to soft context main structure           */
7736/*              token(I) - pointer to token structure                       */
7737/* Write Locks: ipf_tokens                                                  */
7738/*                                                                          */
7739/* Drop the reference count on the token structure and if it drops to zero, */
7740/* call the dereference function for the token type because it is then      */
7741/* possible to free the token data structure.                               */
7742/* ------------------------------------------------------------------------ */
7743int
7744ipf_token_deref(softc, token)
7745	ipf_main_softc_t *softc;
7746	ipftoken_t *token;
7747{
7748	void *data, **datap;
7749
7750	ASSERT(token->ipt_ref > 0);
7751	token->ipt_ref--;
7752	if (token->ipt_ref > 0)
7753		return token->ipt_ref;
7754
7755	data = token->ipt_data;
7756	datap = &data;
7757
7758	if ((data != NULL) && (data != (void *)-1)) {
7759		switch (token->ipt_type)
7760		{
7761		case IPFGENITER_IPF :
7762			(void) ipf_derefrule(softc, (frentry_t **)datap);
7763			break;
7764		case IPFGENITER_IPNAT :
7765			WRITE_ENTER(&softc->ipf_nat);
7766			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7767			RWLOCK_EXIT(&softc->ipf_nat);
7768			break;
7769		case IPFGENITER_NAT :
7770			ipf_nat_deref(softc, (nat_t **)datap);
7771			break;
7772		case IPFGENITER_STATE :
7773			ipf_state_deref(softc, (ipstate_t **)datap);
7774			break;
7775		case IPFGENITER_FRAG :
7776			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7777			break;
7778		case IPFGENITER_NATFRAG :
7779			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7780			break;
7781		case IPFGENITER_HOSTMAP :
7782			WRITE_ENTER(&softc->ipf_nat);
7783			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7784			RWLOCK_EXIT(&softc->ipf_nat);
7785			break;
7786		default :
7787			ipf_lookup_iterderef(softc, token->ipt_type, data);
7788			break;
7789		}
7790	}
7791
7792	ipf_token_unlink(softc, token);
7793	KFREE(token);
7794	return 0;
7795}
7796
7797
7798/* ------------------------------------------------------------------------ */
7799/* Function:    ipf_nextrule                                                */
7800/* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7801/* Parameters:  softc(I)    - pointer to soft context main structure        */
7802/*              fr(I)       - pointer to filter rule                        */
7803/*              out(I)      - 1 == out rules, 0 == input rules              */
7804/*                                                                          */
7805/* Starting with "fr", find the next rule to visit. This includes visiting  */
7806/* the list of rule groups if either fr is NULL (empty list) or it is the   */
7807/* last rule in the list. When walking rule lists, it is either input or    */
7808/* output rules that are returned, never both.                              */
7809/* ------------------------------------------------------------------------ */
7810static frentry_t *
7811ipf_nextrule(softc, active, unit, fr, out)
7812	ipf_main_softc_t *softc;
7813	int active, unit;
7814	frentry_t *fr;
7815	int out;
7816{
7817	frentry_t *next;
7818	frgroup_t *fg;
7819
7820	if (fr != NULL && fr->fr_group != -1) {
7821		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7822				   unit, active, NULL);
7823		if (fg != NULL)
7824			fg = fg->fg_next;
7825	} else {
7826		fg = softc->ipf_groups[unit][active];
7827	}
7828
7829	while (fg != NULL) {
7830		next = fg->fg_start;
7831		while (next != NULL) {
7832			if (out) {
7833				if (next->fr_flags & FR_OUTQUE)
7834					return next;
7835			} else if (next->fr_flags & FR_INQUE) {
7836				return next;
7837			}
7838			next = next->fr_next;
7839		}
7840		if (next == NULL)
7841			fg = fg->fg_next;
7842	}
7843
7844	return NULL;
7845}
7846
7847/* ------------------------------------------------------------------------ */
7848/* Function:    ipf_getnextrule                                             */
7849/* Returns:     int - 0 = success, else error                               */
7850/* Parameters:  softc(I)- pointer to soft context main structure            */
7851/*              t(I)   - pointer to destination information to resolve      */
7852/*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7853/*                                                                          */
7854/* This function's first job is to bring in the ipfruleiter_t structure via */
7855/* the ipfobj_t structure to determine what should be the next rule to      */
7856/* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7857/* find the 'next rule'.  This may include searching rule group lists or    */
7858/* just be as simple as looking at the 'next' field in the rule structure.  */
7859/* When we have found the rule to return, increase its reference count and  */
7860/* if we used an existing rule to get here, decrease its reference count.   */
7861/* ------------------------------------------------------------------------ */
7862int
7863ipf_getnextrule(softc, t, ptr)
7864	ipf_main_softc_t *softc;
7865	ipftoken_t *t;
7866	void *ptr;
7867{
7868	frentry_t *fr, *next, zero;
7869	ipfruleiter_t it;
7870	int error, out;
7871	frgroup_t *fg;
7872	ipfobj_t obj;
7873	int predict;
7874	char *dst;
7875	int unit;
7876
7877	if (t == NULL || ptr == NULL) {
7878		IPFERROR(84);
7879		return EFAULT;
7880	}
7881
7882	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7883	if (error != 0)
7884		return error;
7885
7886	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7887		IPFERROR(85);
7888		return EINVAL;
7889	}
7890	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7891		IPFERROR(86);
7892		return EINVAL;
7893	}
7894	if (it.iri_nrules == 0) {
7895		IPFERROR(87);
7896		return ENOSPC;
7897	}
7898	if (it.iri_rule == NULL) {
7899		IPFERROR(88);
7900		return EFAULT;
7901	}
7902
7903	fg = NULL;
7904	fr = t->ipt_data;
7905	if ((it.iri_inout & F_OUT) != 0)
7906		out = 1;
7907	else
7908		out = 0;
7909	if ((it.iri_inout & F_ACIN) != 0)
7910		unit = IPL_LOGCOUNT;
7911	else
7912		unit = IPL_LOGIPF;
7913
7914	READ_ENTER(&softc->ipf_mutex);
7915	if (fr == NULL) {
7916		if (*it.iri_group == '\0') {
7917			if (unit == IPL_LOGCOUNT) {
7918				next = softc->ipf_acct[out][it.iri_active];
7919			} else {
7920				next = softc->ipf_rules[out][it.iri_active];
7921			}
7922			if (next == NULL)
7923				next = ipf_nextrule(softc, it.iri_active,
7924						    unit, NULL, out);
7925		} else {
7926			fg = ipf_findgroup(softc, it.iri_group, unit,
7927					   it.iri_active, NULL);
7928			if (fg != NULL)
7929				next = fg->fg_start;
7930			else
7931				next = NULL;
7932		}
7933	} else {
7934		next = fr->fr_next;
7935		if (next == NULL)
7936			next = ipf_nextrule(softc, it.iri_active, unit,
7937					    fr, out);
7938	}
7939
7940	if (next != NULL && next->fr_next != NULL)
7941		predict = 1;
7942	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7943		predict = 1;
7944	else
7945		predict = 0;
7946
7947	if (fr != NULL)
7948		(void) ipf_derefrule(softc, &fr);
7949
7950	obj.ipfo_type = IPFOBJ_FRENTRY;
7951	dst = (char *)it.iri_rule;
7952
7953	if (next != NULL) {
7954		obj.ipfo_size = next->fr_size;
7955		MUTEX_ENTER(&next->fr_lock);
7956		next->fr_ref++;
7957		MUTEX_EXIT(&next->fr_lock);
7958		t->ipt_data = next;
7959	} else {
7960		obj.ipfo_size = sizeof(frentry_t);
7961		bzero(&zero, sizeof(zero));
7962		next = &zero;
7963		t->ipt_data = NULL;
7964	}
7965	it.iri_rule = predict ? next : NULL;
7966	if (predict == 0)
7967		ipf_token_mark_complete(t);
7968
7969	RWLOCK_EXIT(&softc->ipf_mutex);
7970
7971	obj.ipfo_ptr = dst;
7972	error = ipf_outobjk(softc, &obj, next);
7973	if (error == 0 && t->ipt_data != NULL) {
7974		dst += obj.ipfo_size;
7975		if (next->fr_data != NULL) {
7976			ipfobj_t dobj;
7977
7978			if (next->fr_type == FR_T_IPFEXPR)
7979				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7980			else
7981				dobj.ipfo_type = IPFOBJ_FRIPF;
7982			dobj.ipfo_size = next->fr_dsize;
7983			dobj.ipfo_rev = obj.ipfo_rev;
7984			dobj.ipfo_ptr = dst;
7985			error = ipf_outobjk(softc, &dobj, next->fr_data);
7986		}
7987	}
7988
7989	if ((fr != NULL) && (next == &zero))
7990		(void) ipf_derefrule(softc, &fr);
7991
7992	return error;
7993}
7994
7995
7996/* ------------------------------------------------------------------------ */
7997/* Function:    ipf_frruleiter                                              */
7998/* Returns:     int - 0 = success, else error                               */
7999/* Parameters:  softc(I)- pointer to soft context main structure            */
8000/*              data(I) - the token type to match                           */
8001/*              uid(I)  - uid owning the token                              */
8002/*              ptr(I)  - context pointer for the token                     */
8003/*                                                                          */
8004/* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8005/* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8006/* the process doing the ioctl and use that to ask for the next rule.       */
8007/* ------------------------------------------------------------------------ */
8008static int
8009ipf_frruleiter(softc, data, uid, ctx)
8010	ipf_main_softc_t *softc;
8011	void *data, *ctx;
8012	int uid;
8013{
8014	ipftoken_t *token;
8015	ipfruleiter_t it;
8016	ipfobj_t obj;
8017	int error;
8018
8019	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8020	if (token != NULL) {
8021		error = ipf_getnextrule(softc, token, data);
8022		WRITE_ENTER(&softc->ipf_tokens);
8023		ipf_token_deref(softc, token);
8024		RWLOCK_EXIT(&softc->ipf_tokens);
8025	} else {
8026		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8027		if (error != 0)
8028			return error;
8029		it.iri_rule = NULL;
8030		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8031	}
8032
8033	return error;
8034}
8035
8036
8037/* ------------------------------------------------------------------------ */
8038/* Function:    ipf_geniter                                                 */
8039/* Returns:     int - 0 = success, else error                               */
8040/* Parameters:  softc(I) - pointer to soft context main structure           */
8041/*              token(I) - pointer to ipftoken_t structure                  */
8042/*              itp(I)   - pointer to iterator data                         */
8043/*                                                                          */
8044/* Decide which iterator function to call using information passed through  */
8045/* the ipfgeniter_t structure at itp.                                       */
8046/* ------------------------------------------------------------------------ */
8047static int
8048ipf_geniter(softc, token, itp)
8049	ipf_main_softc_t *softc;
8050	ipftoken_t *token;
8051	ipfgeniter_t *itp;
8052{
8053	int error;
8054
8055	switch (itp->igi_type)
8056	{
8057	case IPFGENITER_FRAG :
8058		error = ipf_frag_pkt_next(softc, token, itp);
8059		break;
8060	default :
8061		IPFERROR(92);
8062		error = EINVAL;
8063		break;
8064	}
8065
8066	return error;
8067}
8068
8069
8070/* ------------------------------------------------------------------------ */
8071/* Function:    ipf_genericiter                                             */
8072/* Returns:     int - 0 = success, else error                               */
8073/* Parameters:  softc(I)- pointer to soft context main structure            */
8074/*              data(I) - the token type to match                           */
8075/*              uid(I)  - uid owning the token                              */
8076/*              ptr(I)  - context pointer for the token                     */
8077/*                                                                          */
8078/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8079/* ------------------------------------------------------------------------ */
8080int
8081ipf_genericiter(softc, data, uid, ctx)
8082	ipf_main_softc_t *softc;
8083	void *data, *ctx;
8084	int uid;
8085{
8086	ipftoken_t *token;
8087	ipfgeniter_t iter;
8088	int error;
8089
8090	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8091	if (error != 0)
8092		return error;
8093
8094	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8095	if (token != NULL) {
8096		token->ipt_subtype = iter.igi_type;
8097		error = ipf_geniter(softc, token, &iter);
8098		WRITE_ENTER(&softc->ipf_tokens);
8099		ipf_token_deref(softc, token);
8100		RWLOCK_EXIT(&softc->ipf_tokens);
8101	} else {
8102		IPFERROR(93);
8103		error = 0;
8104	}
8105
8106	return error;
8107}
8108
8109
8110/* ------------------------------------------------------------------------ */
8111/* Function:    ipf_ipf_ioctl                                               */
8112/* Returns:     int - 0 = success, else error                               */
8113/* Parameters:  softc(I)- pointer to soft context main structure           */
8114/*              data(I) - the token type to match                           */
8115/*              cmd(I)  - the ioctl command number                          */
8116/*              mode(I) - mode flags for the ioctl                          */
8117/*              uid(I)  - uid owning the token                              */
8118/*              ptr(I)  - context pointer for the token                     */
8119/*                                                                          */
8120/* This function handles all of the ioctl command that are actually isssued */
8121/* to the /dev/ipl device.                                                  */
8122/* ------------------------------------------------------------------------ */
8123int
8124ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8125	ipf_main_softc_t *softc;
8126	caddr_t data;
8127	ioctlcmd_t cmd;
8128	int mode, uid;
8129	void *ctx;
8130{
8131	friostat_t fio;
8132	int error, tmp;
8133	ipfobj_t obj;
8134	SPL_INT(s);
8135
8136	switch (cmd)
8137	{
8138	case SIOCFRENB :
8139		if (!(mode & FWRITE)) {
8140			IPFERROR(94);
8141			error = EPERM;
8142		} else {
8143			error = BCOPYIN(data, &tmp, sizeof(tmp));
8144			if (error != 0) {
8145				IPFERROR(95);
8146				error = EFAULT;
8147				break;
8148			}
8149
8150			WRITE_ENTER(&softc->ipf_global);
8151			if (tmp) {
8152				if (softc->ipf_running > 0)
8153					error = 0;
8154				else
8155					error = ipfattach(softc);
8156				if (error == 0)
8157					softc->ipf_running = 1;
8158				else
8159					(void) ipfdetach(softc);
8160			} else {
8161				if (softc->ipf_running == 1)
8162					error = ipfdetach(softc);
8163				else
8164					error = 0;
8165				if (error == 0)
8166					softc->ipf_running = -1;
8167			}
8168			RWLOCK_EXIT(&softc->ipf_global);
8169		}
8170		break;
8171
8172	case SIOCIPFSET :
8173		if (!(mode & FWRITE)) {
8174			IPFERROR(96);
8175			error = EPERM;
8176			break;
8177		}
8178		/* FALLTHRU */
8179	case SIOCIPFGETNEXT :
8180	case SIOCIPFGET :
8181		error = ipf_ipftune(softc, cmd, (void *)data);
8182		break;
8183
8184	case SIOCSETFF :
8185		if (!(mode & FWRITE)) {
8186			IPFERROR(97);
8187			error = EPERM;
8188		} else {
8189			error = BCOPYIN(data, &softc->ipf_flags,
8190					sizeof(softc->ipf_flags));
8191			if (error != 0) {
8192				IPFERROR(98);
8193				error = EFAULT;
8194			}
8195		}
8196		break;
8197
8198	case SIOCGETFF :
8199		error = BCOPYOUT(&softc->ipf_flags, data,
8200				 sizeof(softc->ipf_flags));
8201		if (error != 0) {
8202			IPFERROR(99);
8203			error = EFAULT;
8204		}
8205		break;
8206
8207	case SIOCFUNCL :
8208		error = ipf_resolvefunc(softc, (void *)data);
8209		break;
8210
8211	case SIOCINAFR :
8212	case SIOCRMAFR :
8213	case SIOCADAFR :
8214	case SIOCZRLST :
8215		if (!(mode & FWRITE)) {
8216			IPFERROR(100);
8217			error = EPERM;
8218		} else {
8219			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8220					  softc->ipf_active, 1);
8221		}
8222		break;
8223
8224	case SIOCINIFR :
8225	case SIOCRMIFR :
8226	case SIOCADIFR :
8227		if (!(mode & FWRITE)) {
8228			IPFERROR(101);
8229			error = EPERM;
8230		} else {
8231			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8232					  1 - softc->ipf_active, 1);
8233		}
8234		break;
8235
8236	case SIOCSWAPA :
8237		if (!(mode & FWRITE)) {
8238			IPFERROR(102);
8239			error = EPERM;
8240		} else {
8241			WRITE_ENTER(&softc->ipf_mutex);
8242			error = BCOPYOUT(&softc->ipf_active, data,
8243					 sizeof(softc->ipf_active));
8244			if (error != 0) {
8245				IPFERROR(103);
8246				error = EFAULT;
8247			} else {
8248				softc->ipf_active = 1 - softc->ipf_active;
8249			}
8250			RWLOCK_EXIT(&softc->ipf_mutex);
8251		}
8252		break;
8253
8254	case SIOCGETFS :
8255		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8256				  IPFOBJ_IPFSTAT);
8257		if (error != 0)
8258			break;
8259		ipf_getstat(softc, &fio, obj.ipfo_rev);
8260		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8261		break;
8262
8263	case SIOCFRZST :
8264		if (!(mode & FWRITE)) {
8265			IPFERROR(104);
8266			error = EPERM;
8267		} else
8268			error = ipf_zerostats(softc, (caddr_t)data);
8269		break;
8270
8271	case SIOCIPFFL :
8272		if (!(mode & FWRITE)) {
8273			IPFERROR(105);
8274			error = EPERM;
8275		} else {
8276			error = BCOPYIN(data, &tmp, sizeof(tmp));
8277			if (!error) {
8278				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8279				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8280				if (error != 0) {
8281					IPFERROR(106);
8282					error = EFAULT;
8283				}
8284			} else {
8285				IPFERROR(107);
8286				error = EFAULT;
8287			}
8288		}
8289		break;
8290
8291#ifdef USE_INET6
8292	case SIOCIPFL6 :
8293		if (!(mode & FWRITE)) {
8294			IPFERROR(108);
8295			error = EPERM;
8296		} else {
8297			error = BCOPYIN(data, &tmp, sizeof(tmp));
8298			if (!error) {
8299				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8300				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8301				if (error != 0) {
8302					IPFERROR(109);
8303					error = EFAULT;
8304				}
8305			} else {
8306				IPFERROR(110);
8307				error = EFAULT;
8308			}
8309		}
8310		break;
8311#endif
8312
8313	case SIOCSTLCK :
8314		if (!(mode & FWRITE)) {
8315			IPFERROR(122);
8316			error = EPERM;
8317		} else {
8318			error = BCOPYIN(data, &tmp, sizeof(tmp));
8319			if (error == 0) {
8320				ipf_state_setlock(softc->ipf_state_soft, tmp);
8321				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8322				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8323				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8324			} else {
8325				IPFERROR(111);
8326				error = EFAULT;
8327			}
8328		}
8329		break;
8330
8331#ifdef	IPFILTER_LOG
8332	case SIOCIPFFB :
8333		if (!(mode & FWRITE)) {
8334			IPFERROR(112);
8335			error = EPERM;
8336		} else {
8337			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8338			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8339			if (error) {
8340				IPFERROR(113);
8341				error = EFAULT;
8342			}
8343		}
8344		break;
8345#endif /* IPFILTER_LOG */
8346
8347	case SIOCFRSYN :
8348		if (!(mode & FWRITE)) {
8349			IPFERROR(114);
8350			error = EPERM;
8351		} else {
8352			WRITE_ENTER(&softc->ipf_global);
8353#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8354			error = ipfsync();
8355#else
8356			ipf_sync(softc, NULL);
8357			error = 0;
8358#endif
8359			RWLOCK_EXIT(&softc->ipf_global);
8360
8361		}
8362		break;
8363
8364	case SIOCGFRST :
8365		error = ipf_outobj(softc, (void *)data,
8366				   ipf_frag_stats(softc->ipf_frag_soft),
8367				   IPFOBJ_FRAGSTAT);
8368		break;
8369
8370#ifdef	IPFILTER_LOG
8371	case FIONREAD :
8372		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8373		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8374		break;
8375#endif
8376
8377	case SIOCIPFITER :
8378		SPL_SCHED(s);
8379		error = ipf_frruleiter(softc, data, uid, ctx);
8380		SPL_X(s);
8381		break;
8382
8383	case SIOCGENITER :
8384		SPL_SCHED(s);
8385		error = ipf_genericiter(softc, data, uid, ctx);
8386		SPL_X(s);
8387		break;
8388
8389	case SIOCIPFDELTOK :
8390		error = BCOPYIN(data, &tmp, sizeof(tmp));
8391		if (error == 0) {
8392			SPL_SCHED(s);
8393			error = ipf_token_del(softc, tmp, uid, ctx);
8394			SPL_X(s);
8395		}
8396		break;
8397
8398	default :
8399		IPFERROR(115);
8400		error = EINVAL;
8401		break;
8402	}
8403
8404	return error;
8405}
8406
8407
8408/* ------------------------------------------------------------------------ */
8409/* Function:    ipf_decaps                                                  */
8410/* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8411/*                           flags indicating packet filtering decision.    */
8412/* Parameters:  fin(I)     - pointer to packet information                  */
8413/*              pass(I)    - IP protocol version to match                   */
8414/*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8415/*                                                                          */
8416/* This function is called for packets that are wrapt up in other packets,  */
8417/* for example, an IP packet that is the entire data segment for another IP */
8418/* packet.  If the basic constraints for this are satisfied, change the     */
8419/* buffer to point to the start of the inner packet and start processing    */
8420/* rules belonging to the head group this rule specifies.                   */
8421/* ------------------------------------------------------------------------ */
8422u_32_t
8423ipf_decaps(fin, pass, l5proto)
8424	fr_info_t *fin;
8425	u_32_t pass;
8426	int l5proto;
8427{
8428	fr_info_t fin2, *fino = NULL;
8429	int elen, hlen, nh;
8430	grehdr_t gre;
8431	ip_t *ip;
8432	mb_t *m;
8433
8434	if ((fin->fin_flx & FI_COALESCE) == 0)
8435		if (ipf_coalesce(fin) == -1)
8436			goto cantdecaps;
8437
8438	m = fin->fin_m;
8439	hlen = fin->fin_hlen;
8440
8441	switch (fin->fin_p)
8442	{
8443	case IPPROTO_UDP :
8444		/*
8445		 * In this case, the specific protocol being decapsulated
8446		 * inside UDP frames comes from the rule.
8447		 */
8448		nh = fin->fin_fr->fr_icode;
8449		break;
8450
8451	case IPPROTO_GRE :	/* 47 */
8452		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8453		hlen += sizeof(grehdr_t);
8454		if (gre.gr_R|gre.gr_s)
8455			goto cantdecaps;
8456		if (gre.gr_C)
8457			hlen += 4;
8458		if (gre.gr_K)
8459			hlen += 4;
8460		if (gre.gr_S)
8461			hlen += 4;
8462
8463		nh = IPPROTO_IP;
8464
8465		/*
8466		 * If the routing options flag is set, validate that it is
8467		 * there and bounce over it.
8468		 */
8469#if 0
8470		/* This is really heavy weight and lots of room for error, */
8471		/* so for now, put it off and get the simple stuff right.  */
8472		if (gre.gr_R) {
8473			u_char off, len, *s;
8474			u_short af;
8475			int end;
8476
8477			end = 0;
8478			s = fin->fin_dp;
8479			s += hlen;
8480			aplen = fin->fin_plen - hlen;
8481			while (aplen > 3) {
8482				af = (s[0] << 8) | s[1];
8483				off = s[2];
8484				len = s[3];
8485				aplen -= 4;
8486				s += 4;
8487				if (af == 0 && len == 0) {
8488					end = 1;
8489					break;
8490				}
8491				if (aplen < len)
8492					break;
8493				s += len;
8494				aplen -= len;
8495			}
8496			if (end != 1)
8497				goto cantdecaps;
8498			hlen = s - (u_char *)fin->fin_dp;
8499		}
8500#endif
8501		break;
8502
8503#ifdef IPPROTO_IPIP
8504	case IPPROTO_IPIP :	/* 4 */
8505#endif
8506		nh = IPPROTO_IP;
8507		break;
8508
8509	default :	/* Includes ESP, AH is special for IPv4 */
8510		goto cantdecaps;
8511	}
8512
8513	switch (nh)
8514	{
8515	case IPPROTO_IP :
8516	case IPPROTO_IPV6 :
8517		break;
8518	default :
8519		goto cantdecaps;
8520	}
8521
8522	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8523	fino = fin;
8524	fin = &fin2;
8525	elen = hlen;
8526#if defined(MENTAT) && defined(_KERNEL)
8527	m->b_rptr += elen;
8528#else
8529	m->m_data += elen;
8530	m->m_len -= elen;
8531#endif
8532	fin->fin_plen -= elen;
8533
8534	ip = (ip_t *)((char *)fin->fin_ip + elen);
8535
8536	/*
8537	 * Make sure we have at least enough data for the network layer
8538	 * header.
8539	 */
8540	if (IP_V(ip) == 4)
8541		hlen = IP_HL(ip) << 2;
8542#ifdef USE_INET6
8543	else if (IP_V(ip) == 6)
8544		hlen = sizeof(ip6_t);
8545#endif
8546	else
8547		goto cantdecaps2;
8548
8549	if (fin->fin_plen < hlen)
8550		goto cantdecaps2;
8551
8552	fin->fin_dp = (char *)ip + hlen;
8553
8554	if (IP_V(ip) == 4) {
8555		/*
8556		 * Perform IPv4 header checksum validation.
8557		 */
8558		if (ipf_cksum((u_short *)ip, hlen))
8559			goto cantdecaps2;
8560	}
8561
8562	if (ipf_makefrip(hlen, ip, fin) == -1) {
8563cantdecaps2:
8564		if (m != NULL) {
8565#if defined(MENTAT) && defined(_KERNEL)
8566			m->b_rptr -= elen;
8567#else
8568			m->m_data -= elen;
8569			m->m_len += elen;
8570#endif
8571		}
8572cantdecaps:
8573		DT1(frb_decapfrip, fr_info_t *, fin);
8574		pass &= ~FR_CMDMASK;
8575		pass |= FR_BLOCK|FR_QUICK;
8576		fin->fin_reason = FRB_DECAPFRIP;
8577		return -1;
8578	}
8579
8580	pass = ipf_scanlist(fin, pass);
8581
8582	/*
8583	 * Copy the packet filter "result" fields out of the fr_info_t struct
8584	 * that is local to the decapsulation processing and back into the
8585	 * one we were called with.
8586	 */
8587	fino->fin_flx = fin->fin_flx;
8588	fino->fin_rev = fin->fin_rev;
8589	fino->fin_icode = fin->fin_icode;
8590	fino->fin_rule = fin->fin_rule;
8591	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8592	fino->fin_fr = fin->fin_fr;
8593	fino->fin_error = fin->fin_error;
8594	fino->fin_mp = fin->fin_mp;
8595	fino->fin_m = fin->fin_m;
8596	m = fin->fin_m;
8597	if (m != NULL) {
8598#if defined(MENTAT) && defined(_KERNEL)
8599		m->b_rptr -= elen;
8600#else
8601		m->m_data -= elen;
8602		m->m_len += elen;
8603#endif
8604	}
8605	return pass;
8606}
8607
8608
8609/* ------------------------------------------------------------------------ */
8610/* Function:    ipf_matcharray_load                                         */
8611/* Returns:     int         - 0 = success, else error                       */
8612/* Parameters:  softc(I)    - pointer to soft context main structure        */
8613/*              data(I)     - pointer to ioctl data                         */
8614/*              objp(I)     - ipfobj_t structure to load data into          */
8615/*              arrayptr(I) - pointer to location to store array pointer    */
8616/*                                                                          */
8617/* This function loads in a mathing array through the ipfobj_t struct that  */
8618/* describes it.  Sanity checking and array size limitations are enforced   */
8619/* in this function to prevent userspace from trying to load in something   */
8620/* that is insanely big.  Once the size of the array is known, the memory   */
8621/* required is malloc'd and returned through changing *arrayptr.  The       */
8622/* contents of the array are verified before returning.  Only in the event  */
8623/* of a successful call is the caller required to free up the malloc area.  */
8624/* ------------------------------------------------------------------------ */
8625int
8626ipf_matcharray_load(softc, data, objp, arrayptr)
8627	ipf_main_softc_t *softc;
8628	caddr_t data;
8629	ipfobj_t *objp;
8630	int **arrayptr;
8631{
8632	int arraysize, *array, error;
8633
8634	*arrayptr = NULL;
8635
8636	error = BCOPYIN(data, objp, sizeof(*objp));
8637	if (error != 0) {
8638		IPFERROR(116);
8639		return EFAULT;
8640	}
8641
8642	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8643		IPFERROR(117);
8644		return EINVAL;
8645	}
8646
8647	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8648	    (objp->ipfo_size > 1024)) {
8649		IPFERROR(118);
8650		return EINVAL;
8651	}
8652
8653	arraysize = objp->ipfo_size * sizeof(*array);
8654	KMALLOCS(array, int *, arraysize);
8655	if (array == NULL) {
8656		IPFERROR(119);
8657		return ENOMEM;
8658	}
8659
8660	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8661	if (error != 0) {
8662		KFREES(array, arraysize);
8663		IPFERROR(120);
8664		return EFAULT;
8665	}
8666
8667	if (ipf_matcharray_verify(array, arraysize) != 0) {
8668		KFREES(array, arraysize);
8669		IPFERROR(121);
8670		return EINVAL;
8671	}
8672
8673	*arrayptr = array;
8674	return 0;
8675}
8676
8677
8678/* ------------------------------------------------------------------------ */
8679/* Function:    ipf_matcharray_verify                                       */
8680/* Returns:     Nil                                                         */
8681/* Parameters:  array(I)     - pointer to matching array                    */
8682/*              arraysize(I) - number of elements in the array              */
8683/*                                                                          */
8684/* Verify the contents of a matching array by stepping through each element */
8685/* in it.  The actual commands in the array are not verified for            */
8686/* correctness, only that all of the sizes are correctly within limits.     */
8687/* ------------------------------------------------------------------------ */
8688int
8689ipf_matcharray_verify(array, arraysize)
8690	int *array, arraysize;
8691{
8692	int i, nelem, maxidx;
8693	ipfexp_t *e;
8694
8695	nelem = arraysize / sizeof(*array);
8696
8697	/*
8698	 * Currently, it makes no sense to have an array less than 6
8699	 * elements long - the initial size at the from, a single operation
8700	 * (minimum 4 in length) and a trailer, for a total of 6.
8701	 */
8702	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8703		return -1;
8704	}
8705
8706	/*
8707	 * Verify the size of data pointed to by array with how long
8708	 * the array claims to be itself.
8709	 */
8710	if (array[0] * sizeof(*array) != arraysize) {
8711		return -1;
8712	}
8713
8714	maxidx = nelem - 1;
8715	/*
8716	 * The last opcode in this array should be an IPF_EXP_END.
8717	 */
8718	if (array[maxidx] != IPF_EXP_END) {
8719		return -1;
8720	}
8721
8722	for (i = 1; i < maxidx; ) {
8723		e = (ipfexp_t *)(array + i);
8724
8725		/*
8726		 * The length of the bits to check must be at least 1
8727		 * (or else there is nothing to comapre with!) and it
8728		 * cannot exceed the length of the data present.
8729		 */
8730		if ((e->ipfe_size < 1 ) ||
8731		    (e->ipfe_size + i > maxidx)) {
8732			return -1;
8733		}
8734		i += e->ipfe_size;
8735	}
8736	return 0;
8737}
8738
8739
8740/* ------------------------------------------------------------------------ */
8741/* Function:    ipf_fr_matcharray                                           */
8742/* Returns:     int      - 0 = match failed, else positive match            */
8743/* Parameters:  fin(I)   - pointer to packet information                    */
8744/*              array(I) - pointer to matching array                        */
8745/*                                                                          */
8746/* This function is used to apply a matching array against a packet and     */
8747/* return an indication of whether or not the packet successfully matches   */
8748/* all of the commands in it.                                               */
8749/* ------------------------------------------------------------------------ */
8750static int
8751ipf_fr_matcharray(fin, array)
8752	fr_info_t *fin;
8753	int *array;
8754{
8755	int i, n, *x, rv, p;
8756	ipfexp_t *e;
8757
8758	rv = 0;
8759	n = array[0];
8760	x = array + 1;
8761
8762	for (; n > 0; x += 3 + x[3], rv = 0) {
8763		e = (ipfexp_t *)x;
8764		if (e->ipfe_cmd == IPF_EXP_END)
8765			break;
8766		n -= e->ipfe_size;
8767
8768		/*
8769		 * The upper 16 bits currently store the protocol value.
8770		 * This is currently used with TCP and UDP port compares and
8771		 * allows "tcp.port = 80" without requiring an explicit
8772		 " "ip.pr = tcp" first.
8773		 */
8774		p = e->ipfe_cmd >> 16;
8775		if ((p != 0) && (p != fin->fin_p))
8776			break;
8777
8778		switch (e->ipfe_cmd)
8779		{
8780		case IPF_EXP_IP_PR :
8781			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8782				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8783			}
8784			break;
8785
8786		case IPF_EXP_IP_SRCADDR :
8787			if (fin->fin_v != 4)
8788				break;
8789			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8790				rv |= ((fin->fin_saddr &
8791					e->ipfe_arg0[i * 2 + 1]) ==
8792				       e->ipfe_arg0[i * 2]);
8793			}
8794			break;
8795
8796		case IPF_EXP_IP_DSTADDR :
8797			if (fin->fin_v != 4)
8798				break;
8799			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8800				rv |= ((fin->fin_daddr &
8801					e->ipfe_arg0[i * 2 + 1]) ==
8802				       e->ipfe_arg0[i * 2]);
8803			}
8804			break;
8805
8806		case IPF_EXP_IP_ADDR :
8807			if (fin->fin_v != 4)
8808				break;
8809			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8810				rv |= ((fin->fin_saddr &
8811					e->ipfe_arg0[i * 2 + 1]) ==
8812				       e->ipfe_arg0[i * 2]) ||
8813				      ((fin->fin_daddr &
8814					e->ipfe_arg0[i * 2 + 1]) ==
8815				       e->ipfe_arg0[i * 2]);
8816			}
8817			break;
8818
8819#ifdef USE_INET6
8820		case IPF_EXP_IP6_SRCADDR :
8821			if (fin->fin_v != 6)
8822				break;
8823			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8824				rv |= IP6_MASKEQ(&fin->fin_src6,
8825						 &e->ipfe_arg0[i * 8 + 4],
8826						 &e->ipfe_arg0[i * 8]);
8827			}
8828			break;
8829
8830		case IPF_EXP_IP6_DSTADDR :
8831			if (fin->fin_v != 6)
8832				break;
8833			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8834				rv |= IP6_MASKEQ(&fin->fin_dst6,
8835						 &e->ipfe_arg0[i * 8 + 4],
8836						 &e->ipfe_arg0[i * 8]);
8837			}
8838			break;
8839
8840		case IPF_EXP_IP6_ADDR :
8841			if (fin->fin_v != 6)
8842				break;
8843			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8844				rv |= IP6_MASKEQ(&fin->fin_src6,
8845						 &e->ipfe_arg0[i * 8 + 4],
8846						 &e->ipfe_arg0[i * 8]) ||
8847				      IP6_MASKEQ(&fin->fin_dst6,
8848						 &e->ipfe_arg0[i * 8 + 4],
8849						 &e->ipfe_arg0[i * 8]);
8850			}
8851			break;
8852#endif
8853
8854		case IPF_EXP_UDP_PORT :
8855		case IPF_EXP_TCP_PORT :
8856			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8857				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8858				      (fin->fin_dport == e->ipfe_arg0[i]);
8859			}
8860			break;
8861
8862		case IPF_EXP_UDP_SPORT :
8863		case IPF_EXP_TCP_SPORT :
8864			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8865				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8866			}
8867			break;
8868
8869		case IPF_EXP_UDP_DPORT :
8870		case IPF_EXP_TCP_DPORT :
8871			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8872				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8873			}
8874			break;
8875
8876		case IPF_EXP_TCP_FLAGS :
8877			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8878				rv |= ((fin->fin_tcpf &
8879					e->ipfe_arg0[i * 2 + 1]) ==
8880				       e->ipfe_arg0[i * 2]);
8881			}
8882			break;
8883		}
8884		rv ^= e->ipfe_not;
8885
8886		if (rv == 0)
8887			break;
8888	}
8889
8890	return rv;
8891}
8892
8893
8894/* ------------------------------------------------------------------------ */
8895/* Function:    ipf_queueflush                                              */
8896/* Returns:     int - number of entries flushed (0 = none)                  */
8897/* Parameters:  softc(I)    - pointer to soft context main structure        */
8898/*              deletefn(I) - function to call to delete entry              */
8899/*              ipfqs(I)    - top of the list of ipf internal queues        */
8900/*              userqs(I)   - top of the list of user defined timeouts      */
8901/*                                                                          */
8902/* This fucntion gets called when the state/NAT hash tables fill up and we  */
8903/* need to try a bit harder to free up some space.  The algorithm used here */
8904/* split into two parts but both halves have the same goal: to reduce the   */
8905/* number of connections considered to be "active" to the low watermark.    */
8906/* There are two steps in doing this:                                       */
8907/* 1) Remove any TCP connections that are already considered to be "closed" */
8908/*    but have not yet been removed from the state table.  The two states   */
8909/*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8910/*    candidates for this style of removal.  If freeing up entries in       */
8911/*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8912/*    we do not go on to step 2.                                            */
8913/*                                                                          */
8914/* 2) Look for the oldest entries on each timeout queue and free them if    */
8915/*    they are within the given window we are considering.  Where the       */
8916/*    window starts and the steps taken to increase its size depend upon    */
8917/*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8918/*    last 30 seconds is not touched.                                       */
8919/*                                              touched                     */
8920/*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8921/*           |          |        |           |     |     |                  */
8922/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8923/*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8924/*                                                                          */
8925/* Points to note:                                                          */
8926/* - tqe_die is the time, in the future, when entries die.                  */
8927/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8928/*   ticks.                                                                 */
8929/* - tqe_touched is when the entry was last used by NAT/state               */
8930/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8931/*   ipf_ticks any given timeout queue and vice versa.                      */
8932/* - both tqe_die and tqe_touched increase over time                        */
8933/* - timeout queues are sorted with the highest value of tqe_die at the     */
8934/*   bottom and therefore the smallest values of each are at the top        */
8935/* - the pointer passed in as ipfqs should point to an array of timeout     */
8936/*   queues representing each of the TCP states                             */
8937/*                                                                          */
8938/* We start by setting up a maximum range to scan for things to move of     */
8939/* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8940/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8941/* we start again with a new value for "iend" and "istart".  This is        */
8942/* continued until we either finish the scan of 30 second intervals or the  */
8943/* low water mark is reached.                                               */
8944/* ------------------------------------------------------------------------ */
8945int
8946ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8947	ipf_main_softc_t *softc;
8948	ipftq_delete_fn_t deletefn;
8949	ipftq_t *ipfqs, *userqs;
8950	u_int *activep;
8951	int size, low;
8952{
8953	u_long interval, istart, iend;
8954	ipftq_t *ifq, *ifqnext;
8955	ipftqent_t *tqe, *tqn;
8956	int removed = 0;
8957
8958	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8959		tqn = tqe->tqe_next;
8960		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8961			removed++;
8962	}
8963	if ((*activep * 100 / size) > low) {
8964		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8965		     ((tqe = tqn) != NULL); ) {
8966			tqn = tqe->tqe_next;
8967			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8968				removed++;
8969		}
8970	}
8971
8972	if ((*activep * 100 / size) <= low) {
8973		return removed;
8974	}
8975
8976	/*
8977	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8978	 *       used then the operations are upgraded to floating point
8979	 *       and kernels don't like floating point...
8980	 */
8981	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8982		istart = IPF_TTLVAL(86400 * 4);
8983		interval = IPF_TTLVAL(43200);
8984	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8985		istart = IPF_TTLVAL(43200);
8986		interval = IPF_TTLVAL(1800);
8987	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8988		istart = IPF_TTLVAL(1800);
8989		interval = IPF_TTLVAL(30);
8990	} else {
8991		return 0;
8992	}
8993	if (istart > softc->ipf_ticks) {
8994		if (softc->ipf_ticks - interval < interval)
8995			istart = interval;
8996		else
8997			istart = (softc->ipf_ticks / interval) * interval;
8998	}
8999
9000	iend = softc->ipf_ticks - interval;
9001
9002	while ((*activep * 100 / size) > low) {
9003		u_long try;
9004
9005		try = softc->ipf_ticks - istart;
9006
9007		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9008			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9009				if (try < tqe->tqe_touched)
9010					break;
9011				tqn = tqe->tqe_next;
9012				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9013					removed++;
9014			}
9015		}
9016
9017		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9018			ifqnext = ifq->ifq_next;
9019
9020			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9021				if (try < tqe->tqe_touched)
9022					break;
9023				tqn = tqe->tqe_next;
9024				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9025					removed++;
9026			}
9027		}
9028
9029		if (try >= iend) {
9030			if (interval == IPF_TTLVAL(43200)) {
9031				interval = IPF_TTLVAL(1800);
9032			} else if (interval == IPF_TTLVAL(1800)) {
9033				interval = IPF_TTLVAL(30);
9034			} else {
9035				break;
9036			}
9037			if (interval >= softc->ipf_ticks)
9038				break;
9039
9040			iend = softc->ipf_ticks - interval;
9041		}
9042		istart -= interval;
9043	}
9044
9045	return removed;
9046}
9047
9048
9049/* ------------------------------------------------------------------------ */
9050/* Function:    ipf_deliverlocal                                            */
9051/* Returns:     int - 1 = local address, 0 = non-local address              */
9052/* Parameters:  softc(I)     - pointer to soft context main structure       */
9053/*              ipversion(I) - IP protocol version (4 or 6)                 */
9054/*              ifp(I)       - network interface pointer                    */
9055/*              ipaddr(I)    - IPv4/6 destination address                   */
9056/*                                                                          */
9057/* This fucntion is used to determine in the address "ipaddr" belongs to    */
9058/* the network interface represented by ifp.                                */
9059/* ------------------------------------------------------------------------ */
9060int
9061ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9062	ipf_main_softc_t *softc;
9063	int ipversion;
9064	void *ifp;
9065	i6addr_t *ipaddr;
9066{
9067	i6addr_t addr;
9068	int islocal = 0;
9069
9070	if (ipversion == 4) {
9071		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9072			if (addr.in4.s_addr == ipaddr->in4.s_addr)
9073				islocal = 1;
9074		}
9075
9076#ifdef USE_INET6
9077	} else if (ipversion == 6) {
9078		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9079			if (IP6_EQ(&addr, ipaddr))
9080				islocal = 1;
9081		}
9082#endif
9083	}
9084
9085	return islocal;
9086}
9087
9088
9089/* ------------------------------------------------------------------------ */
9090/* Function:    ipf_settimeout                                              */
9091/* Returns:     int - 0 = success, -1 = failure                             */
9092/* Parameters:  softc(I) - pointer to soft context main structure           */
9093/*              t(I)     - pointer to tuneable array entry                  */
9094/*              p(I)     - pointer to values passed in to apply             */
9095/*                                                                          */
9096/* This function is called to set the timeout values for each distinct      */
9097/* queue timeout that is available.  When called, it calls into both the    */
9098/* state and NAT code, telling them to update their timeout queues.         */
9099/* ------------------------------------------------------------------------ */
9100static int
9101ipf_settimeout(softc, t, p)
9102	struct ipf_main_softc_s *softc;
9103	ipftuneable_t *t;
9104	ipftuneval_t *p;
9105{
9106
9107	/*
9108	 * ipf_interror should be set by the functions called here, not
9109	 * by this function - it's just a middle man.
9110	 */
9111	if (ipf_state_settimeout(softc, t, p) == -1)
9112		return -1;
9113	if (ipf_nat_settimeout(softc, t, p) == -1)
9114		return -1;
9115	return 0;
9116}
9117
9118
9119/* ------------------------------------------------------------------------ */
9120/* Function:    ipf_apply_timeout                                           */
9121/* Returns:     int - 0 = success, -1 = failure                             */
9122/* Parameters:  head(I)    - pointer to tuneable array entry                */
9123/*              seconds(I) - pointer to values passed in to apply           */
9124/*                                                                          */
9125/* This function applies a timeout of "seconds" to the timeout queue that   */
9126/* is pointed to by "head".  All entries on this list have an expiration    */
9127/* set to be the current tick value of ipf plus the ttl.  Given that this   */
9128/* function should only be called when the delta is non-zero, the task is   */
9129/* to walk the entire list and apply the change.  The sort order will not   */
9130/* change.  The only catch is that this is O(n) across the list, so if the  */
9131/* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9132/* could take a relatively long time to work through them all.              */
9133/* ------------------------------------------------------------------------ */
9134void
9135ipf_apply_timeout(head, seconds)
9136	ipftq_t *head;
9137	u_int seconds;
9138{
9139	u_int oldtimeout, newtimeout;
9140	ipftqent_t *tqe;
9141	int delta;
9142
9143	MUTEX_ENTER(&head->ifq_lock);
9144	oldtimeout = head->ifq_ttl;
9145	newtimeout = IPF_TTLVAL(seconds);
9146	delta = oldtimeout - newtimeout;
9147
9148	head->ifq_ttl = newtimeout;
9149
9150	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9151		tqe->tqe_die += delta;
9152	}
9153	MUTEX_EXIT(&head->ifq_lock);
9154}
9155
9156
9157/* ------------------------------------------------------------------------ */
9158/* Function:   ipf_settimeout_tcp                                           */
9159/* Returns:    int - 0 = successfully applied, -1 = failed                  */
9160/* Parameters: t(I)   - pointer to tuneable to change                       */
9161/*             p(I)   - pointer to new timeout information                  */
9162/*             tab(I) - pointer to table of TCP queues                      */
9163/*                                                                          */
9164/* This function applies the new timeout (p) to the TCP tunable (t) and     */
9165/* updates all of the entries on the relevant timeout queue by calling      */
9166/* ipf_apply_timeout().                                                     */
9167/* ------------------------------------------------------------------------ */
9168int
9169ipf_settimeout_tcp(t, p, tab)
9170	ipftuneable_t *t;
9171	ipftuneval_t *p;
9172	ipftq_t *tab;
9173{
9174	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9175	    !strcmp(t->ipft_name, "tcp_established")) {
9176		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9177	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9178		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9179	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9180		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9181	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9182		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9183		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9184		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9185	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
9186		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9187	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9188		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9189	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
9190		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9191	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9192		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9193	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9194		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9195	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
9196		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9197	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9198		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9199	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9200		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9201	} else {
9202		/*
9203		 * ipf_interror isn't set here because it should be set
9204		 * by whatever called this function.
9205		 */
9206		return -1;
9207	}
9208	return 0;
9209}
9210
9211
9212/* ------------------------------------------------------------------------ */
9213/* Function:   ipf_main_soft_create                                         */
9214/* Returns:    NULL = failure, else success                                 */
9215/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9216/*                                                                          */
9217/* Create the foundation soft context structure. In circumstances where it  */
9218/* is not required to dynamically allocate the context, a pointer can be    */
9219/* passed in (rather than NULL) to a structure to be initialised.           */
9220/* The main thing of interest is that a number of locks are initialised     */
9221/* here instead of in the where might be expected - in the relevant create  */
9222/* function elsewhere.  This is done because the current locking design has */
9223/* some areas where these locks are used outside of their module.           */
9224/* Possibly the most important exercise that is done here is setting of all */
9225/* the timeout values, allowing them to be changed before init().           */
9226/* ------------------------------------------------------------------------ */
9227void *
9228ipf_main_soft_create(arg)
9229	void *arg;
9230{
9231	ipf_main_softc_t *softc;
9232
9233	if (arg == NULL) {
9234		KMALLOC(softc, ipf_main_softc_t *);
9235		if (softc == NULL)
9236			return NULL;
9237	} else {
9238		softc = arg;
9239	}
9240
9241	bzero((char *)softc, sizeof(*softc));
9242
9243	/*
9244	 * This serves as a flag as to whether or not the softc should be
9245	 * free'd when _destroy is called.
9246	 */
9247	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9248
9249	softc->ipf_tuners = ipf_tune_array_copy(softc,
9250						sizeof(ipf_main_tuneables),
9251						ipf_main_tuneables);
9252	if (softc->ipf_tuners == NULL) {
9253		ipf_main_soft_destroy(softc);
9254		return NULL;
9255	}
9256
9257	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9258	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9259	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9260	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9261	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9262	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9263	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9264	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9265	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9266
9267	softc->ipf_token_head = NULL;
9268	softc->ipf_token_tail = &softc->ipf_token_head;
9269
9270	softc->ipf_tcpidletimeout = FIVE_DAYS;
9271	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9272	softc->ipf_tcplastack = IPF_TTLVAL(30);
9273	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9274	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9275	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9276	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9277	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9278	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9279	softc->ipf_udptimeout = IPF_TTLVAL(120);
9280	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9281	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9282	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9283	softc->ipf_iptimeout = IPF_TTLVAL(60);
9284
9285#if defined(IPFILTER_DEFAULT_BLOCK)
9286	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9287#else
9288	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9289#endif
9290	softc->ipf_minttl = 4;
9291	softc->ipf_icmpminfragmtu = 68;
9292	softc->ipf_flags = IPF_LOGGING;
9293
9294	return softc;
9295}
9296
9297/* ------------------------------------------------------------------------ */
9298/* Function:   ipf_main_soft_init                                           */
9299/* Returns:    0 = success, -1 = failure                                    */
9300/* Parameters: softc(I) - pointer to soft context main structure            */
9301/*                                                                          */
9302/* A null-op function that exists as a placeholder so that the flow in      */
9303/* other functions is obvious.                                              */
9304/* ------------------------------------------------------------------------ */
9305/*ARGSUSED*/
9306int
9307ipf_main_soft_init(softc)
9308	ipf_main_softc_t *softc;
9309{
9310	return 0;
9311}
9312
9313
9314/* ------------------------------------------------------------------------ */
9315/* Function:   ipf_main_soft_destroy                                        */
9316/* Returns:    void                                                         */
9317/* Parameters: softc(I) - pointer to soft context main structure            */
9318/*                                                                          */
9319/* Undo everything that we did in ipf_main_soft_create.                     */
9320/*                                                                          */
9321/* The most important check that needs to be made here is whether or not    */
9322/* the structure was allocated by ipf_main_soft_create() by checking what   */
9323/* value is stored in ipf_dynamic_main.                                     */
9324/* ------------------------------------------------------------------------ */
9325/*ARGSUSED*/
9326void
9327ipf_main_soft_destroy(softc)
9328	ipf_main_softc_t *softc;
9329{
9330
9331	RW_DESTROY(&softc->ipf_frag);
9332	RW_DESTROY(&softc->ipf_poolrw);
9333	RW_DESTROY(&softc->ipf_nat);
9334	RW_DESTROY(&softc->ipf_state);
9335	RW_DESTROY(&softc->ipf_tokens);
9336	RW_DESTROY(&softc->ipf_mutex);
9337	RW_DESTROY(&softc->ipf_global);
9338	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9339	MUTEX_DESTROY(&softc->ipf_rw);
9340
9341	if (softc->ipf_tuners != NULL) {
9342		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9343	}
9344	if (softc->ipf_dynamic_softc == 1) {
9345		KFREE(softc);
9346	}
9347}
9348
9349
9350/* ------------------------------------------------------------------------ */
9351/* Function:   ipf_main_soft_fini                                           */
9352/* Returns:    0 = success, -1 = failure                                    */
9353/* Parameters: softc(I) - pointer to soft context main structure            */
9354/*                                                                          */
9355/* Clean out the rules which have been added since _init was last called,   */
9356/* the only dynamic part of the mainline.                                   */
9357/* ------------------------------------------------------------------------ */
9358int
9359ipf_main_soft_fini(softc)
9360	ipf_main_softc_t *softc;
9361{
9362	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9363	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9364	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9365	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9366
9367	return 0;
9368}
9369
9370
9371/* ------------------------------------------------------------------------ */
9372/* Function:   ipf_main_load                                                */
9373/* Returns:    0 = success, -1 = failure                                    */
9374/* Parameters: none                                                         */
9375/*                                                                          */
9376/* Handle global initialisation that needs to be done for the base part of  */
9377/* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9378/* arrays that get used by the state/NAT code.                              */
9379/* ------------------------------------------------------------------------ */
9380int
9381ipf_main_load()
9382{
9383	int i;
9384
9385	/* fill icmp reply type table */
9386	for (i = 0; i <= ICMP_MAXTYPE; i++)
9387		icmpreplytype4[i] = -1;
9388	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9389	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9390	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9391	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9392
9393#ifdef  USE_INET6
9394	/* fill icmp reply type table */
9395	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9396		icmpreplytype6[i] = -1;
9397	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9398	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9399	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9400	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9401	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9402#endif
9403
9404	return 0;
9405}
9406
9407
9408/* ------------------------------------------------------------------------ */
9409/* Function:   ipf_main_unload                                              */
9410/* Returns:    0 = success, -1 = failure                                    */
9411/* Parameters: none                                                         */
9412/*                                                                          */
9413/* A null-op function that exists as a placeholder so that the flow in      */
9414/* other functions is obvious.                                              */
9415/* ------------------------------------------------------------------------ */
9416int
9417ipf_main_unload()
9418{
9419	return 0;
9420}
9421
9422
9423/* ------------------------------------------------------------------------ */
9424/* Function:   ipf_load_all                                                 */
9425/* Returns:    0 = success, -1 = failure                                    */
9426/* Parameters: none                                                         */
9427/*                                                                          */
9428/* Work through all of the subsystems inside IPFilter and call the load     */
9429/* function for each in an order that won't lead to a crash :)              */
9430/* ------------------------------------------------------------------------ */
9431int
9432ipf_load_all()
9433{
9434	if (ipf_main_load() == -1)
9435		return -1;
9436
9437	if (ipf_state_main_load() == -1)
9438		return -1;
9439
9440	if (ipf_nat_main_load() == -1)
9441		return -1;
9442
9443	if (ipf_frag_main_load() == -1)
9444		return -1;
9445
9446	if (ipf_auth_main_load() == -1)
9447		return -1;
9448
9449	if (ipf_proxy_main_load() == -1)
9450		return -1;
9451
9452	return 0;
9453}
9454
9455
9456/* ------------------------------------------------------------------------ */
9457/* Function:   ipf_unload_all                                               */
9458/* Returns:    0 = success, -1 = failure                                    */
9459/* Parameters: none                                                         */
9460/*                                                                          */
9461/* Work through all of the subsystems inside IPFilter and call the unload   */
9462/* function for each in an order that won't lead to a crash :)              */
9463/* ------------------------------------------------------------------------ */
9464int
9465ipf_unload_all()
9466{
9467	if (ipf_proxy_main_unload() == -1)
9468		return -1;
9469
9470	if (ipf_auth_main_unload() == -1)
9471		return -1;
9472
9473	if (ipf_frag_main_unload() == -1)
9474		return -1;
9475
9476	if (ipf_nat_main_unload() == -1)
9477		return -1;
9478
9479	if (ipf_state_main_unload() == -1)
9480		return -1;
9481
9482	if (ipf_main_unload() == -1)
9483		return -1;
9484
9485	return 0;
9486}
9487
9488
9489/* ------------------------------------------------------------------------ */
9490/* Function:   ipf_create_all                                               */
9491/* Returns:    NULL = failure, else success                                 */
9492/* Parameters: arg(I) - pointer to soft context main structure              */
9493/*                                                                          */
9494/* Work through all of the subsystems inside IPFilter and call the create   */
9495/* function for each in an order that won't lead to a crash :)              */
9496/* ------------------------------------------------------------------------ */
9497ipf_main_softc_t *
9498ipf_create_all(arg)
9499	void *arg;
9500{
9501	ipf_main_softc_t *softc;
9502
9503	softc = ipf_main_soft_create(arg);
9504	if (softc == NULL)
9505		return NULL;
9506
9507#ifdef IPFILTER_LOG
9508	softc->ipf_log_soft = ipf_log_soft_create(softc);
9509	if (softc->ipf_log_soft == NULL) {
9510		ipf_destroy_all(softc);
9511		return NULL;
9512	}
9513#endif
9514
9515	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9516	if (softc->ipf_lookup_soft == NULL) {
9517		ipf_destroy_all(softc);
9518		return NULL;
9519	}
9520
9521	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9522	if (softc->ipf_sync_soft == NULL) {
9523		ipf_destroy_all(softc);
9524		return NULL;
9525	}
9526
9527	softc->ipf_state_soft = ipf_state_soft_create(softc);
9528	if (softc->ipf_state_soft == NULL) {
9529		ipf_destroy_all(softc);
9530		return NULL;
9531	}
9532
9533	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9534	if (softc->ipf_nat_soft == NULL) {
9535		ipf_destroy_all(softc);
9536		return NULL;
9537	}
9538
9539	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9540	if (softc->ipf_frag_soft == NULL) {
9541		ipf_destroy_all(softc);
9542		return NULL;
9543	}
9544
9545	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9546	if (softc->ipf_auth_soft == NULL) {
9547		ipf_destroy_all(softc);
9548		return NULL;
9549	}
9550
9551	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9552	if (softc->ipf_proxy_soft == NULL) {
9553		ipf_destroy_all(softc);
9554		return NULL;
9555	}
9556
9557	return softc;
9558}
9559
9560
9561/* ------------------------------------------------------------------------ */
9562/* Function:   ipf_destroy_all                                              */
9563/* Returns:    void                                                         */
9564/* Parameters: softc(I) - pointer to soft context main structure            */
9565/*                                                                          */
9566/* Work through all of the subsystems inside IPFilter and call the destroy  */
9567/* function for each in an order that won't lead to a crash :)              */
9568/*                                                                          */
9569/* Every one of these functions is expected to succeed, so there is no      */
9570/* checking of return values.                                               */
9571/* ------------------------------------------------------------------------ */
9572void
9573ipf_destroy_all(softc)
9574	ipf_main_softc_t *softc;
9575{
9576
9577	if (softc->ipf_state_soft != NULL) {
9578		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9579		softc->ipf_state_soft = NULL;
9580	}
9581
9582	if (softc->ipf_nat_soft != NULL) {
9583		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9584		softc->ipf_nat_soft = NULL;
9585	}
9586
9587	if (softc->ipf_frag_soft != NULL) {
9588		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9589		softc->ipf_frag_soft = NULL;
9590	}
9591
9592	if (softc->ipf_auth_soft != NULL) {
9593		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9594		softc->ipf_auth_soft = NULL;
9595	}
9596
9597	if (softc->ipf_proxy_soft != NULL) {
9598		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9599		softc->ipf_proxy_soft = NULL;
9600	}
9601
9602	if (softc->ipf_sync_soft != NULL) {
9603		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9604		softc->ipf_sync_soft = NULL;
9605	}
9606
9607	if (softc->ipf_lookup_soft != NULL) {
9608		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9609		softc->ipf_lookup_soft = NULL;
9610	}
9611
9612#ifdef IPFILTER_LOG
9613	if (softc->ipf_log_soft != NULL) {
9614		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9615		softc->ipf_log_soft = NULL;
9616	}
9617#endif
9618
9619	ipf_main_soft_destroy(softc);
9620}
9621
9622
9623/* ------------------------------------------------------------------------ */
9624/* Function:   ipf_init_all                                                 */
9625/* Returns:    0 = success, -1 = failure                                    */
9626/* Parameters: softc(I) - pointer to soft context main structure            */
9627/*                                                                          */
9628/* Work through all of the subsystems inside IPFilter and call the init     */
9629/* function for each in an order that won't lead to a crash :)              */
9630/* ------------------------------------------------------------------------ */
9631int
9632ipf_init_all(softc)
9633	ipf_main_softc_t *softc;
9634{
9635
9636	if (ipf_main_soft_init(softc) == -1)
9637		return -1;
9638
9639#ifdef IPFILTER_LOG
9640	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9641		return -1;
9642#endif
9643
9644	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9645		return -1;
9646
9647	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9648		return -1;
9649
9650	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9651		return -1;
9652
9653	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9654		return -1;
9655
9656	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9657		return -1;
9658
9659	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9660		return -1;
9661
9662	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9663		return -1;
9664
9665	return 0;
9666}
9667
9668
9669/* ------------------------------------------------------------------------ */
9670/* Function:   ipf_fini_all                                                 */
9671/* Returns:    0 = success, -1 = failure                                    */
9672/* Parameters: softc(I) - pointer to soft context main structure            */
9673/*                                                                          */
9674/* Work through all of the subsystems inside IPFilter and call the fini     */
9675/* function for each in an order that won't lead to a crash :)              */
9676/* ------------------------------------------------------------------------ */
9677int
9678ipf_fini_all(softc)
9679	ipf_main_softc_t *softc;
9680{
9681
9682	ipf_token_flush(softc);
9683
9684	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9685		return -1;
9686
9687	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9688		return -1;
9689
9690	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9691		return -1;
9692
9693	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9694		return -1;
9695
9696	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9697		return -1;
9698
9699	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9700		return -1;
9701
9702	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9703		return -1;
9704
9705#ifdef IPFILTER_LOG
9706	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9707		return -1;
9708#endif
9709
9710	if (ipf_main_soft_fini(softc) == -1)
9711		return -1;
9712
9713	return 0;
9714}
9715
9716
9717/* ------------------------------------------------------------------------ */
9718/* Function:    ipf_rule_expire                                             */
9719/* Returns:     Nil                                                         */
9720/* Parameters:  softc(I) - pointer to soft context main structure           */
9721/*                                                                          */
9722/* At present this function exists just to support temporary addition of    */
9723/* firewall rules. Both inactive and active lists are scanned for items to  */
9724/* purge, as by rights, the expiration is computed as soon as the rule is   */
9725/* loaded in.                                                               */
9726/* ------------------------------------------------------------------------ */
9727void
9728ipf_rule_expire(softc)
9729	ipf_main_softc_t *softc;
9730{
9731	frentry_t *fr;
9732
9733	if ((softc->ipf_rule_explist[0] == NULL) &&
9734	    (softc->ipf_rule_explist[1] == NULL))
9735		return;
9736
9737	WRITE_ENTER(&softc->ipf_mutex);
9738
9739	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9740		/*
9741		 * Because the list is kept sorted on insertion, the fist
9742		 * one that dies in the future means no more work to do.
9743		 */
9744		if (fr->fr_die > softc->ipf_ticks)
9745			break;
9746		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9747	}
9748
9749	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9750		/*
9751		 * Because the list is kept sorted on insertion, the fist
9752		 * one that dies in the future means no more work to do.
9753		 */
9754		if (fr->fr_die > softc->ipf_ticks)
9755			break;
9756		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9757	}
9758
9759	RWLOCK_EXIT(&softc->ipf_mutex);
9760}
9761
9762
9763static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9764static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9765				      i6addr_t *));
9766
9767host_node_t RBI_ZERO(ipf_rb);
9768RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9769
9770
9771/* ------------------------------------------------------------------------ */
9772/* Function:    ipf_ht_node_cmp                                             */
9773/* Returns:     int   - 0 == nodes are the same, ..                         */
9774/* Parameters:  k1(I) - pointer to first key to compare                     */
9775/*              k2(I) - pointer to second key to compare                    */
9776/*                                                                          */
9777/* The "key" for the node is a combination of two fields: the address       */
9778/* family and the address itself.                                           */
9779/*                                                                          */
9780/* Because we're not actually interpreting the address data, it isn't       */
9781/* necessary to convert them to/from network/host byte order. The mask is   */
9782/* just used to remove bits that aren't significant - it doesn't matter     */
9783/* where they are, as long as they're always in the same place.             */
9784/*                                                                          */
9785/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9786/* this is where individual ones will differ the most - but not true for    */
9787/* for /48's, etc.                                                          */
9788/* ------------------------------------------------------------------------ */
9789static int
9790ipf_ht_node_cmp(k1, k2)
9791	struct host_node_s *k1, *k2;
9792{
9793	int i;
9794
9795	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9796	if (i != 0)
9797		return i;
9798
9799	if (k1->hn_addr.adf_family == AF_INET)
9800		return (k2->hn_addr.adf_addr.in4.s_addr -
9801			k1->hn_addr.adf_addr.in4.s_addr);
9802
9803	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9804	if (i != 0)
9805		return i;
9806	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9807	if (i != 0)
9808		return i;
9809	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9810	if (i != 0)
9811		return i;
9812	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9813	return i;
9814}
9815
9816
9817/* ------------------------------------------------------------------------ */
9818/* Function:    ipf_ht_node_make_key                                        */
9819/* Returns:     Nil                                                         */
9820/* parameters:  htp(I)    - pointer to address tracking structure           */
9821/*              key(I)    - where to store masked address for lookup        */
9822/*              family(I) - protocol family of address                      */
9823/*              addr(I)   - pointer to network address                      */
9824/*                                                                          */
9825/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9826/* copy the address passed in into the key structure whilst masking out the */
9827/* bits that we don't want.                                                 */
9828/*                                                                          */
9829/* Because the parser will set ht_netmask to 128 if there is no protocol    */
9830/* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9831/* have to be wary of that and not allow 32-128 to happen.                  */
9832/* ------------------------------------------------------------------------ */
9833static void
9834ipf_ht_node_make_key(htp, key, family, addr)
9835	host_track_t *htp;
9836	host_node_t *key;
9837	int family;
9838	i6addr_t *addr;
9839{
9840	key->hn_addr.adf_family = family;
9841	if (family == AF_INET) {
9842		u_32_t mask;
9843		int bits;
9844
9845		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9846		bits = htp->ht_netmask;
9847		if (bits >= 32) {
9848			mask = 0xffffffff;
9849		} else {
9850			mask = htonl(0xffffffff << (32 - bits));
9851		}
9852		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9853#ifdef USE_INET6
9854	} else {
9855		int bits = htp->ht_netmask;
9856
9857		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9858		if (bits > 96) {
9859			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9860					     htonl(0xffffffff << (128 - bits));
9861			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9862			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9863			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9864		} else if (bits > 64) {
9865			key->hn_addr.adf_addr.i6[3] = 0;
9866			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9867					     htonl(0xffffffff << (96 - bits));
9868			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9869			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9870		} else if (bits > 32) {
9871			key->hn_addr.adf_addr.i6[3] = 0;
9872			key->hn_addr.adf_addr.i6[2] = 0;
9873			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9874					     htonl(0xffffffff << (64 - bits));
9875			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9876		} else {
9877			key->hn_addr.adf_addr.i6[3] = 0;
9878			key->hn_addr.adf_addr.i6[2] = 0;
9879			key->hn_addr.adf_addr.i6[1] = 0;
9880			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9881					     htonl(0xffffffff << (32 - bits));
9882		}
9883#endif
9884	}
9885}
9886
9887
9888/* ------------------------------------------------------------------------ */
9889/* Function:    ipf_ht_node_add                                             */
9890/* Returns:     int       - 0 == success,  -1 == failure                    */
9891/* Parameters:  softc(I)  - pointer to soft context main structure          */
9892/*              htp(I)    - pointer to address tracking structure           */
9893/*              family(I) - protocol family of address                      */
9894/*              addr(I)   - pointer to network address                      */
9895/*                                                                          */
9896/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9897/*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9898/*                                                                          */
9899/* After preparing the key with the address information to find, look in    */
9900/* the red-black tree to see if the address is known. A successful call to  */
9901/* this function can mean one of two things: a new node was added to the    */
9902/* tree or a matching node exists and we're able to bump up its activity.   */
9903/* ------------------------------------------------------------------------ */
9904int
9905ipf_ht_node_add(softc, htp, family, addr)
9906	ipf_main_softc_t *softc;
9907	host_track_t *htp;
9908	int family;
9909	i6addr_t *addr;
9910{
9911	host_node_t *h;
9912	host_node_t k;
9913
9914	ipf_ht_node_make_key(htp, &k, family, addr);
9915
9916	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9917	if (h == NULL) {
9918		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9919			return -1;
9920		KMALLOC(h, host_node_t *);
9921		if (h == NULL) {
9922			DT(ipf_rb_no_mem);
9923			LBUMP(ipf_rb_no_mem);
9924			return -1;
9925		}
9926
9927		/*
9928		 * If there was a macro to initialise the RB node then that
9929		 * would get used here, but there isn't...
9930		 */
9931		bzero((char *)h, sizeof(*h));
9932		h->hn_addr = k.hn_addr;
9933		h->hn_addr.adf_family = k.hn_addr.adf_family;
9934		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9935		htp->ht_cur_nodes++;
9936	} else {
9937		if ((htp->ht_max_per_node != 0) &&
9938		    (h->hn_active >= htp->ht_max_per_node)) {
9939			DT(ipf_rb_node_max);
9940			LBUMP(ipf_rb_node_max);
9941			return -1;
9942		}
9943	}
9944
9945	h->hn_active++;
9946
9947	return 0;
9948}
9949
9950
9951/* ------------------------------------------------------------------------ */
9952/* Function:    ipf_ht_node_del                                             */
9953/* Returns:     int       - 0 == success,  -1 == failure                    */
9954/* parameters:  htp(I)    - pointer to address tracking structure           */
9955/*              family(I) - protocol family of address                      */
9956/*              addr(I)   - pointer to network address                      */
9957/*                                                                          */
9958/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9959/*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9960/*                                                                          */
9961/* Try and find the address passed in amongst the leavese on this tree to   */
9962/* be friend. If found then drop the active account for that node drops by  */
9963/* one. If that count reaches 0, it is time to free it all up.              */
9964/* ------------------------------------------------------------------------ */
9965int
9966ipf_ht_node_del(htp, family, addr)
9967	host_track_t *htp;
9968	int family;
9969	i6addr_t *addr;
9970{
9971	host_node_t *h;
9972	host_node_t k;
9973
9974	ipf_ht_node_make_key(htp, &k, family, addr);
9975
9976	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9977	if (h == NULL) {
9978		return -1;
9979	} else {
9980		h->hn_active--;
9981		if (h->hn_active == 0) {
9982			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9983			htp->ht_cur_nodes--;
9984			KFREE(h);
9985		}
9986	}
9987
9988	return 0;
9989}
9990
9991
9992/* ------------------------------------------------------------------------ */
9993/* Function:    ipf_rb_ht_init                                              */
9994/* Returns:     Nil                                                         */
9995/* Parameters:  head(I) - pointer to host tracking structure                */
9996/*                                                                          */
9997/* Initialise the host tracking structure to be ready for use above.        */
9998/* ------------------------------------------------------------------------ */
9999void
10000ipf_rb_ht_init(head)
10001	host_track_t *head;
10002{
10003	RBI_INIT(ipf_rb, &head->ht_root);
10004}
10005
10006
10007/* ------------------------------------------------------------------------ */
10008/* Function:    ipf_rb_ht_freenode                                          */
10009/* Returns:     Nil                                                         */
10010/* Parameters:  head(I) - pointer to host tracking structure                */
10011/*              arg(I)  - additional argument from walk caller              */
10012/*                                                                          */
10013/* Free an actual host_node_t structure.                                    */
10014/* ------------------------------------------------------------------------ */
10015void
10016ipf_rb_ht_freenode(node, arg)
10017	host_node_t *node;
10018	void *arg;
10019{
10020	KFREE(node);
10021}
10022
10023
10024/* ------------------------------------------------------------------------ */
10025/* Function:    ipf_rb_ht_flush                                             */
10026/* Returns:     Nil                                                         */
10027/* Parameters:  head(I) - pointer to host tracking structure                */
10028/*                                                                          */
10029/* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10030/* and free'ing each one.                                                   */
10031/* ------------------------------------------------------------------------ */
10032void
10033ipf_rb_ht_flush(head)
10034	host_track_t *head;
10035{
10036	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10037}
10038
10039
10040/* ------------------------------------------------------------------------ */
10041/* Function:    ipf_slowtimer                                               */
10042/* Returns:     Nil                                                         */
10043/* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10044/*                                                                          */
10045/* Slowly expire held state for fragments.  Timeouts are set * in           */
10046/* expectation of this being called twice per second.                       */
10047/* ------------------------------------------------------------------------ */
10048void
10049ipf_slowtimer(softc)
10050	ipf_main_softc_t *softc;
10051{
10052
10053	ipf_token_expire(softc);
10054	ipf_frag_expire(softc);
10055	ipf_state_expire(softc);
10056	ipf_nat_expire(softc);
10057	ipf_auth_expire(softc);
10058	ipf_lookup_expire(softc);
10059	ipf_rule_expire(softc);
10060	ipf_sync_expire(softc);
10061	softc->ipf_ticks++;
10062}
10063
10064
10065/* ------------------------------------------------------------------------ */
10066/* Function:    ipf_inet_mask_add                                           */
10067/* Returns:     Nil                                                         */
10068/* Parameters:  bits(I) - pointer to nat context information                */
10069/*              mtab(I) - pointer to mask hash table structure              */
10070/*                                                                          */
10071/* When called, bits represents the mask of a new NAT rule that has just    */
10072/* been added. This function inserts a bitmask into the array of masks to   */
10073/* search when searching for a matching NAT rule for a packet.              */
10074/* Prevention of duplicate masks is achieved by checking the use count for  */
10075/* a given netmask.                                                         */
10076/* ------------------------------------------------------------------------ */
10077void
10078ipf_inet_mask_add(bits, mtab)
10079	int bits;
10080	ipf_v4_masktab_t *mtab;
10081{
10082	u_32_t mask;
10083	int i, j;
10084
10085	mtab->imt4_masks[bits]++;
10086	if (mtab->imt4_masks[bits] > 1)
10087		return;
10088
10089	if (bits == 0)
10090		mask = 0;
10091	else
10092		mask = 0xffffffff << (32 - bits);
10093
10094	for (i = 0; i < 33; i++) {
10095		if (ntohl(mtab->imt4_active[i]) < mask) {
10096			for (j = 32; j > i; j--)
10097				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10098			mtab->imt4_active[i] = htonl(mask);
10099			break;
10100		}
10101	}
10102	mtab->imt4_max++;
10103}
10104
10105
10106/* ------------------------------------------------------------------------ */
10107/* Function:    ipf_inet_mask_del                                           */
10108/* Returns:     Nil                                                         */
10109/* Parameters:  bits(I) - number of bits set in the netmask                 */
10110/*              mtab(I) - pointer to mask hash table structure              */
10111/*                                                                          */
10112/* Remove the 32bit bitmask represented by "bits" from the collection of    */
10113/* netmasks stored inside of mtab.                                          */
10114/* ------------------------------------------------------------------------ */
10115void
10116ipf_inet_mask_del(bits, mtab)
10117	int bits;
10118	ipf_v4_masktab_t *mtab;
10119{
10120	u_32_t mask;
10121	int i, j;
10122
10123	mtab->imt4_masks[bits]--;
10124	if (mtab->imt4_masks[bits] > 0)
10125		return;
10126
10127	mask = htonl(0xffffffff << (32 - bits));
10128	for (i = 0; i < 33; i++) {
10129		if (mtab->imt4_active[i] == mask) {
10130			for (j = i + 1; j < 33; j++)
10131				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10132			break;
10133		}
10134	}
10135	mtab->imt4_max--;
10136	ASSERT(mtab->imt4_max >= 0);
10137}
10138
10139
10140#ifdef USE_INET6
10141/* ------------------------------------------------------------------------ */
10142/* Function:    ipf_inet6_mask_add                                          */
10143/* Returns:     Nil                                                         */
10144/* Parameters:  bits(I) - number of bits set in mask                        */
10145/*              mask(I) - pointer to mask to add                            */
10146/*              mtab(I) - pointer to mask hash table structure              */
10147/*                                                                          */
10148/* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10149/* has just been added. This function inserts a bitmask into the array of   */
10150/* masks to search when searching for a matching NAT rule for a packet.     */
10151/* Prevention of duplicate masks is achieved by checking the use count for  */
10152/* a given netmask.                                                         */
10153/* ------------------------------------------------------------------------ */
10154void
10155ipf_inet6_mask_add(bits, mask, mtab)
10156	int bits;
10157	i6addr_t *mask;
10158	ipf_v6_masktab_t *mtab;
10159{
10160	i6addr_t zero;
10161	int i, j;
10162
10163	mtab->imt6_masks[bits]++;
10164	if (mtab->imt6_masks[bits] > 1)
10165		return;
10166
10167	if (bits == 0) {
10168		mask = &zero;
10169		zero.i6[0] = 0;
10170		zero.i6[1] = 0;
10171		zero.i6[2] = 0;
10172		zero.i6[3] = 0;
10173	}
10174
10175	for (i = 0; i < 129; i++) {
10176		if (IP6_LT(&mtab->imt6_active[i], mask)) {
10177			for (j = 128; j > i; j--)
10178				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10179			mtab->imt6_active[i] = *mask;
10180			break;
10181		}
10182	}
10183	mtab->imt6_max++;
10184}
10185
10186
10187/* ------------------------------------------------------------------------ */
10188/* Function:    ipf_inet6_mask_del                                          */
10189/* Returns:     Nil                                                         */
10190/* Parameters:  bits(I) - number of bits set in mask                        */
10191/*              mask(I) - pointer to mask to remove                         */
10192/*              mtab(I) - pointer to mask hash table structure              */
10193/*                                                                          */
10194/* Remove the 128bit bitmask represented by "bits" from the collection of   */
10195/* netmasks stored inside of mtab.                                          */
10196/* ------------------------------------------------------------------------ */
10197void
10198ipf_inet6_mask_del(bits, mask, mtab)
10199	int bits;
10200	i6addr_t *mask;
10201	ipf_v6_masktab_t *mtab;
10202{
10203	i6addr_t zero;
10204	int i, j;
10205
10206	mtab->imt6_masks[bits]--;
10207	if (mtab->imt6_masks[bits] > 0)
10208		return;
10209
10210	if (bits == 0)
10211		mask = &zero;
10212	zero.i6[0] = 0;
10213	zero.i6[1] = 0;
10214	zero.i6[2] = 0;
10215	zero.i6[3] = 0;
10216
10217	for (i = 0; i < 129; i++) {
10218		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10219			for (j = i + 1; j < 129; j++) {
10220				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10221				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10222					break;
10223			}
10224			break;
10225		}
10226	}
10227	mtab->imt6_max--;
10228	ASSERT(mtab->imt6_max >= 0);
10229}
10230
10231#ifdef	_KERNEL
10232static u_int
10233ipf_pcksum6(fin, ip6, off, len)
10234	fr_info_t *fin;
10235	ip6_t *ip6;
10236	u_int32_t off;
10237	u_int32_t len;
10238{
10239	struct mbuf *m;
10240	int sum;
10241
10242	m = fin->fin_m;
10243	if (m->m_len < sizeof(struct ip6_hdr)) {
10244		return 0xffff;
10245	}
10246
10247	sum = in6_cksum(m, ip6->ip6_nxt, off, len);
10248	return(sum);
10249}
10250#else
10251static u_int
10252ipf_pcksum6(fin, ip6, off, len)
10253	fr_info_t *fin;
10254	ip6_t *ip6;
10255	u_int32_t off;
10256	u_int32_t len;
10257{
10258	u_short *sp;
10259	u_int sum;
10260
10261	sp = (u_short *)&ip6->ip6_src;
10262	sum = *sp++;   /* ip6_src */
10263	sum += *sp++;
10264	sum += *sp++;
10265	sum += *sp++;
10266	sum += *sp++;
10267	sum += *sp++;
10268	sum += *sp++;
10269	sum += *sp++;
10270	sum += *sp++;   /* ip6_dst */
10271	sum += *sp++;
10272	sum += *sp++;
10273	sum += *sp++;
10274	sum += *sp++;
10275	sum += *sp++;
10276	sum += *sp++;
10277	sum += *sp++;
10278	return(ipf_pcksum(fin, off, sum));
10279}
10280#endif
10281#endif
10282