fil.c revision 350110
1/*	$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 350110 2019-07-18 11:43:09Z cy $	*/
2
3/*
4 * Copyright (C) 2012 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Copyright 2008 Sun Microsystems.
9 *
10 * $Id$
11 *
12 */
13#if defined(KERNEL) || defined(_KERNEL)
14# undef KERNEL
15# undef _KERNEL
16# define        KERNEL	1
17# define        _KERNEL	1
18#endif
19#include <sys/errno.h>
20#include <sys/types.h>
21#include <sys/param.h>
22#include <sys/time.h>
23#if defined(_KERNEL) && defined(__FreeBSD_version)
24#  if !defined(IPFILTER_LKM)
25#   include "opt_inet6.h"
26#  endif
27# include <sys/filio.h>
28#else
29# include <sys/ioctl.h>
30#endif
31#if defined(__SVR4) || defined(sun) /* SOLARIS */
32# include <sys/filio.h>
33#endif
34# include <sys/fcntl.h>
35#if defined(_KERNEL)
36# include <sys/systm.h>
37# include <sys/file.h>
38#else
39# include <stdio.h>
40# include <string.h>
41# include <stdlib.h>
42# include <stddef.h>
43# include <sys/file.h>
44# define _KERNEL
45# include <sys/uio.h>
46# undef _KERNEL
47#endif
48#if !defined(__SVR4)
49# include <sys/mbuf.h>
50#else
51#  include <sys/byteorder.h>
52# if (SOLARIS2 < 5) && defined(sun)
53#  include <sys/dditypes.h>
54# endif
55#endif
56# include <sys/protosw.h>
57#include <sys/socket.h>
58#include <net/if.h>
59#ifdef sun
60# include <net/af.h>
61#endif
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/tcp.h>
66# include <netinet/udp.h>
67# include <netinet/ip_icmp.h>
68#include "netinet/ip_compat.h"
69#ifdef	USE_INET6
70# include <netinet/icmp6.h>
71# if !SOLARIS && defined(_KERNEL)
72#  include <netinet6/in6_var.h>
73# endif
74#endif
75#include "netinet/ip_fil.h"
76#include "netinet/ip_nat.h"
77#include "netinet/ip_frag.h"
78#include "netinet/ip_state.h"
79#include "netinet/ip_proxy.h"
80#include "netinet/ip_auth.h"
81#ifdef IPFILTER_SCAN
82# include "netinet/ip_scan.h"
83#endif
84#include "netinet/ip_sync.h"
85#include "netinet/ip_lookup.h"
86#include "netinet/ip_pool.h"
87#include "netinet/ip_htable.h"
88#ifdef IPFILTER_COMPILED
89# include "netinet/ip_rules.h"
90#endif
91#if defined(IPFILTER_BPF) && defined(_KERNEL)
92# include <net/bpf.h>
93#endif
94#if defined(__FreeBSD_version)
95# include <sys/malloc.h>
96#endif
97#include "netinet/ipl.h"
98
99#if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100# include <sys/callout.h>
101extern struct callout ipf_slowtimer_ch;
102#endif
103/* END OF INCLUDES */
104
105#if !defined(lint)
106static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
107static const char rcsid[] = "@(#)$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 350110 2019-07-18 11:43:09Z cy $";
108/* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
109#endif
110
111#ifndef	_KERNEL
112# include "ipf.h"
113# include "ipt.h"
114extern	int	opts;
115extern	int	blockreason;
116#endif /* _KERNEL */
117
118#define	LBUMP(x)	softc->x++
119#define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
120
121static	INLINE int	ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122static	u_32_t		ipf_checkcipso __P((fr_info_t *, u_char *, int));
123static	u_32_t		ipf_checkripso __P((u_char *));
124static	u_32_t		ipf_decaps __P((fr_info_t *, u_32_t, int));
125#ifdef IPFILTER_LOG
126static	frentry_t	*ipf_dolog __P((fr_info_t *, u_32_t *));
127#endif
128static	int		ipf_flushlist __P((ipf_main_softc_t *, int *,
129					   frentry_t **));
130static	int		ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
131					      int));
132static	ipfunc_t	ipf_findfunc __P((ipfunc_t));
133static	void		*ipf_findlookup __P((ipf_main_softc_t *, int,
134					     frentry_t *,
135					     i6addr_t *, i6addr_t *));
136static	frentry_t	*ipf_firewall __P((fr_info_t *, u_32_t *));
137static	int		ipf_fr_matcharray __P((fr_info_t *, int *));
138static	int		ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
139					    void *));
140static	void		ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141static	int		ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142static	int		ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
143					 ipfgeniter_t *));
144static	void		ipf_getstat __P((ipf_main_softc_t *,
145					 struct friostat *, int));
146static	int		ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147static	void		ipf_group_free __P((frgroup_t *));
148static	int		ipf_grpmapfini __P((struct ipf_main_softc_s *,
149					    frentry_t *));
150static	int		ipf_grpmapinit __P((struct ipf_main_softc_s *,
151					    frentry_t *));
152static	frentry_t	*ipf_nextrule __P((ipf_main_softc_t *, int, int,
153					   frentry_t *, int));
154static	int		ipf_portcheck __P((frpcmp_t *, u_32_t));
155static	INLINE int	ipf_pr_ah __P((fr_info_t *));
156static	INLINE void	ipf_pr_esp __P((fr_info_t *));
157static	INLINE void	ipf_pr_gre __P((fr_info_t *));
158static	INLINE void	ipf_pr_udp __P((fr_info_t *));
159static	INLINE void	ipf_pr_tcp __P((fr_info_t *));
160static	INLINE void	ipf_pr_icmp __P((fr_info_t *));
161static	INLINE void	ipf_pr_ipv4hdr __P((fr_info_t *));
162static	INLINE void	ipf_pr_short __P((fr_info_t *, int));
163static	INLINE int	ipf_pr_tcpcommon __P((fr_info_t *));
164static	INLINE int	ipf_pr_udpcommon __P((fr_info_t *));
165static	void		ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
166					     int, int));
167static	void		ipf_rule_expire_insert __P((ipf_main_softc_t *,
168						    frentry_t *, int));
169static	int		ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
170					  void *));
171static	void		ipf_token_flush __P((ipf_main_softc_t *));
172static	void		ipf_token_unlink __P((ipf_main_softc_t *,
173					      ipftoken_t *));
174static	ipftuneable_t	*ipf_tune_findbyname __P((ipftuneable_t *,
175						  const char *));
176static	ipftuneable_t	*ipf_tune_findbycookie __P((ipftuneable_t **, void *,
177						    void **));
178static	int		ipf_updateipid __P((fr_info_t *));
179static	int		ipf_settimeout __P((struct ipf_main_softc_s *,
180					    struct ipftuneable *,
181					    ipftuneval_t *));
182#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, need_free = 0;
4480	enum {	OP_ADD,		/* add rule */
4481		OP_REM,		/* remove rule */
4482		OP_ZERO 	/* zero statistics and counters */ }
4483		addrem = OP_ADD;
4484	frentry_t frd, *fp, *f, **fprev, **ftail;
4485	void *ptr, *uptr, *cptr;
4486	u_int *p, *pp;
4487	frgroup_t *fg;
4488	char *group;
4489
4490	ptr = NULL;
4491	cptr = NULL;
4492	fg = NULL;
4493	fp = &frd;
4494	if (makecopy != 0) {
4495		bzero(fp, sizeof(frd));
4496		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4497		if (error) {
4498			return error;
4499		}
4500		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4501			IPFERROR(6);
4502			return EINVAL;
4503		}
4504		KMALLOCS(f, frentry_t *, fp->fr_size);
4505		if (f == NULL) {
4506			IPFERROR(131);
4507			return ENOMEM;
4508		}
4509		bzero(f, fp->fr_size);
4510		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4511				    fp->fr_size);
4512		if (error) {
4513			KFREES(f, fp->fr_size);
4514			return error;
4515		}
4516
4517		fp = f;
4518		f = NULL;
4519		fp->fr_next = NULL;
4520		fp->fr_dnext = NULL;
4521		fp->fr_pnext = NULL;
4522		fp->fr_pdnext = NULL;
4523		fp->fr_grp = NULL;
4524		fp->fr_grphead = NULL;
4525		fp->fr_icmpgrp = NULL;
4526		fp->fr_isc = (void *)-1;
4527		fp->fr_ptr = NULL;
4528		fp->fr_ref = 0;
4529		fp->fr_flags |= FR_COPIED;
4530	} else {
4531		fp = (frentry_t *)data;
4532		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4533			IPFERROR(7);
4534			return EINVAL;
4535		}
4536		fp->fr_flags &= ~FR_COPIED;
4537	}
4538
4539	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4540	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4541		IPFERROR(8);
4542		error = EINVAL;
4543		goto donenolock;
4544	}
4545
4546	family = fp->fr_family;
4547	uptr = fp->fr_data;
4548
4549	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4550	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4551		addrem = OP_ADD;	/* Add rule */
4552	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4553		addrem = OP_REM;		/* Remove rule */
4554	else if (req == (ioctlcmd_t)SIOCZRLST)
4555		addrem = OP_ZERO;	/* Zero statistics and counters */
4556	else {
4557		IPFERROR(9);
4558		error = EINVAL;
4559		goto donenolock;
4560	}
4561
4562	/*
4563	 * Only filter rules for IPv4 or IPv6 are accepted.
4564	 */
4565	if (family == AF_INET) {
4566		/*EMPTY*/;
4567#ifdef	USE_INET6
4568	} else if (family == AF_INET6) {
4569		/*EMPTY*/;
4570#endif
4571	} else if (family != 0) {
4572		IPFERROR(10);
4573		error = EINVAL;
4574		goto donenolock;
4575	}
4576
4577	/*
4578	 * If the rule is being loaded from user space, i.e. we had to copy it
4579	 * into kernel space, then do not trust the function pointer in the
4580	 * rule.
4581	 */
4582	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4583		if (ipf_findfunc(fp->fr_func) == NULL) {
4584			IPFERROR(11);
4585			error = ESRCH;
4586			goto donenolock;
4587		}
4588
4589		if (addrem == OP_ADD) {
4590			error = ipf_funcinit(softc, fp);
4591			if (error != 0)
4592				goto donenolock;
4593		}
4594	}
4595	if ((fp->fr_flags & FR_CALLNOW) &&
4596	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4597		IPFERROR(142);
4598		error = ESRCH;
4599		goto donenolock;
4600	}
4601	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4602	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4603		IPFERROR(143);
4604		error = ESRCH;
4605		goto donenolock;
4606	}
4607
4608	ptr = NULL;
4609	cptr = NULL;
4610
4611	if (FR_ISACCOUNT(fp->fr_flags))
4612		unit = IPL_LOGCOUNT;
4613
4614	/*
4615	 * Check that each group name in the rule has a start index that
4616	 * is valid.
4617	 */
4618	if (fp->fr_icmphead != -1) {
4619		if ((fp->fr_icmphead < 0) ||
4620		    (fp->fr_icmphead >= fp->fr_namelen)) {
4621			IPFERROR(136);
4622			error = EINVAL;
4623			goto donenolock;
4624		}
4625		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4626			fp->fr_names[fp->fr_icmphead] = '\0';
4627	}
4628
4629	if (fp->fr_grhead != -1) {
4630		if ((fp->fr_grhead < 0) ||
4631		    (fp->fr_grhead >= fp->fr_namelen)) {
4632			IPFERROR(137);
4633			error = EINVAL;
4634			goto donenolock;
4635		}
4636		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4637			fp->fr_names[fp->fr_grhead] = '\0';
4638	}
4639
4640	if (fp->fr_group != -1) {
4641		if ((fp->fr_group < 0) ||
4642		    (fp->fr_group >= fp->fr_namelen)) {
4643			IPFERROR(138);
4644			error = EINVAL;
4645			goto donenolock;
4646		}
4647		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4648			/*
4649			 * Allow loading rules that are in groups to cause
4650			 * them to be created if they don't already exit.
4651			 */
4652			group = FR_NAME(fp, fr_group);
4653			if (addrem == OP_ADD) {
4654				fg = ipf_group_add(softc, group, NULL,
4655						   fp->fr_flags, unit, set);
4656				fp->fr_grp = fg;
4657			} else {
4658				fg = ipf_findgroup(softc, group, unit,
4659						   set, NULL);
4660				if (fg == NULL) {
4661					IPFERROR(12);
4662					error = ESRCH;
4663					goto donenolock;
4664				}
4665			}
4666
4667			if (fg->fg_flags == 0) {
4668				fg->fg_flags = fp->fr_flags & FR_INOUT;
4669			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4670				IPFERROR(13);
4671				error = ESRCH;
4672				goto donenolock;
4673			}
4674		}
4675	} else {
4676		/*
4677		 * If a rule is going to be part of a group then it does
4678		 * not matter whether it is an in or out rule, but if it
4679		 * isn't in a group, then it does...
4680		 */
4681		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4682			IPFERROR(14);
4683			error = EINVAL;
4684			goto donenolock;
4685		}
4686	}
4687	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4688
4689	/*
4690	 * Work out which rule list this change is being applied to.
4691	 */
4692	ftail = NULL;
4693	fprev = NULL;
4694	if (unit == IPL_LOGAUTH) {
4695                if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4696		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4697		    (fp->fr_dif.fd_ptr != NULL) ||
4698		    (fp->fr_flags & FR_FASTROUTE)) {
4699			softc->ipf_interror = 145;
4700			error = EINVAL;
4701			goto donenolock;
4702		}
4703		fprev = ipf_auth_rulehead(softc);
4704	} else {
4705		if (FR_ISACCOUNT(fp->fr_flags))
4706			fprev = &softc->ipf_acct[in][set];
4707		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4708			fprev = &softc->ipf_rules[in][set];
4709	}
4710	if (fprev == NULL) {
4711		IPFERROR(15);
4712		error = ESRCH;
4713		goto donenolock;
4714	}
4715
4716	if (fg != NULL)
4717		fprev = &fg->fg_start;
4718
4719	/*
4720	 * Copy in extra data for the rule.
4721	 */
4722	if (fp->fr_dsize != 0) {
4723		if (makecopy != 0) {
4724			KMALLOCS(ptr, void *, fp->fr_dsize);
4725			if (ptr == NULL) {
4726				IPFERROR(16);
4727				error = ENOMEM;
4728				goto donenolock;
4729			}
4730
4731			/*
4732			 * The bcopy case is for when the data is appended
4733			 * to the rule by ipf_in_compat().
4734			 */
4735			if (uptr >= (void *)fp &&
4736			    uptr < (void *)((char *)fp + fp->fr_size)) {
4737				bcopy(uptr, ptr, fp->fr_dsize);
4738				error = 0;
4739			} else {
4740				error = COPYIN(uptr, ptr, fp->fr_dsize);
4741				if (error != 0) {
4742					IPFERROR(17);
4743					error = EFAULT;
4744					goto donenolock;
4745				}
4746			}
4747		} else {
4748			ptr = uptr;
4749		}
4750		fp->fr_data = ptr;
4751	} else {
4752		fp->fr_data = NULL;
4753	}
4754
4755	/*
4756	 * Perform per-rule type sanity checks of their members.
4757	 * All code after this needs to be aware that allocated memory
4758	 * may need to be free'd before exiting.
4759	 */
4760	switch (fp->fr_type & ~FR_T_BUILTIN)
4761	{
4762#if defined(IPFILTER_BPF)
4763	case FR_T_BPFOPC :
4764		if (fp->fr_dsize == 0) {
4765			IPFERROR(19);
4766			error = EINVAL;
4767			break;
4768		}
4769		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4770			IPFERROR(20);
4771			error = EINVAL;
4772			break;
4773		}
4774		break;
4775#endif
4776	case FR_T_IPF :
4777		/*
4778		 * Preparation for error case at the bottom of this function.
4779		 */
4780		if (fp->fr_datype == FRI_LOOKUP)
4781			fp->fr_dstptr = NULL;
4782		if (fp->fr_satype == FRI_LOOKUP)
4783			fp->fr_srcptr = NULL;
4784
4785		if (fp->fr_dsize != sizeof(fripf_t)) {
4786			IPFERROR(21);
4787			error = EINVAL;
4788			break;
4789		}
4790
4791		/*
4792		 * Allowing a rule with both "keep state" and "with oow" is
4793		 * pointless because adding a state entry to the table will
4794		 * fail with the out of window (oow) flag set.
4795		 */
4796		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4797			IPFERROR(22);
4798			error = EINVAL;
4799			break;
4800		}
4801
4802		switch (fp->fr_satype)
4803		{
4804		case FRI_BROADCAST :
4805		case FRI_DYNAMIC :
4806		case FRI_NETWORK :
4807		case FRI_NETMASKED :
4808		case FRI_PEERADDR :
4809			if (fp->fr_sifpidx < 0) {
4810				IPFERROR(23);
4811				error = EINVAL;
4812			}
4813			break;
4814		case FRI_LOOKUP :
4815			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4816						       &fp->fr_src6,
4817						       &fp->fr_smsk6);
4818			if (fp->fr_srcfunc == NULL) {
4819				IPFERROR(132);
4820				error = ESRCH;
4821				break;
4822			}
4823			break;
4824		case FRI_NORMAL :
4825			break;
4826		default :
4827			IPFERROR(133);
4828			error = EINVAL;
4829			break;
4830		}
4831		if (error != 0)
4832			break;
4833
4834		switch (fp->fr_datype)
4835		{
4836		case FRI_BROADCAST :
4837		case FRI_DYNAMIC :
4838		case FRI_NETWORK :
4839		case FRI_NETMASKED :
4840		case FRI_PEERADDR :
4841			if (fp->fr_difpidx < 0) {
4842				IPFERROR(24);
4843				error = EINVAL;
4844			}
4845			break;
4846		case FRI_LOOKUP :
4847			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4848						       &fp->fr_dst6,
4849						       &fp->fr_dmsk6);
4850			if (fp->fr_dstfunc == NULL) {
4851				IPFERROR(134);
4852				error = ESRCH;
4853			}
4854			break;
4855		case FRI_NORMAL :
4856			break;
4857		default :
4858			IPFERROR(135);
4859			error = EINVAL;
4860		}
4861		break;
4862
4863	case FR_T_NONE :
4864	case FR_T_CALLFUNC :
4865	case FR_T_COMPIPF :
4866		break;
4867
4868	case FR_T_IPFEXPR :
4869		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4870			IPFERROR(25);
4871			error = EINVAL;
4872		}
4873		break;
4874
4875	default :
4876		IPFERROR(26);
4877		error = EINVAL;
4878		break;
4879	}
4880	if (error != 0)
4881		goto donenolock;
4882
4883	if (fp->fr_tif.fd_name != -1) {
4884		if ((fp->fr_tif.fd_name < 0) ||
4885		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4886			IPFERROR(139);
4887			error = EINVAL;
4888			goto donenolock;
4889		}
4890	}
4891
4892	if (fp->fr_dif.fd_name != -1) {
4893		if ((fp->fr_dif.fd_name < 0) ||
4894		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4895			IPFERROR(140);
4896			error = EINVAL;
4897			goto donenolock;
4898		}
4899	}
4900
4901	if (fp->fr_rif.fd_name != -1) {
4902		if ((fp->fr_rif.fd_name < 0) ||
4903		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4904			IPFERROR(141);
4905			error = EINVAL;
4906			goto donenolock;
4907		}
4908	}
4909
4910	/*
4911	 * Lookup all the interface names that are part of the rule.
4912	 */
4913	error = ipf_synclist(softc, fp, NULL);
4914	if (error != 0)
4915		goto donenolock;
4916	fp->fr_statecnt = 0;
4917	if (fp->fr_srctrack.ht_max_nodes != 0)
4918		ipf_rb_ht_init(&fp->fr_srctrack);
4919
4920	/*
4921	 * Look for an existing matching filter rule, but don't include the
4922	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4923	 * This elminates rules which are indentical being loaded.  Checksum
4924	 * the constant part of the filter rule to make comparisons quicker
4925	 * (this meaning no pointers are included).
4926	 */
4927	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4928	     p < pp; p++)
4929		fp->fr_cksum += *p;
4930	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4931	for (p = (u_int *)fp->fr_data; p < pp; p++)
4932		fp->fr_cksum += *p;
4933
4934	WRITE_ENTER(&softc->ipf_mutex);
4935
4936	/*
4937	 * Now that the filter rule lists are locked, we can walk the
4938	 * chain of them without fear.
4939	 */
4940	ftail = fprev;
4941	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4942		if (fp->fr_collect <= f->fr_collect) {
4943			ftail = fprev;
4944			f = NULL;
4945			break;
4946		}
4947		fprev = ftail;
4948	}
4949
4950	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4951		if (ipf_rule_compare(fp, f) == 0)
4952			break;
4953	}
4954
4955	/*
4956	 * If zero'ing statistics, copy current to caller and zero.
4957	 */
4958	if (addrem == OP_ZERO) {
4959		if (f == NULL) {
4960			IPFERROR(27);
4961			error = ESRCH;
4962		} else {
4963			/*
4964			 * Copy and reduce lock because of impending copyout.
4965			 * Well we should, but if we do then the atomicity of
4966			 * this call and the correctness of fr_hits and
4967			 * fr_bytes cannot be guaranteed.  As it is, this code
4968			 * only resets them to 0 if they are successfully
4969			 * copied out into user space.
4970			 */
4971			bcopy((char *)f, (char *)fp, f->fr_size);
4972			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4973
4974			/*
4975			 * When we copy this rule back out, set the data
4976			 * pointer to be what it was in user space.
4977			 */
4978			fp->fr_data = uptr;
4979			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4980
4981			if (error == 0) {
4982				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4983					error = COPYOUT(f->fr_data, uptr,
4984							f->fr_dsize);
4985					if (error == 0) {
4986						f->fr_hits = 0;
4987						f->fr_bytes = 0;
4988					} else {
4989						IPFERROR(28);
4990						error = EFAULT;
4991					}
4992				}
4993			}
4994		}
4995
4996		if (makecopy != 0) {
4997			if (ptr != NULL) {
4998				KFREES(ptr, fp->fr_dsize);
4999			}
5000			KFREES(fp, fp->fr_size);
5001		}
5002		RWLOCK_EXIT(&softc->ipf_mutex);
5003		return error;
5004	}
5005
5006	if (f == NULL) {
5007		/*
5008		 * At the end of this, ftail must point to the place where the
5009		 * new rule is to be saved/inserted/added.
5010		 * For SIOCAD*FR, this should be the last rule in the group of
5011		 * rules that have equal fr_collect fields.
5012		 * For SIOCIN*FR, ...
5013		 */
5014		if (req == (ioctlcmd_t)SIOCADAFR ||
5015		    req == (ioctlcmd_t)SIOCADIFR) {
5016
5017			for (ftail = fprev; (f = *ftail) != NULL; ) {
5018				if (f->fr_collect > fp->fr_collect)
5019					break;
5020				ftail = &f->fr_next;
5021				fprev = ftail;
5022			}
5023			ftail = fprev;
5024			f = NULL;
5025			ptr = NULL;
5026		} else if (req == (ioctlcmd_t)SIOCINAFR ||
5027			   req == (ioctlcmd_t)SIOCINIFR) {
5028			while ((f = *fprev) != NULL) {
5029				if (f->fr_collect >= fp->fr_collect)
5030					break;
5031				fprev = &f->fr_next;
5032			}
5033  			ftail = fprev;
5034  			if (fp->fr_hits != 0) {
5035				while (fp->fr_hits && (f = *ftail)) {
5036					if (f->fr_collect != fp->fr_collect)
5037						break;
5038					fprev = ftail;
5039  					ftail = &f->fr_next;
5040					fp->fr_hits--;
5041				}
5042  			}
5043  			f = NULL;
5044  			ptr = NULL;
5045		}
5046	}
5047
5048	/*
5049	 * Request to remove a rule.
5050	 */
5051	if (addrem == OP_REM) {
5052		if (f == NULL) {
5053			IPFERROR(29);
5054			error = ESRCH;
5055		} else {
5056			/*
5057			 * Do not allow activity from user space to interfere
5058			 * with rules not loaded that way.
5059			 */
5060			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5061				IPFERROR(30);
5062				error = EPERM;
5063				goto done;
5064			}
5065
5066			/*
5067			 * Return EBUSY if the rule is being reference by
5068			 * something else (eg state information.)
5069			 */
5070			if (f->fr_ref > 1) {
5071				IPFERROR(31);
5072				error = EBUSY;
5073				goto done;
5074			}
5075#ifdef	IPFILTER_SCAN
5076			if (f->fr_isctag != -1 &&
5077			    (f->fr_isc != (struct ipscan *)-1))
5078				ipf_scan_detachfr(f);
5079#endif
5080
5081			if (unit == IPL_LOGAUTH) {
5082				error = ipf_auth_precmd(softc, req, f, ftail);
5083				goto done;
5084			}
5085
5086			ipf_rule_delete(softc, f, unit, set);
5087
5088			need_free = makecopy;
5089		}
5090	} else {
5091		/*
5092		 * Not removing, so we must be adding/inserting a rule.
5093		 */
5094		if (f != NULL) {
5095			IPFERROR(32);
5096			error = EEXIST;
5097			goto done;
5098		}
5099		if (unit == IPL_LOGAUTH) {
5100			error = ipf_auth_precmd(softc, req, fp, ftail);
5101			goto done;
5102		}
5103
5104		MUTEX_NUKE(&fp->fr_lock);
5105		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5106		if (fp->fr_die != 0)
5107			ipf_rule_expire_insert(softc, fp, set);
5108
5109		fp->fr_hits = 0;
5110		if (makecopy != 0)
5111			fp->fr_ref = 1;
5112		fp->fr_pnext = ftail;
5113		fp->fr_next = *ftail;
5114		if (fp->fr_next != NULL)
5115			fp->fr_next->fr_pnext = &fp->fr_next;
5116		*ftail = fp;
5117		if (addrem == OP_ADD)
5118			ipf_fixskip(ftail, fp, 1);
5119
5120		fp->fr_icmpgrp = NULL;
5121		if (fp->fr_icmphead != -1) {
5122			group = FR_NAME(fp, fr_icmphead);
5123			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5124			fp->fr_icmpgrp = fg;
5125		}
5126
5127		fp->fr_grphead = NULL;
5128		if (fp->fr_grhead != -1) {
5129			group = FR_NAME(fp, fr_grhead);
5130			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5131					   unit, set);
5132			fp->fr_grphead = fg;
5133		}
5134	}
5135done:
5136	RWLOCK_EXIT(&softc->ipf_mutex);
5137donenolock:
5138	if (need_free || (error != 0)) {
5139		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5140			if ((fp->fr_satype == FRI_LOOKUP) &&
5141			    (fp->fr_srcptr != NULL))
5142				ipf_lookup_deref(softc, fp->fr_srctype,
5143						 fp->fr_srcptr);
5144			if ((fp->fr_datype == FRI_LOOKUP) &&
5145			    (fp->fr_dstptr != NULL))
5146				ipf_lookup_deref(softc, fp->fr_dsttype,
5147						 fp->fr_dstptr);
5148		}
5149		if (fp->fr_grp != NULL) {
5150			WRITE_ENTER(&softc->ipf_mutex);
5151			ipf_group_del(softc, fp->fr_grp, fp);
5152			RWLOCK_EXIT(&softc->ipf_mutex);
5153		}
5154		if ((ptr != NULL) && (makecopy != 0)) {
5155			KFREES(ptr, fp->fr_dsize);
5156		}
5157		KFREES(fp, fp->fr_size);
5158	}
5159	return (error);
5160}
5161
5162
5163/* ------------------------------------------------------------------------ */
5164/* Function:   ipf_rule_delete                                              */
5165/* Returns:    Nil                                                          */
5166/* Parameters: softc(I) - pointer to soft context main structure            */
5167/*             f(I)     - pointer to the rule being deleted                 */
5168/*             ftail(I) - pointer to the pointer to f                       */
5169/*             unit(I)  - device for which this is for                      */
5170/*             set(I)   - 1 or 0 (filter set)                               */
5171/*                                                                          */
5172/* This function attempts to do what it can to delete a filter rule: remove */
5173/* it from any linked lists and remove any groups it is responsible for.    */
5174/* But in the end, removing a rule can only drop the reference count - we   */
5175/* must use that as the guide for whether or not it can be freed.           */
5176/* ------------------------------------------------------------------------ */
5177static void
5178ipf_rule_delete(softc, f, unit, set)
5179	ipf_main_softc_t *softc;
5180	frentry_t *f;
5181	int unit, set;
5182{
5183
5184	/*
5185	 * If fr_pdnext is set, then the rule is on the expire list, so
5186	 * remove it from there.
5187	 */
5188	if (f->fr_pdnext != NULL) {
5189		*f->fr_pdnext = f->fr_dnext;
5190		if (f->fr_dnext != NULL)
5191			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5192		f->fr_pdnext = NULL;
5193		f->fr_dnext = NULL;
5194	}
5195
5196	ipf_fixskip(f->fr_pnext, f, -1);
5197	if (f->fr_pnext != NULL)
5198		*f->fr_pnext = f->fr_next;
5199	if (f->fr_next != NULL)
5200		f->fr_next->fr_pnext = f->fr_pnext;
5201	f->fr_pnext = NULL;
5202	f->fr_next = NULL;
5203
5204	(void) ipf_derefrule(softc, &f);
5205}
5206
5207/* ------------------------------------------------------------------------ */
5208/* Function:   ipf_rule_expire_insert                                       */
5209/* Returns:    Nil                                                          */
5210/* Parameters: softc(I) - pointer to soft context main structure            */
5211/*             f(I)     - pointer to rule to be added to expire list        */
5212/*             set(I)   - 1 or 0 (filter set)                               */
5213/*                                                                          */
5214/* If the new rule has a given expiration time, insert it into the list of  */
5215/* expiring rules with the ones to be removed first added to the front of   */
5216/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5217/* expiration interval checks.                                              */
5218/* ------------------------------------------------------------------------ */
5219static void
5220ipf_rule_expire_insert(softc, f, set)
5221	ipf_main_softc_t *softc;
5222	frentry_t *f;
5223	int set;
5224{
5225	frentry_t *fr;
5226
5227	/*
5228	 */
5229
5230	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5231	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5232	     fr = fr->fr_dnext) {
5233		if (f->fr_die < fr->fr_die)
5234			break;
5235		if (fr->fr_dnext == NULL) {
5236			/*
5237			 * We've got to the last rule and everything
5238			 * wanted to be expired before this new node,
5239			 * so we have to tack it on the end...
5240			 */
5241			fr->fr_dnext = f;
5242			f->fr_pdnext = &fr->fr_dnext;
5243			fr = NULL;
5244			break;
5245		}
5246	}
5247
5248	if (softc->ipf_rule_explist[set] == NULL) {
5249		softc->ipf_rule_explist[set] = f;
5250		f->fr_pdnext = &softc->ipf_rule_explist[set];
5251	} else if (fr != NULL) {
5252		f->fr_dnext = fr;
5253		f->fr_pdnext = fr->fr_pdnext;
5254		fr->fr_pdnext = &f->fr_dnext;
5255	}
5256}
5257
5258
5259/* ------------------------------------------------------------------------ */
5260/* Function:   ipf_findlookup                                               */
5261/* Returns:    NULL = failure, else success                                 */
5262/* Parameters: softc(I) - pointer to soft context main structure            */
5263/*             unit(I)  - ipf device we want to find match for              */
5264/*             fp(I)    - rule for which lookup is for                      */
5265/*             addrp(I) - pointer to lookup information in address struct   */
5266/*             maskp(O) - pointer to lookup information for storage         */
5267/*                                                                          */
5268/* When using pools and hash tables to store addresses for matching in      */
5269/* rules, it is necessary to resolve both the object referred to by the     */
5270/* name or address (and return that pointer) and also provide the means by  */
5271/* which to determine if an address belongs to that object to make the      */
5272/* packet matching quicker.                                                 */
5273/* ------------------------------------------------------------------------ */
5274static void *
5275ipf_findlookup(softc, unit, fr, addrp, maskp)
5276	ipf_main_softc_t *softc;
5277	int unit;
5278	frentry_t *fr;
5279	i6addr_t *addrp, *maskp;
5280{
5281	void *ptr = NULL;
5282
5283	switch (addrp->iplookupsubtype)
5284	{
5285	case 0 :
5286		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5287					 addrp->iplookupnum,
5288					 &maskp->iplookupfunc);
5289		break;
5290	case 1 :
5291		if (addrp->iplookupname < 0)
5292			break;
5293		if (addrp->iplookupname >= fr->fr_namelen)
5294			break;
5295		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5296					  fr->fr_names + addrp->iplookupname,
5297					  &maskp->iplookupfunc);
5298		break;
5299	default :
5300		break;
5301	}
5302
5303	return ptr;
5304}
5305
5306
5307/* ------------------------------------------------------------------------ */
5308/* Function:    ipf_funcinit                                                */
5309/* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5310/* Parameters:  softc(I) - pointer to soft context main structure           */
5311/*              fr(I)    - pointer to filter rule                           */
5312/*                                                                          */
5313/* If a rule is a call rule, then check if the function it points to needs  */
5314/* an init function to be called now the rule has been loaded.              */
5315/* ------------------------------------------------------------------------ */
5316static int
5317ipf_funcinit(softc, fr)
5318	ipf_main_softc_t *softc;
5319	frentry_t *fr;
5320{
5321	ipfunc_resolve_t *ft;
5322	int err;
5323
5324	IPFERROR(34);
5325	err = ESRCH;
5326
5327	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5328		if (ft->ipfu_addr == fr->fr_func) {
5329			err = 0;
5330			if (ft->ipfu_init != NULL)
5331				err = (*ft->ipfu_init)(softc, fr);
5332			break;
5333		}
5334	return err;
5335}
5336
5337
5338/* ------------------------------------------------------------------------ */
5339/* Function:    ipf_funcfini                                                */
5340/* Returns:     Nil                                                         */
5341/* Parameters:  softc(I) - pointer to soft context main structure           */
5342/*              fr(I)    - pointer to filter rule                           */
5343/*                                                                          */
5344/* For a given filter rule, call the matching "fini" function if the rule   */
5345/* is using a known function that would have resulted in the "init" being   */
5346/* called for ealier.                                                       */
5347/* ------------------------------------------------------------------------ */
5348static void
5349ipf_funcfini(softc, fr)
5350	ipf_main_softc_t *softc;
5351	frentry_t *fr;
5352{
5353	ipfunc_resolve_t *ft;
5354
5355	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5356		if (ft->ipfu_addr == fr->fr_func) {
5357			if (ft->ipfu_fini != NULL)
5358				(void) (*ft->ipfu_fini)(softc, fr);
5359			break;
5360		}
5361}
5362
5363
5364/* ------------------------------------------------------------------------ */
5365/* Function:    ipf_findfunc                                                */
5366/* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5367/* Parameters:  funcptr(I) - function pointer to lookup                     */
5368/*                                                                          */
5369/* Look for a function in the table of known functions.                     */
5370/* ------------------------------------------------------------------------ */
5371static ipfunc_t
5372ipf_findfunc(funcptr)
5373	ipfunc_t funcptr;
5374{
5375	ipfunc_resolve_t *ft;
5376
5377	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5378		if (ft->ipfu_addr == funcptr)
5379			return funcptr;
5380	return NULL;
5381}
5382
5383
5384/* ------------------------------------------------------------------------ */
5385/* Function:    ipf_resolvefunc                                             */
5386/* Returns:     int - 0 == success, else error                              */
5387/* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5388/*                                                                          */
5389/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5390/* This will either be the function name (if the pointer is set) or the     */
5391/* function pointer if the name is set.  When found, fill in the other one  */
5392/* so that the entire, complete, structure can be copied back to user space.*/
5393/* ------------------------------------------------------------------------ */
5394int
5395ipf_resolvefunc(softc, data)
5396	ipf_main_softc_t *softc;
5397	void *data;
5398{
5399	ipfunc_resolve_t res, *ft;
5400	int error;
5401
5402	error = BCOPYIN(data, &res, sizeof(res));
5403	if (error != 0) {
5404		IPFERROR(123);
5405		return EFAULT;
5406	}
5407
5408	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5409		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5410			if (strncmp(res.ipfu_name, ft->ipfu_name,
5411				    sizeof(res.ipfu_name)) == 0) {
5412				res.ipfu_addr = ft->ipfu_addr;
5413				res.ipfu_init = ft->ipfu_init;
5414				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5415					IPFERROR(35);
5416					return EFAULT;
5417				}
5418				return 0;
5419			}
5420	}
5421	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5422		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5423			if (ft->ipfu_addr == res.ipfu_addr) {
5424				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5425					       sizeof(res.ipfu_name));
5426				res.ipfu_init = ft->ipfu_init;
5427				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5428					IPFERROR(36);
5429					return EFAULT;
5430				}
5431				return 0;
5432			}
5433	}
5434	IPFERROR(37);
5435	return ESRCH;
5436}
5437
5438
5439#if !defined(_KERNEL) || SOLARIS
5440/*
5441 * From: NetBSD
5442 * ppsratecheck(): packets (or events) per second limitation.
5443 */
5444int
5445ppsratecheck(lasttime, curpps, maxpps)
5446	struct timeval *lasttime;
5447	int *curpps;
5448	int maxpps;	/* maximum pps allowed */
5449{
5450	struct timeval tv, delta;
5451	int rv;
5452
5453	GETKTIME(&tv);
5454
5455	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5456	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5457	if (delta.tv_usec < 0) {
5458		delta.tv_sec--;
5459		delta.tv_usec += 1000000;
5460	}
5461
5462	/*
5463	 * check for 0,0 is so that the message will be seen at least once.
5464	 * if more than one second have passed since the last update of
5465	 * lasttime, reset the counter.
5466	 *
5467	 * we do increment *curpps even in *curpps < maxpps case, as some may
5468	 * try to use *curpps for stat purposes as well.
5469	 */
5470	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5471	    delta.tv_sec >= 1) {
5472		*lasttime = tv;
5473		*curpps = 0;
5474		rv = 1;
5475	} else if (maxpps < 0)
5476		rv = 1;
5477	else if (*curpps < maxpps)
5478		rv = 1;
5479	else
5480		rv = 0;
5481	*curpps = *curpps + 1;
5482
5483	return (rv);
5484}
5485#endif
5486
5487
5488/* ------------------------------------------------------------------------ */
5489/* Function:    ipf_derefrule                                               */
5490/* Returns:     int   - 0 == rule freed up, else rule not freed             */
5491/* Parameters:  fr(I) - pointer to filter rule                              */
5492/*                                                                          */
5493/* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5494/* free it and any associated storage space being used by it.               */
5495/* ------------------------------------------------------------------------ */
5496int
5497ipf_derefrule(softc, frp)
5498	ipf_main_softc_t *softc;
5499	frentry_t **frp;
5500{
5501	frentry_t *fr;
5502	frdest_t *fdp;
5503
5504	fr = *frp;
5505	*frp = NULL;
5506
5507	MUTEX_ENTER(&fr->fr_lock);
5508	fr->fr_ref--;
5509	if (fr->fr_ref == 0) {
5510		MUTEX_EXIT(&fr->fr_lock);
5511		MUTEX_DESTROY(&fr->fr_lock);
5512
5513		ipf_funcfini(softc, fr);
5514
5515		fdp = &fr->fr_tif;
5516		if (fdp->fd_type == FRD_DSTLIST)
5517			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5518
5519		fdp = &fr->fr_rif;
5520		if (fdp->fd_type == FRD_DSTLIST)
5521			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5522
5523		fdp = &fr->fr_dif;
5524		if (fdp->fd_type == FRD_DSTLIST)
5525			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5526
5527		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5528		    fr->fr_satype == FRI_LOOKUP)
5529			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5530		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5531		    fr->fr_datype == FRI_LOOKUP)
5532			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5533
5534		if (fr->fr_grp != NULL)
5535			ipf_group_del(softc, fr->fr_grp, fr);
5536
5537		if (fr->fr_grphead != NULL)
5538			ipf_group_del(softc, fr->fr_grphead, fr);
5539
5540		if (fr->fr_icmpgrp != NULL)
5541			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5542
5543		if ((fr->fr_flags & FR_COPIED) != 0) {
5544			if (fr->fr_dsize) {
5545				KFREES(fr->fr_data, fr->fr_dsize);
5546			}
5547			KFREES(fr, fr->fr_size);
5548			return 0;
5549		}
5550		return 1;
5551	} else {
5552		MUTEX_EXIT(&fr->fr_lock);
5553	}
5554	return -1;
5555}
5556
5557
5558/* ------------------------------------------------------------------------ */
5559/* Function:    ipf_grpmapinit                                              */
5560/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5561/* Parameters:  fr(I) - pointer to rule to find hash table for              */
5562/*                                                                          */
5563/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5564/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5565/* ------------------------------------------------------------------------ */
5566static int
5567ipf_grpmapinit(softc, fr)
5568	ipf_main_softc_t *softc;
5569	frentry_t *fr;
5570{
5571	char name[FR_GROUPLEN];
5572	iphtable_t *iph;
5573
5574#if defined(SNPRINTF) && defined(_KERNEL)
5575	SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5576#else
5577	(void) sprintf(name, "%d", fr->fr_arg);
5578#endif
5579	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5580	if (iph == NULL) {
5581		IPFERROR(38);
5582		return ESRCH;
5583	}
5584	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5585		IPFERROR(39);
5586		return ESRCH;
5587	}
5588	iph->iph_ref++;
5589	fr->fr_ptr = iph;
5590	return 0;
5591}
5592
5593
5594/* ------------------------------------------------------------------------ */
5595/* Function:    ipf_grpmapfini                                              */
5596/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5597/* Parameters:  softc(I) - pointer to soft context main structure           */
5598/*              fr(I)    - pointer to rule to release hash table for        */
5599/*                                                                          */
5600/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5601/* be called to undo what ipf_grpmapinit caused to be done.                 */
5602/* ------------------------------------------------------------------------ */
5603static int
5604ipf_grpmapfini(softc, fr)
5605	ipf_main_softc_t *softc;
5606	frentry_t *fr;
5607{
5608	iphtable_t *iph;
5609	iph = fr->fr_ptr;
5610	if (iph != NULL)
5611		ipf_lookup_deref(softc, IPLT_HASH, iph);
5612	return 0;
5613}
5614
5615
5616/* ------------------------------------------------------------------------ */
5617/* Function:    ipf_srcgrpmap                                               */
5618/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5619/* Parameters:  fin(I)    - pointer to packet information                   */
5620/*              passp(IO) - pointer to current/new filter decision (unused) */
5621/*                                                                          */
5622/* Look for a rule group head in a hash table, using the source address as  */
5623/* the key, and descend into that group and continue matching rules against */
5624/* the packet.                                                              */
5625/* ------------------------------------------------------------------------ */
5626frentry_t *
5627ipf_srcgrpmap(fin, passp)
5628	fr_info_t *fin;
5629	u_32_t *passp;
5630{
5631	frgroup_t *fg;
5632	void *rval;
5633
5634	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5635				 &fin->fin_src);
5636	if (rval == NULL)
5637		return NULL;
5638
5639	fg = rval;
5640	fin->fin_fr = fg->fg_start;
5641	(void) ipf_scanlist(fin, *passp);
5642	return fin->fin_fr;
5643}
5644
5645
5646/* ------------------------------------------------------------------------ */
5647/* Function:    ipf_dstgrpmap                                               */
5648/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5649/* Parameters:  fin(I)    - pointer to packet information                   */
5650/*              passp(IO) - pointer to current/new filter decision (unused) */
5651/*                                                                          */
5652/* Look for a rule group head in a hash table, using the destination        */
5653/* address as the key, and descend into that group and continue matching    */
5654/* rules against  the packet.                                               */
5655/* ------------------------------------------------------------------------ */
5656frentry_t *
5657ipf_dstgrpmap(fin, passp)
5658	fr_info_t *fin;
5659	u_32_t *passp;
5660{
5661	frgroup_t *fg;
5662	void *rval;
5663
5664	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5665				 &fin->fin_dst);
5666	if (rval == NULL)
5667		return NULL;
5668
5669	fg = rval;
5670	fin->fin_fr = fg->fg_start;
5671	(void) ipf_scanlist(fin, *passp);
5672	return fin->fin_fr;
5673}
5674
5675/*
5676 * Queue functions
5677 * ===============
5678 * These functions manage objects on queues for efficient timeouts.  There
5679 * are a number of system defined queues as well as user defined timeouts.
5680 * It is expected that a lock is held in the domain in which the queue
5681 * belongs (i.e. either state or NAT) when calling any of these functions
5682 * that prevents ipf_freetimeoutqueue() from being called at the same time
5683 * as any other.
5684 */
5685
5686
5687/* ------------------------------------------------------------------------ */
5688/* Function:    ipf_addtimeoutqueue                                         */
5689/* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5690/*                               timeout queue with given interval.         */
5691/* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5692/*                           of interface queues.                           */
5693/*              seconds(I) - timeout value in seconds for this queue.       */
5694/*                                                                          */
5695/* This routine first looks for a timeout queue that matches the interval   */
5696/* being requested.  If it finds one, increments the reference counter and  */
5697/* returns a pointer to it.  If none are found, it allocates a new one and  */
5698/* inserts it at the top of the list.                                       */
5699/*                                                                          */
5700/* Locking.                                                                 */
5701/* It is assumed that the caller of this function has an appropriate lock   */
5702/* held (exclusively) in the domain that encompases 'parent'.               */
5703/* ------------------------------------------------------------------------ */
5704ipftq_t *
5705ipf_addtimeoutqueue(softc, parent, seconds)
5706	ipf_main_softc_t *softc;
5707	ipftq_t **parent;
5708	u_int seconds;
5709{
5710	ipftq_t *ifq;
5711	u_int period;
5712
5713	period = seconds * IPF_HZ_DIVIDE;
5714
5715	MUTEX_ENTER(&softc->ipf_timeoutlock);
5716	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5717		if (ifq->ifq_ttl == period) {
5718			/*
5719			 * Reset the delete flag, if set, so the structure
5720			 * gets reused rather than freed and reallocated.
5721			 */
5722			MUTEX_ENTER(&ifq->ifq_lock);
5723			ifq->ifq_flags &= ~IFQF_DELETE;
5724			ifq->ifq_ref++;
5725			MUTEX_EXIT(&ifq->ifq_lock);
5726			MUTEX_EXIT(&softc->ipf_timeoutlock);
5727
5728			return ifq;
5729		}
5730	}
5731
5732	KMALLOC(ifq, ipftq_t *);
5733	if (ifq != NULL) {
5734		MUTEX_NUKE(&ifq->ifq_lock);
5735		IPFTQ_INIT(ifq, period, "ipftq mutex");
5736		ifq->ifq_next = *parent;
5737		ifq->ifq_pnext = parent;
5738		ifq->ifq_flags = IFQF_USER;
5739		ifq->ifq_ref++;
5740		*parent = ifq;
5741		softc->ipf_userifqs++;
5742	}
5743	MUTEX_EXIT(&softc->ipf_timeoutlock);
5744	return ifq;
5745}
5746
5747
5748/* ------------------------------------------------------------------------ */
5749/* Function:    ipf_deletetimeoutqueue                                      */
5750/* Returns:     int    - new reference count value of the timeout queue     */
5751/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5752/* Locks:       ifq->ifq_lock                                               */
5753/*                                                                          */
5754/* This routine must be called when we're discarding a pointer to a timeout */
5755/* queue object, taking care of the reference counter.                      */
5756/*                                                                          */
5757/* Now that this just sets a DELETE flag, it requires the expire code to    */
5758/* check the list of user defined timeout queues and call the free function */
5759/* below (currently commented out) to stop memory leaking.  It is done this */
5760/* way because the locking may not be sufficient to safely do a free when   */
5761/* this function is called.                                                 */
5762/* ------------------------------------------------------------------------ */
5763int
5764ipf_deletetimeoutqueue(ifq)
5765	ipftq_t *ifq;
5766{
5767
5768	ifq->ifq_ref--;
5769	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5770		ifq->ifq_flags |= IFQF_DELETE;
5771	}
5772
5773	return ifq->ifq_ref;
5774}
5775
5776
5777/* ------------------------------------------------------------------------ */
5778/* Function:    ipf_freetimeoutqueue                                        */
5779/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5780/* Returns:     Nil                                                         */
5781/*                                                                          */
5782/* Locking:                                                                 */
5783/* It is assumed that the caller of this function has an appropriate lock   */
5784/* held (exclusively) in the domain that encompases the callers "domain".   */
5785/* The ifq_lock for this structure should not be held.                      */
5786/*                                                                          */
5787/* Remove a user defined timeout queue from the list of queues it is in and */
5788/* tidy up after this is done.                                              */
5789/* ------------------------------------------------------------------------ */
5790void
5791ipf_freetimeoutqueue(softc, ifq)
5792	ipf_main_softc_t *softc;
5793	ipftq_t *ifq;
5794{
5795
5796	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5797	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5798		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5799		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5800		       ifq->ifq_ref);
5801		return;
5802	}
5803
5804	/*
5805	 * Remove from its position in the list.
5806	 */
5807	*ifq->ifq_pnext = ifq->ifq_next;
5808	if (ifq->ifq_next != NULL)
5809		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5810	ifq->ifq_next = NULL;
5811	ifq->ifq_pnext = NULL;
5812
5813	MUTEX_DESTROY(&ifq->ifq_lock);
5814	ATOMIC_DEC(softc->ipf_userifqs);
5815	KFREE(ifq);
5816}
5817
5818
5819/* ------------------------------------------------------------------------ */
5820/* Function:    ipf_deletequeueentry                                        */
5821/* Returns:     Nil                                                         */
5822/* Parameters:  tqe(I) - timeout queue entry to delete                      */
5823/*                                                                          */
5824/* Remove a tail queue entry from its queue and make it an orphan.          */
5825/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5826/* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5827/* the correct lock(s) may not be held that would make it safe to do so.    */
5828/* ------------------------------------------------------------------------ */
5829void
5830ipf_deletequeueentry(tqe)
5831	ipftqent_t *tqe;
5832{
5833	ipftq_t *ifq;
5834
5835	ifq = tqe->tqe_ifq;
5836
5837	MUTEX_ENTER(&ifq->ifq_lock);
5838
5839	if (tqe->tqe_pnext != NULL) {
5840		*tqe->tqe_pnext = tqe->tqe_next;
5841		if (tqe->tqe_next != NULL)
5842			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5843		else    /* we must be the tail anyway */
5844			ifq->ifq_tail = tqe->tqe_pnext;
5845
5846		tqe->tqe_pnext = NULL;
5847		tqe->tqe_ifq = NULL;
5848	}
5849
5850	(void) ipf_deletetimeoutqueue(ifq);
5851	ASSERT(ifq->ifq_ref > 0);
5852
5853	MUTEX_EXIT(&ifq->ifq_lock);
5854}
5855
5856
5857/* ------------------------------------------------------------------------ */
5858/* Function:    ipf_queuefront                                              */
5859/* Returns:     Nil                                                         */
5860/* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5861/*                                                                          */
5862/* Move a queue entry to the front of the queue, if it isn't already there. */
5863/* ------------------------------------------------------------------------ */
5864void
5865ipf_queuefront(tqe)
5866	ipftqent_t *tqe;
5867{
5868	ipftq_t *ifq;
5869
5870	ifq = tqe->tqe_ifq;
5871	if (ifq == NULL)
5872		return;
5873
5874	MUTEX_ENTER(&ifq->ifq_lock);
5875	if (ifq->ifq_head != tqe) {
5876		*tqe->tqe_pnext = tqe->tqe_next;
5877		if (tqe->tqe_next)
5878			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5879		else
5880			ifq->ifq_tail = tqe->tqe_pnext;
5881
5882		tqe->tqe_next = ifq->ifq_head;
5883		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5884		ifq->ifq_head = tqe;
5885		tqe->tqe_pnext = &ifq->ifq_head;
5886	}
5887	MUTEX_EXIT(&ifq->ifq_lock);
5888}
5889
5890
5891/* ------------------------------------------------------------------------ */
5892/* Function:    ipf_queueback                                               */
5893/* Returns:     Nil                                                         */
5894/* Parameters:  ticks(I) - ipf tick time to use with this call              */
5895/*              tqe(I)   - pointer to timeout queue entry                   */
5896/*                                                                          */
5897/* Move a queue entry to the back of the queue, if it isn't already there.  */
5898/* We use use ticks to calculate the expiration and mark for when we last   */
5899/* touched the structure.                                                   */
5900/* ------------------------------------------------------------------------ */
5901void
5902ipf_queueback(ticks, tqe)
5903	u_long ticks;
5904	ipftqent_t *tqe;
5905{
5906	ipftq_t *ifq;
5907
5908	ifq = tqe->tqe_ifq;
5909	if (ifq == NULL)
5910		return;
5911	tqe->tqe_die = ticks + ifq->ifq_ttl;
5912	tqe->tqe_touched = ticks;
5913
5914	MUTEX_ENTER(&ifq->ifq_lock);
5915	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5916		/*
5917		 * Remove from list
5918		 */
5919		*tqe->tqe_pnext = tqe->tqe_next;
5920		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5921
5922		/*
5923		 * Make it the last entry.
5924		 */
5925		tqe->tqe_next = NULL;
5926		tqe->tqe_pnext = ifq->ifq_tail;
5927		*ifq->ifq_tail = tqe;
5928		ifq->ifq_tail = &tqe->tqe_next;
5929	}
5930	MUTEX_EXIT(&ifq->ifq_lock);
5931}
5932
5933
5934/* ------------------------------------------------------------------------ */
5935/* Function:    ipf_queueappend                                             */
5936/* Returns:     Nil                                                         */
5937/* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5938/*              tqe(I)    - pointer to timeout queue entry                  */
5939/*              ifq(I)    - pointer to timeout queue                        */
5940/*              parent(I) - owing object pointer                            */
5941/*                                                                          */
5942/* Add a new item to this queue and put it on the very end.                 */
5943/* We use use ticks to calculate the expiration and mark for when we last   */
5944/* touched the structure.                                                   */
5945/* ------------------------------------------------------------------------ */
5946void
5947ipf_queueappend(ticks, tqe, ifq, parent)
5948	u_long ticks;
5949	ipftqent_t *tqe;
5950	ipftq_t *ifq;
5951	void *parent;
5952{
5953
5954	MUTEX_ENTER(&ifq->ifq_lock);
5955	tqe->tqe_parent = parent;
5956	tqe->tqe_pnext = ifq->ifq_tail;
5957	*ifq->ifq_tail = tqe;
5958	ifq->ifq_tail = &tqe->tqe_next;
5959	tqe->tqe_next = NULL;
5960	tqe->tqe_ifq = ifq;
5961	tqe->tqe_die = ticks + ifq->ifq_ttl;
5962	tqe->tqe_touched = ticks;
5963	ifq->ifq_ref++;
5964	MUTEX_EXIT(&ifq->ifq_lock);
5965}
5966
5967
5968/* ------------------------------------------------------------------------ */
5969/* Function:    ipf_movequeue                                               */
5970/* Returns:     Nil                                                         */
5971/* Parameters:  tq(I)   - pointer to timeout queue information              */
5972/*              oifp(I) - old timeout queue entry was on                    */
5973/*              nifp(I) - new timeout queue to put entry on                 */
5974/*                                                                          */
5975/* Move a queue entry from one timeout queue to another timeout queue.      */
5976/* If it notices that the current entry is already last and does not need   */
5977/* to move queue, the return.                                               */
5978/* ------------------------------------------------------------------------ */
5979void
5980ipf_movequeue(ticks, tqe, oifq, nifq)
5981	u_long ticks;
5982	ipftqent_t *tqe;
5983	ipftq_t *oifq, *nifq;
5984{
5985
5986	/*
5987	 * If the queue hasn't changed and we last touched this entry at the
5988	 * same ipf time, then we're not going to achieve anything by either
5989	 * changing the ttl or moving it on the queue.
5990	 */
5991	if (oifq == nifq && tqe->tqe_touched == ticks)
5992		return;
5993
5994	/*
5995	 * For any of this to be outside the lock, there is a risk that two
5996	 * packets entering simultaneously, with one changing to a different
5997	 * queue and one not, could end up with things in a bizarre state.
5998	 */
5999	MUTEX_ENTER(&oifq->ifq_lock);
6000
6001	tqe->tqe_touched = ticks;
6002	tqe->tqe_die = ticks + nifq->ifq_ttl;
6003	/*
6004	 * Is the operation here going to be a no-op ?
6005	 */
6006	if (oifq == nifq) {
6007		if ((tqe->tqe_next == NULL) ||
6008		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6009			MUTEX_EXIT(&oifq->ifq_lock);
6010			return;
6011		}
6012	}
6013
6014	/*
6015	 * Remove from the old queue
6016	 */
6017	*tqe->tqe_pnext = tqe->tqe_next;
6018	if (tqe->tqe_next)
6019		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6020	else
6021		oifq->ifq_tail = tqe->tqe_pnext;
6022	tqe->tqe_next = NULL;
6023
6024	/*
6025	 * If we're moving from one queue to another, release the
6026	 * lock on the old queue and get a lock on the new queue.
6027	 * For user defined queues, if we're moving off it, call
6028	 * delete in case it can now be freed.
6029	 */
6030	if (oifq != nifq) {
6031		tqe->tqe_ifq = NULL;
6032
6033		(void) ipf_deletetimeoutqueue(oifq);
6034
6035		MUTEX_EXIT(&oifq->ifq_lock);
6036
6037		MUTEX_ENTER(&nifq->ifq_lock);
6038
6039		tqe->tqe_ifq = nifq;
6040		nifq->ifq_ref++;
6041	}
6042
6043	/*
6044	 * Add to the bottom of the new queue
6045	 */
6046	tqe->tqe_pnext = nifq->ifq_tail;
6047	*nifq->ifq_tail = tqe;
6048	nifq->ifq_tail = &tqe->tqe_next;
6049	MUTEX_EXIT(&nifq->ifq_lock);
6050}
6051
6052
6053/* ------------------------------------------------------------------------ */
6054/* Function:    ipf_updateipid                                              */
6055/* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6056/* Parameters:  fin(I) - pointer to packet information                      */
6057/*                                                                          */
6058/* When we are doing NAT, change the IP of every packet to represent a      */
6059/* single sequence of packets coming from the host, hiding any host         */
6060/* specific sequencing that might otherwise be revealed.  If the packet is  */
6061/* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6062/* the fragment cache for non-leading fragments.  If a non-leading fragment */
6063/* has no match in the cache, return an error.                              */
6064/* ------------------------------------------------------------------------ */
6065static int
6066ipf_updateipid(fin)
6067	fr_info_t *fin;
6068{
6069	u_short id, ido, sums;
6070	u_32_t sumd, sum;
6071	ip_t *ip;
6072
6073	ip = fin->fin_ip;
6074	ido = ntohs(ip->ip_id);
6075	if (fin->fin_off != 0) {
6076		sum = ipf_frag_ipidknown(fin);
6077		if (sum == 0xffffffff)
6078			return -1;
6079		sum &= 0xffff;
6080		id = (u_short)sum;
6081		ip->ip_id = htons(id);
6082	} else {
6083		ip_fillid(ip);
6084		id = ntohs(ip->ip_id);
6085		if ((fin->fin_flx & FI_FRAG) != 0)
6086			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
6087	}
6088
6089	if (id == ido)
6090		return 0;
6091	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
6092	sum = (~ntohs(ip->ip_sum)) & 0xffff;
6093	sum += sumd;
6094	sum = (sum >> 16) + (sum & 0xffff);
6095	sum = (sum >> 16) + (sum & 0xffff);
6096	sums = ~(u_short)sum;
6097	ip->ip_sum = htons(sums);
6098	return 0;
6099}
6100
6101
6102#ifdef	NEED_FRGETIFNAME
6103/* ------------------------------------------------------------------------ */
6104/* Function:    ipf_getifname                                               */
6105/* Returns:     char *    - pointer to interface name                       */
6106/* Parameters:  ifp(I)    - pointer to network interface                    */
6107/*              buffer(O) - pointer to where to store interface name        */
6108/*                                                                          */
6109/* Constructs an interface name in the buffer passed.  The buffer passed is */
6110/* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6111/* as a NULL pointer then return a pointer to a static array.               */
6112/* ------------------------------------------------------------------------ */
6113char *
6114ipf_getifname(ifp, buffer)
6115	struct ifnet *ifp;
6116	char *buffer;
6117{
6118	static char namebuf[LIFNAMSIZ];
6119# if defined(MENTAT) || defined(__FreeBSD__)
6120	int unit, space;
6121	char temp[20];
6122	char *s;
6123# endif
6124
6125	if (buffer == NULL)
6126		buffer = namebuf;
6127	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6128	buffer[LIFNAMSIZ - 1] = '\0';
6129# if defined(MENTAT) || defined(__FreeBSD__)
6130	for (s = buffer; *s; s++)
6131		;
6132	unit = ifp->if_unit;
6133	space = LIFNAMSIZ - (s - buffer);
6134	if ((space > 0) && (unit >= 0)) {
6135#  if defined(SNPRINTF) && defined(_KERNEL)
6136		SNPRINTF(temp, sizeof(temp), "%d", unit);
6137#  else
6138		(void) sprintf(temp, "%d", unit);
6139#  endif
6140		(void) strncpy(s, temp, space);
6141	}
6142# endif
6143	return buffer;
6144}
6145#endif
6146
6147
6148/* ------------------------------------------------------------------------ */
6149/* Function:    ipf_ioctlswitch                                             */
6150/* Returns:     int     - -1 continue processing, else ioctl return value   */
6151/* Parameters:  unit(I) - device unit opened                                */
6152/*              data(I) - pointer to ioctl data                             */
6153/*              cmd(I)  - ioctl command                                     */
6154/*              mode(I) - mode value                                        */
6155/*              uid(I)  - uid making the ioctl call                         */
6156/*              ctx(I)  - pointer to context data                           */
6157/*                                                                          */
6158/* Based on the value of unit, call the appropriate ioctl handler or return */
6159/* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6160/* for the device in order to execute the ioctl.  A special case is made    */
6161/* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6162/* The context data pointer is passed through as this is used as the key    */
6163/* for locating a matching token for continued access for walking lists,    */
6164/* etc.                                                                     */
6165/* ------------------------------------------------------------------------ */
6166int
6167ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6168	ipf_main_softc_t *softc;
6169	int unit, mode, uid;
6170	ioctlcmd_t cmd;
6171	void *data, *ctx;
6172{
6173	int error = 0;
6174
6175	switch (cmd)
6176	{
6177	case SIOCIPFINTERROR :
6178		error = BCOPYOUT(&softc->ipf_interror, data,
6179				 sizeof(softc->ipf_interror));
6180		if (error != 0) {
6181			IPFERROR(40);
6182			error = EFAULT;
6183		}
6184		return error;
6185	default :
6186		break;
6187	}
6188
6189	switch (unit)
6190	{
6191	case IPL_LOGIPF :
6192		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6193		break;
6194	case IPL_LOGNAT :
6195		if (softc->ipf_running > 0) {
6196			error = ipf_nat_ioctl(softc, data, cmd, mode,
6197					      uid, ctx);
6198		} else {
6199			IPFERROR(42);
6200			error = EIO;
6201		}
6202		break;
6203	case IPL_LOGSTATE :
6204		if (softc->ipf_running > 0) {
6205			error = ipf_state_ioctl(softc, data, cmd, mode,
6206						uid, ctx);
6207		} else {
6208			IPFERROR(43);
6209			error = EIO;
6210		}
6211		break;
6212	case IPL_LOGAUTH :
6213		if (softc->ipf_running > 0) {
6214			error = ipf_auth_ioctl(softc, data, cmd, mode,
6215					       uid, ctx);
6216		} else {
6217			IPFERROR(44);
6218			error = EIO;
6219		}
6220		break;
6221	case IPL_LOGSYNC :
6222		if (softc->ipf_running > 0) {
6223			error = ipf_sync_ioctl(softc, data, cmd, mode,
6224					       uid, ctx);
6225		} else {
6226			error = EIO;
6227			IPFERROR(45);
6228		}
6229		break;
6230	case IPL_LOGSCAN :
6231#ifdef IPFILTER_SCAN
6232		if (softc->ipf_running > 0)
6233			error = ipf_scan_ioctl(softc, data, cmd, mode,
6234					       uid, ctx);
6235		else
6236#endif
6237		{
6238			error = EIO;
6239			IPFERROR(46);
6240		}
6241		break;
6242	case IPL_LOGLOOKUP :
6243		if (softc->ipf_running > 0) {
6244			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6245						 uid, ctx);
6246		} else {
6247			error = EIO;
6248			IPFERROR(47);
6249		}
6250		break;
6251	default :
6252		IPFERROR(48);
6253		error = EIO;
6254		break;
6255	}
6256
6257	return error;
6258}
6259
6260
6261/*
6262 * This array defines the expected size of objects coming into the kernel
6263 * for the various recognised object types. The first column is flags (see
6264 * below), 2nd column is current size, 3rd column is the version number of
6265 * when the current size became current.
6266 * Flags:
6267 * 1 = minimum size, not absolute size
6268 */
6269static const int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6270	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6271	{ 1,	sizeof(struct friostat),	5010000 },
6272	{ 0,	sizeof(struct fr_info),		5010000 },
6273	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6274	{ 0,	sizeof(struct ipfrstat),	5010000 },
6275	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6276	{ 0,	sizeof(struct natstat),		5010000 },
6277	{ 0,	sizeof(struct ipstate_save),	5010000 },
6278	{ 1,	sizeof(struct nat_save),	5010000 },
6279	{ 0,	sizeof(struct natlookup),	5010000 },
6280	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6281	{ 0,	sizeof(struct ips_stat),	5010000 },
6282	{ 0,	sizeof(struct frauth),		5010000 },
6283	{ 0,	sizeof(struct ipftune),		4010100 },
6284	{ 0,	sizeof(struct nat),		5010000 },
6285	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6286	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6287	{ 0,	sizeof(struct ipftable),	4011400 },
6288	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6289	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6290	{ 1,	0,				0	}, /* IPFEXPR */
6291	{ 0,	0,				0	}, /* PROXYCTL */
6292	{ 0,	sizeof (struct fripf),		5010000	}
6293};
6294
6295
6296/* ------------------------------------------------------------------------ */
6297/* Function:    ipf_inobj                                                   */
6298/* Returns:     int     - 0 = success, else failure                         */
6299/* Parameters:  softc(I) - soft context pointerto work with                 */
6300/*              data(I)  - pointer to ioctl data                            */
6301/*              objp(O)  - where to store ipfobj structure                  */
6302/*              ptr(I)   - pointer to data to copy out                      */
6303/*              type(I)  - type of structure being moved                    */
6304/*                                                                          */
6305/* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6306/* add things to check for version numbers, sizes, etc, to make it backward */
6307/* compatible at the ABI for user land.                                     */
6308/* If objp is not NULL then we assume that the caller wants to see what is  */
6309/* in the ipfobj_t structure being copied in. As an example, this can tell  */
6310/* the caller what version of ipfilter the ioctl program was written to.    */
6311/* ------------------------------------------------------------------------ */
6312int
6313ipf_inobj(softc, data, objp, ptr, type)
6314	ipf_main_softc_t *softc;
6315	void *data;
6316	ipfobj_t *objp;
6317	void *ptr;
6318	int type;
6319{
6320	ipfobj_t obj;
6321	int error;
6322	int size;
6323
6324	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6325		IPFERROR(49);
6326		return EINVAL;
6327	}
6328
6329	if (objp == NULL)
6330		objp = &obj;
6331	error = BCOPYIN(data, objp, sizeof(*objp));
6332	if (error != 0) {
6333		IPFERROR(124);
6334		return EFAULT;
6335	}
6336
6337	if (objp->ipfo_type != type) {
6338		IPFERROR(50);
6339		return EINVAL;
6340	}
6341
6342	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6343		if ((ipf_objbytes[type][0] & 1) != 0) {
6344			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6345				IPFERROR(51);
6346				return EINVAL;
6347			}
6348			size =  ipf_objbytes[type][1];
6349		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6350			size =  objp->ipfo_size;
6351		} else {
6352			IPFERROR(52);
6353			return EINVAL;
6354		}
6355		error = COPYIN(objp->ipfo_ptr, ptr, size);
6356		if (error != 0) {
6357			IPFERROR(55);
6358			error = EFAULT;
6359		}
6360	} else {
6361#ifdef  IPFILTER_COMPAT
6362		error = ipf_in_compat(softc, objp, ptr, 0);
6363#else
6364		IPFERROR(54);
6365		error = EINVAL;
6366#endif
6367	}
6368	return error;
6369}
6370
6371
6372/* ------------------------------------------------------------------------ */
6373/* Function:    ipf_inobjsz                                                 */
6374/* Returns:     int     - 0 = success, else failure                         */
6375/* Parameters:  softc(I) - soft context pointerto work with                 */
6376/*              data(I)  - pointer to ioctl data                            */
6377/*              ptr(I)   - pointer to store real data in                    */
6378/*              type(I)  - type of structure being moved                    */
6379/*              sz(I)    - size of data to copy                             */
6380/*                                                                          */
6381/* As per ipf_inobj, except the size of the object to copy in is passed in  */
6382/* but it must not be smaller than the size defined for the type and the    */
6383/* type must allow for varied sized objects.  The extra requirement here is */
6384/* that sz must match the size of the object being passed in - this is not  */
6385/* not possible nor required in ipf_inobj().                                */
6386/* ------------------------------------------------------------------------ */
6387int
6388ipf_inobjsz(softc, data, ptr, type, sz)
6389	ipf_main_softc_t *softc;
6390	void *data;
6391	void *ptr;
6392	int type, sz;
6393{
6394	ipfobj_t obj;
6395	int error;
6396
6397	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6398		IPFERROR(56);
6399		return EINVAL;
6400	}
6401
6402	error = BCOPYIN(data, &obj, sizeof(obj));
6403	if (error != 0) {
6404		IPFERROR(125);
6405		return EFAULT;
6406	}
6407
6408	if (obj.ipfo_type != type) {
6409		IPFERROR(58);
6410		return EINVAL;
6411	}
6412
6413	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6414		if (((ipf_objbytes[type][0] & 1) == 0) ||
6415		    (sz < ipf_objbytes[type][1])) {
6416			IPFERROR(57);
6417			return EINVAL;
6418		}
6419		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6420		if (error != 0) {
6421			IPFERROR(61);
6422			error = EFAULT;
6423		}
6424	} else {
6425#ifdef	IPFILTER_COMPAT
6426		error = ipf_in_compat(softc, &obj, ptr, sz);
6427#else
6428		IPFERROR(60);
6429		error = EINVAL;
6430#endif
6431	}
6432	return error;
6433}
6434
6435
6436/* ------------------------------------------------------------------------ */
6437/* Function:    ipf_outobjsz                                                */
6438/* Returns:     int     - 0 = success, else failure                         */
6439/* Parameters:  data(I) - pointer to ioctl data                             */
6440/*              ptr(I)  - pointer to store real data in                     */
6441/*              type(I) - type of structure being moved                     */
6442/*              sz(I)   - size of data to copy                              */
6443/*                                                                          */
6444/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6445/* but it must not be smaller than the size defined for the type and the    */
6446/* type must allow for varied sized objects.  The extra requirement here is */
6447/* that sz must match the size of the object being passed in - this is not  */
6448/* not possible nor required in ipf_outobj().                               */
6449/* ------------------------------------------------------------------------ */
6450int
6451ipf_outobjsz(softc, data, ptr, type, sz)
6452	ipf_main_softc_t *softc;
6453	void *data;
6454	void *ptr;
6455	int type, sz;
6456{
6457	ipfobj_t obj;
6458	int error;
6459
6460	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6461		IPFERROR(62);
6462		return EINVAL;
6463	}
6464
6465	error = BCOPYIN(data, &obj, sizeof(obj));
6466	if (error != 0) {
6467		IPFERROR(127);
6468		return EFAULT;
6469	}
6470
6471	if (obj.ipfo_type != type) {
6472		IPFERROR(63);
6473		return EINVAL;
6474	}
6475
6476	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6477		if (((ipf_objbytes[type][0] & 1) == 0) ||
6478		    (sz < ipf_objbytes[type][1])) {
6479			IPFERROR(146);
6480			return EINVAL;
6481		}
6482		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6483		if (error != 0) {
6484			IPFERROR(66);
6485			error = EFAULT;
6486		}
6487	} else {
6488#ifdef	IPFILTER_COMPAT
6489		error = ipf_out_compat(softc, &obj, ptr);
6490#else
6491		IPFERROR(65);
6492		error = EINVAL;
6493#endif
6494	}
6495	return error;
6496}
6497
6498
6499/* ------------------------------------------------------------------------ */
6500/* Function:    ipf_outobj                                                  */
6501/* Returns:     int     - 0 = success, else failure                         */
6502/* Parameters:  data(I) - pointer to ioctl data                             */
6503/*              ptr(I)  - pointer to store real data in                     */
6504/*              type(I) - type of structure being moved                     */
6505/*                                                                          */
6506/* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6507/* future, we add things to check for version numbers, sizes, etc, to make  */
6508/* it backward  compatible at the ABI for user land.                        */
6509/* ------------------------------------------------------------------------ */
6510int
6511ipf_outobj(softc, data, ptr, type)
6512	ipf_main_softc_t *softc;
6513	void *data;
6514	void *ptr;
6515	int type;
6516{
6517	ipfobj_t obj;
6518	int error;
6519
6520	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6521		IPFERROR(67);
6522		return EINVAL;
6523	}
6524
6525	error = BCOPYIN(data, &obj, sizeof(obj));
6526	if (error != 0) {
6527		IPFERROR(126);
6528		return EFAULT;
6529	}
6530
6531	if (obj.ipfo_type != type) {
6532		IPFERROR(68);
6533		return EINVAL;
6534	}
6535
6536	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6537		if ((ipf_objbytes[type][0] & 1) != 0) {
6538			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6539				IPFERROR(69);
6540				return EINVAL;
6541			}
6542		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6543			IPFERROR(70);
6544			return EINVAL;
6545		}
6546
6547		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6548		if (error != 0) {
6549			IPFERROR(73);
6550			error = EFAULT;
6551		}
6552	} else {
6553#ifdef	IPFILTER_COMPAT
6554		error = ipf_out_compat(softc, &obj, ptr);
6555#else
6556		IPFERROR(72);
6557		error = EINVAL;
6558#endif
6559	}
6560	return error;
6561}
6562
6563
6564/* ------------------------------------------------------------------------ */
6565/* Function:    ipf_outobjk                                                 */
6566/* Returns:     int     - 0 = success, else failure                         */
6567/* Parameters:  obj(I)  - pointer to data description structure             */
6568/*              ptr(I)  - pointer to kernel data to copy out                */
6569/*                                                                          */
6570/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6571/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6572/* already populated with information and now we just need to use it.       */
6573/* There is no need for this function to have a "type" parameter as there   */
6574/* is no point in validating information that comes from the kernel with    */
6575/* itself.                                                                  */
6576/* ------------------------------------------------------------------------ */
6577int
6578ipf_outobjk(softc, obj, ptr)
6579	ipf_main_softc_t *softc;
6580	ipfobj_t *obj;
6581	void *ptr;
6582{
6583	int type = obj->ipfo_type;
6584	int error;
6585
6586	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6587		IPFERROR(147);
6588		return EINVAL;
6589	}
6590
6591	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6592		if ((ipf_objbytes[type][0] & 1) != 0) {
6593			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6594				IPFERROR(148);
6595				return EINVAL;
6596			}
6597
6598		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6599			IPFERROR(149);
6600			return EINVAL;
6601		}
6602
6603		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6604		if (error != 0) {
6605			IPFERROR(150);
6606			error = EFAULT;
6607		}
6608	} else {
6609#ifdef  IPFILTER_COMPAT
6610		error = ipf_out_compat(softc, obj, ptr);
6611#else
6612		IPFERROR(151);
6613		error = EINVAL;
6614#endif
6615	}
6616	return error;
6617}
6618
6619
6620/* ------------------------------------------------------------------------ */
6621/* Function:    ipf_checkl4sum                                              */
6622/* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6623/* Parameters:  fin(I) - pointer to packet information                      */
6624/*                                                                          */
6625/* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6626/* not possible, return without indicating a failure or success but in a    */
6627/* way that is ditinguishable. This function should only be called by the   */
6628/* ipf_checkv6sum() for each platform.                                      */
6629/* ------------------------------------------------------------------------ */
6630INLINE int
6631ipf_checkl4sum(fin)
6632	fr_info_t *fin;
6633{
6634	u_short sum, hdrsum, *csump;
6635	udphdr_t *udp;
6636	int dosum;
6637
6638	/*
6639	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6640	 * isn't already considered "bad", then validate the checksum.  If
6641	 * this check fails then considered the packet to be "bad".
6642	 */
6643	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6644		return 1;
6645
6646	DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6647	if (fin->fin_out == 1) {
6648		fin->fin_cksum = FI_CK_SUMOK;
6649		return 0;
6650	}
6651
6652	csump = NULL;
6653	hdrsum = 0;
6654	dosum = 0;
6655	sum = 0;
6656
6657	switch (fin->fin_p)
6658	{
6659	case IPPROTO_TCP :
6660		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6661		dosum = 1;
6662		break;
6663
6664	case IPPROTO_UDP :
6665		udp = fin->fin_dp;
6666		if (udp->uh_sum != 0) {
6667			csump = &udp->uh_sum;
6668			dosum = 1;
6669		}
6670		break;
6671
6672#ifdef USE_INET6
6673	case IPPROTO_ICMPV6 :
6674		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6675		dosum = 1;
6676		break;
6677#endif
6678
6679	case IPPROTO_ICMP :
6680		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6681		dosum = 1;
6682		break;
6683
6684	default :
6685		return 1;
6686		/*NOTREACHED*/
6687	}
6688
6689	if (csump != NULL)
6690		hdrsum = *csump;
6691
6692	if (dosum) {
6693		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6694	}
6695#if !defined(_KERNEL)
6696	if (sum == hdrsum) {
6697		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6698	} else {
6699		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6700	}
6701#endif
6702	DT2(l4sums, u_short, hdrsum, u_short, sum);
6703#ifdef USE_INET6
6704	if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6705#else
6706	if (hdrsum == sum) {
6707#endif
6708		fin->fin_cksum = FI_CK_SUMOK;
6709		return 0;
6710	}
6711	fin->fin_cksum = FI_CK_BAD;
6712	return -1;
6713}
6714
6715
6716/* ------------------------------------------------------------------------ */
6717/* Function:    ipf_ifpfillv4addr                                           */
6718/* Returns:     int     - 0 = address update, -1 = address not updated      */
6719/* Parameters:  atype(I)   - type of network address update to perform      */
6720/*              sin(I)     - pointer to source of address information       */
6721/*              mask(I)    - pointer to source of netmask information       */
6722/*              inp(I)     - pointer to destination address store           */
6723/*              inpmask(I) - pointer to destination netmask store           */
6724/*                                                                          */
6725/* Given a type of network address update (atype) to perform, copy          */
6726/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6727/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6728/* which case the operation fails.  For all values of atype other than      */
6729/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6730/* value.                                                                   */
6731/* ------------------------------------------------------------------------ */
6732int
6733ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6734	int atype;
6735	struct sockaddr_in *sin, *mask;
6736	struct in_addr *inp, *inpmask;
6737{
6738	if (inpmask != NULL && atype != FRI_NETMASKED)
6739		inpmask->s_addr = 0xffffffff;
6740
6741	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6742		if (atype == FRI_NETMASKED) {
6743			if (inpmask == NULL)
6744				return -1;
6745			inpmask->s_addr = mask->sin_addr.s_addr;
6746		}
6747		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6748	} else {
6749		inp->s_addr = sin->sin_addr.s_addr;
6750	}
6751	return 0;
6752}
6753
6754
6755#ifdef	USE_INET6
6756/* ------------------------------------------------------------------------ */
6757/* Function:    ipf_ifpfillv6addr                                           */
6758/* Returns:     int     - 0 = address update, -1 = address not updated      */
6759/* Parameters:  atype(I)   - type of network address update to perform      */
6760/*              sin(I)     - pointer to source of address information       */
6761/*              mask(I)    - pointer to source of netmask information       */
6762/*              inp(I)     - pointer to destination address store           */
6763/*              inpmask(I) - pointer to destination netmask store           */
6764/*                                                                          */
6765/* Given a type of network address update (atype) to perform, copy          */
6766/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6767/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6768/* which case the operation fails.  For all values of atype other than      */
6769/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6770/* value.                                                                   */
6771/* ------------------------------------------------------------------------ */
6772int
6773ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6774	int atype;
6775	struct sockaddr_in6 *sin, *mask;
6776	i6addr_t *inp, *inpmask;
6777{
6778	i6addr_t *src, *and;
6779
6780	src = (i6addr_t *)&sin->sin6_addr;
6781	and = (i6addr_t *)&mask->sin6_addr;
6782
6783	if (inpmask != NULL && atype != FRI_NETMASKED) {
6784		inpmask->i6[0] = 0xffffffff;
6785		inpmask->i6[1] = 0xffffffff;
6786		inpmask->i6[2] = 0xffffffff;
6787		inpmask->i6[3] = 0xffffffff;
6788	}
6789
6790	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6791		if (atype == FRI_NETMASKED) {
6792			if (inpmask == NULL)
6793				return -1;
6794			inpmask->i6[0] = and->i6[0];
6795			inpmask->i6[1] = and->i6[1];
6796			inpmask->i6[2] = and->i6[2];
6797			inpmask->i6[3] = and->i6[3];
6798		}
6799
6800		inp->i6[0] = src->i6[0] & and->i6[0];
6801		inp->i6[1] = src->i6[1] & and->i6[1];
6802		inp->i6[2] = src->i6[2] & and->i6[2];
6803		inp->i6[3] = src->i6[3] & and->i6[3];
6804	} else {
6805		inp->i6[0] = src->i6[0];
6806		inp->i6[1] = src->i6[1];
6807		inp->i6[2] = src->i6[2];
6808		inp->i6[3] = src->i6[3];
6809	}
6810	return 0;
6811}
6812#endif
6813
6814
6815/* ------------------------------------------------------------------------ */
6816/* Function:    ipf_matchtag                                                */
6817/* Returns:     0 == mismatch, 1 == match.                                  */
6818/* Parameters:  tag1(I) - pointer to first tag to compare                   */
6819/*              tag2(I) - pointer to second tag to compare                  */
6820/*                                                                          */
6821/* Returns true (non-zero) or false(0) if the two tag structures can be     */
6822/* considered to be a match or not match, respectively.  The tag is 16      */
6823/* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6824/* compare the ints instead, for speed. tag1 is the master of the           */
6825/* comparison.  This function should only be called with both tag1 and tag2 */
6826/* as non-NULL pointers.                                                    */
6827/* ------------------------------------------------------------------------ */
6828int
6829ipf_matchtag(tag1, tag2)
6830	ipftag_t *tag1, *tag2;
6831{
6832	if (tag1 == tag2)
6833		return 1;
6834
6835	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6836		return 1;
6837
6838	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6839	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6840	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6841	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6842		return 1;
6843	return 0;
6844}
6845
6846
6847/* ------------------------------------------------------------------------ */
6848/* Function:    ipf_coalesce                                                */
6849/* Returns:     1 == success, -1 == failure, 0 == no change                 */
6850/* Parameters:  fin(I) - pointer to packet information                      */
6851/*                                                                          */
6852/* Attempt to get all of the packet data into a single, contiguous buffer.  */
6853/* If this call returns a failure then the buffers have also been freed.    */
6854/* ------------------------------------------------------------------------ */
6855int
6856ipf_coalesce(fin)
6857	fr_info_t *fin;
6858{
6859
6860	if ((fin->fin_flx & FI_COALESCE) != 0)
6861		return 1;
6862
6863	/*
6864	 * If the mbuf pointers indicate that there is no mbuf to work with,
6865	 * return but do not indicate success or failure.
6866	 */
6867	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6868		return 0;
6869
6870#if defined(_KERNEL)
6871	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6872		ipf_main_softc_t *softc = fin->fin_main_soft;
6873
6874		DT1(frb_coalesce, fr_info_t *, fin);
6875		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6876# ifdef MENTAT
6877		FREE_MB_T(*fin->fin_mp);
6878# endif
6879		fin->fin_reason = FRB_COALESCE;
6880		*fin->fin_mp = NULL;
6881		fin->fin_m = NULL;
6882		return -1;
6883	}
6884#else
6885	fin = fin;	/* LINT */
6886#endif
6887	return 1;
6888}
6889
6890
6891/*
6892 * The following table lists all of the tunable variables that can be
6893 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6894 * in the table below is as follows:
6895 *
6896 * pointer to value, name of value, minimum, maximum, size of the value's
6897 *     container, value attribute flags
6898 *
6899 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6900 * means the value can only be written to when IPFilter is loaded but disabled.
6901 * The obvious implication is if neither of these are set then the value can be
6902 * changed at any time without harm.
6903 */
6904
6905
6906/* ------------------------------------------------------------------------ */
6907/* Function:    ipf_tune_findbycookie                                       */
6908/* Returns:     NULL = search failed, else pointer to tune struct           */
6909/* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6910/*              next(O)   - pointer to place to store the cookie for the    */
6911/*                          "next" tuneable, if it is desired.              */
6912/*                                                                          */
6913/* This function is used to walk through all of the existing tunables with  */
6914/* successive calls.  It searches the known tunables for the one which has  */
6915/* a matching value for "cookie" - ie its address.  When returning a match, */
6916/* the next one to be found may be returned inside next.                    */
6917/* ------------------------------------------------------------------------ */
6918static ipftuneable_t *
6919ipf_tune_findbycookie(ptop, cookie, next)
6920	ipftuneable_t **ptop;
6921	void *cookie, **next;
6922{
6923	ipftuneable_t *ta, **tap;
6924
6925	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6926		if (ta == cookie) {
6927			if (next != NULL) {
6928				/*
6929				 * If the next entry in the array has a name
6930				 * present, then return a pointer to it for
6931				 * where to go next, else return a pointer to
6932				 * the dynaminc list as a key to search there
6933				 * next.  This facilitates a weak linking of
6934				 * the two "lists" together.
6935				 */
6936				if ((ta + 1)->ipft_name != NULL)
6937					*next = ta + 1;
6938				else
6939					*next = ptop;
6940			}
6941			return ta;
6942		}
6943
6944	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6945		if (tap == cookie) {
6946			if (next != NULL)
6947				*next = &ta->ipft_next;
6948			return ta;
6949		}
6950
6951	if (next != NULL)
6952		*next = NULL;
6953	return NULL;
6954}
6955
6956
6957/* ------------------------------------------------------------------------ */
6958/* Function:    ipf_tune_findbyname                                         */
6959/* Returns:     NULL = search failed, else pointer to tune struct           */
6960/* Parameters:  name(I) - name of the tuneable entry to find.               */
6961/*                                                                          */
6962/* Search the static array of tuneables and the list of dynamic tuneables   */
6963/* for an entry with a matching name.  If we can find one, return a pointer */
6964/* to the matching structure.                                               */
6965/* ------------------------------------------------------------------------ */
6966static ipftuneable_t *
6967ipf_tune_findbyname(top, name)
6968	ipftuneable_t *top;
6969	const char *name;
6970{
6971	ipftuneable_t *ta;
6972
6973	for (ta = top; ta != NULL; ta = ta->ipft_next)
6974		if (!strcmp(ta->ipft_name, name)) {
6975			return ta;
6976		}
6977
6978	return NULL;
6979}
6980
6981
6982/* ------------------------------------------------------------------------ */
6983/* Function:    ipf_tune_add_array                                          */
6984/* Returns:     int - 0 == success, else failure                            */
6985/* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6986/*                                                                          */
6987/* Appends tune structures from the array passed in (newtune) to the end of */
6988/* the current list of "dynamic" tuneable parameters.                       */
6989/* If any entry to be added is already present (by name) then the operation */
6990/* is aborted - entries that have been added are removed before returning.  */
6991/* An entry with no name (NULL) is used as the indication that the end of   */
6992/* the array has been reached.                                              */
6993/* ------------------------------------------------------------------------ */
6994int
6995ipf_tune_add_array(softc, newtune)
6996	ipf_main_softc_t *softc;
6997	ipftuneable_t *newtune;
6998{
6999	ipftuneable_t *nt, *dt;
7000	int error = 0;
7001
7002	for (nt = newtune; nt->ipft_name != NULL; nt++) {
7003		error = ipf_tune_add(softc, nt);
7004		if (error != 0) {
7005			for (dt = newtune; dt != nt; dt++) {
7006				(void) ipf_tune_del(softc, dt);
7007			}
7008		}
7009	}
7010
7011	return error;
7012}
7013
7014
7015/* ------------------------------------------------------------------------ */
7016/* Function:    ipf_tune_array_link                                         */
7017/* Returns:     0 == success, -1 == failure                                 */
7018/* Parameters:  softc(I) - soft context pointerto work with                 */
7019/*              array(I) - pointer to an array of tuneables                 */
7020/*                                                                          */
7021/* Given an array of tunables (array), append them to the current list of   */
7022/* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7023/* the array for being appended to the list, initialise all of the next     */
7024/* pointers so we don't need to walk parts of it with ++ and others with    */
7025/* next. The array is expected to have an entry with a NULL name as the     */
7026/* terminator. Trying to add an array with no non-NULL names will return as */
7027/* a failure.                                                               */
7028/* ------------------------------------------------------------------------ */
7029int
7030ipf_tune_array_link(softc, array)
7031	ipf_main_softc_t *softc;
7032	ipftuneable_t *array;
7033{
7034	ipftuneable_t *t, **p;
7035
7036	t = array;
7037	if (t->ipft_name == NULL)
7038		return -1;
7039
7040	for (; t[1].ipft_name != NULL; t++)
7041		t[0].ipft_next = &t[1];
7042	t->ipft_next = NULL;
7043
7044	/*
7045	 * Since a pointer to the last entry isn't kept, we need to find it
7046	 * each time we want to add new variables to the list.
7047	 */
7048	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7049		if (t->ipft_name == NULL)
7050			break;
7051	*p = array;
7052
7053	return 0;
7054}
7055
7056
7057/* ------------------------------------------------------------------------ */
7058/* Function:    ipf_tune_array_unlink                                       */
7059/* Returns:     0 == success, -1 == failure                                 */
7060/* Parameters:  softc(I) - soft context pointerto work with                 */
7061/*              array(I) - pointer to an array of tuneables                 */
7062/*                                                                          */
7063/* ------------------------------------------------------------------------ */
7064int
7065ipf_tune_array_unlink(softc, array)
7066	ipf_main_softc_t *softc;
7067	ipftuneable_t *array;
7068{
7069	ipftuneable_t *t, **p;
7070
7071	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7072		if (t == array)
7073			break;
7074	if (t == NULL)
7075		return -1;
7076
7077	for (; t[1].ipft_name != NULL; t++)
7078		;
7079
7080	*p = t->ipft_next;
7081
7082	return 0;
7083}
7084
7085
7086/* ------------------------------------------------------------------------ */
7087/* Function:   ipf_tune_array_copy                                          */
7088/* Returns:    NULL = failure, else pointer to new array                    */
7089/* Parameters: base(I)     - pointer to structure base                      */
7090/*             size(I)     - size of the array at template                  */
7091/*             template(I) - original array to copy                         */
7092/*                                                                          */
7093/* Allocate memory for a new set of tuneable values and copy everything     */
7094/* from template into the new region of memory.  The new region is full of  */
7095/* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7096/*                                                                          */
7097/* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7098/* In the array template, ipftp_offset is the offset (in bytes) of the      */
7099/* location of the tuneable value inside the structure pointed to by base.  */
7100/* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7101/* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7102/* ipftp_void that points to the stored value.                              */
7103/* ------------------------------------------------------------------------ */
7104ipftuneable_t *
7105ipf_tune_array_copy(base, size, template)
7106	void *base;
7107	size_t size;
7108	ipftuneable_t *template;
7109{
7110	ipftuneable_t *copy;
7111	int i;
7112
7113
7114	KMALLOCS(copy, ipftuneable_t *, size);
7115	if (copy == NULL) {
7116		return NULL;
7117	}
7118	bcopy(template, copy, size);
7119
7120	for (i = 0; copy[i].ipft_name; i++) {
7121		copy[i].ipft_una.ipftp_offset += (u_long)base;
7122		copy[i].ipft_next = copy + i + 1;
7123	}
7124
7125	return copy;
7126}
7127
7128
7129/* ------------------------------------------------------------------------ */
7130/* Function:    ipf_tune_add                                                */
7131/* Returns:     int - 0 == success, else failure                            */
7132/* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7133/*                                                                          */
7134/* Appends tune structures from the array passed in (newtune) to the end of */
7135/* the current list of "dynamic" tuneable parameters.  Once added, the      */
7136/* owner of the object is not expected to ever change "ipft_next".          */
7137/* ------------------------------------------------------------------------ */
7138int
7139ipf_tune_add(softc, newtune)
7140	ipf_main_softc_t *softc;
7141	ipftuneable_t *newtune;
7142{
7143	ipftuneable_t *ta, **tap;
7144
7145	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7146	if (ta != NULL) {
7147		IPFERROR(74);
7148		return EEXIST;
7149	}
7150
7151	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7152		;
7153
7154	newtune->ipft_next = NULL;
7155	*tap = newtune;
7156	return 0;
7157}
7158
7159
7160/* ------------------------------------------------------------------------ */
7161/* Function:    ipf_tune_del                                                */
7162/* Returns:     int - 0 == success, else failure                            */
7163/* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7164/*                        current dynamic tuneables                         */
7165/*                                                                          */
7166/* Search for the tune structure, by pointer, in the list of those that are */
7167/* dynamically added at run time.  If found, adjust the list so that this   */
7168/* structure is no longer part of it.                                       */
7169/* ------------------------------------------------------------------------ */
7170int
7171ipf_tune_del(softc, oldtune)
7172	ipf_main_softc_t *softc;
7173	ipftuneable_t *oldtune;
7174{
7175	ipftuneable_t *ta, **tap;
7176	int error = 0;
7177
7178	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7179	     tap = &ta->ipft_next) {
7180		if (ta == oldtune) {
7181			*tap = oldtune->ipft_next;
7182			oldtune->ipft_next = NULL;
7183			break;
7184		}
7185	}
7186
7187	if (ta == NULL) {
7188		error = ESRCH;
7189		IPFERROR(75);
7190	}
7191	return error;
7192}
7193
7194
7195/* ------------------------------------------------------------------------ */
7196/* Function:    ipf_tune_del_array                                          */
7197/* Returns:     int - 0 == success, else failure                            */
7198/* Parameters:  oldtune - pointer to tuneables array                        */
7199/*                                                                          */
7200/* Remove each tuneable entry in the array from the list of "dynamic"       */
7201/* tunables.  If one entry should fail to be found, an error will be        */
7202/* returned and no further ones removed.                                    */
7203/* An entry with a NULL name is used as the indicator of the last entry in  */
7204/* the array.                                                               */
7205/* ------------------------------------------------------------------------ */
7206int
7207ipf_tune_del_array(softc, oldtune)
7208	ipf_main_softc_t *softc;
7209	ipftuneable_t *oldtune;
7210{
7211	ipftuneable_t *ot;
7212	int error = 0;
7213
7214	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7215		error = ipf_tune_del(softc, ot);
7216		if (error != 0)
7217			break;
7218	}
7219
7220	return error;
7221
7222}
7223
7224
7225/* ------------------------------------------------------------------------ */
7226/* Function:    ipf_tune                                                    */
7227/* Returns:     int - 0 == success, else failure                            */
7228/* Parameters:  cmd(I)  - ioctl command number                              */
7229/*              data(I) - pointer to ioctl data structure                   */
7230/*                                                                          */
7231/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7232/* three ioctls provide the means to access and control global variables    */
7233/* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7234/* changed without rebooting, reloading or recompiling.  The initialisation */
7235/* and 'destruction' routines of the various components of ipfilter are all */
7236/* each responsible for handling their own values being too big.            */
7237/* ------------------------------------------------------------------------ */
7238int
7239ipf_ipftune(softc, cmd, data)
7240	ipf_main_softc_t *softc;
7241	ioctlcmd_t cmd;
7242	void *data;
7243{
7244	ipftuneable_t *ta;
7245	ipftune_t tu;
7246	void *cookie;
7247	int error;
7248
7249	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7250	if (error != 0)
7251		return error;
7252
7253	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7254	cookie = tu.ipft_cookie;
7255	ta = NULL;
7256
7257	switch (cmd)
7258	{
7259	case SIOCIPFGETNEXT :
7260		/*
7261		 * If cookie is non-NULL, assume it to be a pointer to the last
7262		 * entry we looked at, so find it (if possible) and return a
7263		 * pointer to the next one after it.  The last entry in the
7264		 * the table is a NULL entry, so when we get to it, set cookie
7265		 * to NULL and return that, indicating end of list, erstwhile
7266		 * if we come in with cookie set to NULL, we are starting anew
7267		 * at the front of the list.
7268		 */
7269		if (cookie != NULL) {
7270			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7271						   cookie, &tu.ipft_cookie);
7272		} else {
7273			ta = softc->ipf_tuners;
7274			tu.ipft_cookie = ta + 1;
7275		}
7276		if (ta != NULL) {
7277			/*
7278			 * Entry found, but does the data pointed to by that
7279			 * row fit in what we can return?
7280			 */
7281			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7282				IPFERROR(76);
7283				return EINVAL;
7284			}
7285
7286			tu.ipft_vlong = 0;
7287			if (ta->ipft_sz == sizeof(u_long))
7288				tu.ipft_vlong = *ta->ipft_plong;
7289			else if (ta->ipft_sz == sizeof(u_int))
7290				tu.ipft_vint = *ta->ipft_pint;
7291			else if (ta->ipft_sz == sizeof(u_short))
7292				tu.ipft_vshort = *ta->ipft_pshort;
7293			else if (ta->ipft_sz == sizeof(u_char))
7294				tu.ipft_vchar = *ta->ipft_pchar;
7295
7296			tu.ipft_sz = ta->ipft_sz;
7297			tu.ipft_min = ta->ipft_min;
7298			tu.ipft_max = ta->ipft_max;
7299			tu.ipft_flags = ta->ipft_flags;
7300			bcopy(ta->ipft_name, tu.ipft_name,
7301			      MIN(sizeof(tu.ipft_name),
7302				  strlen(ta->ipft_name) + 1));
7303		}
7304		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7305		break;
7306
7307	case SIOCIPFGET :
7308	case SIOCIPFSET :
7309		/*
7310		 * Search by name or by cookie value for a particular entry
7311		 * in the tuning paramter table.
7312		 */
7313		IPFERROR(77);
7314		error = ESRCH;
7315		if (cookie != NULL) {
7316			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7317						   cookie, NULL);
7318			if (ta != NULL)
7319				error = 0;
7320		} else if (tu.ipft_name[0] != '\0') {
7321			ta = ipf_tune_findbyname(softc->ipf_tuners,
7322						 tu.ipft_name);
7323			if (ta != NULL)
7324				error = 0;
7325		}
7326		if (error != 0)
7327			break;
7328
7329		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7330			/*
7331			 * Fetch the tuning parameters for a particular value
7332			 */
7333			tu.ipft_vlong = 0;
7334			if (ta->ipft_sz == sizeof(u_long))
7335				tu.ipft_vlong = *ta->ipft_plong;
7336			else if (ta->ipft_sz == sizeof(u_int))
7337				tu.ipft_vint = *ta->ipft_pint;
7338			else if (ta->ipft_sz == sizeof(u_short))
7339				tu.ipft_vshort = *ta->ipft_pshort;
7340			else if (ta->ipft_sz == sizeof(u_char))
7341				tu.ipft_vchar = *ta->ipft_pchar;
7342			tu.ipft_cookie = ta;
7343			tu.ipft_sz = ta->ipft_sz;
7344			tu.ipft_min = ta->ipft_min;
7345			tu.ipft_max = ta->ipft_max;
7346			tu.ipft_flags = ta->ipft_flags;
7347			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7348
7349		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7350			/*
7351			 * Set an internal parameter.  The hard part here is
7352			 * getting the new value safely and correctly out of
7353			 * the kernel (given we only know its size, not type.)
7354			 */
7355			u_long in;
7356
7357			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7358			    (softc->ipf_running > 0)) {
7359				IPFERROR(78);
7360				error = EBUSY;
7361				break;
7362			}
7363
7364			in = tu.ipft_vlong;
7365			if (in < ta->ipft_min || in > ta->ipft_max) {
7366				IPFERROR(79);
7367				error = EINVAL;
7368				break;
7369			}
7370
7371			if (ta->ipft_func != NULL) {
7372				SPL_INT(s);
7373
7374				SPL_NET(s);
7375				error = (*ta->ipft_func)(softc, ta,
7376							 &tu.ipft_un);
7377				SPL_X(s);
7378
7379			} else if (ta->ipft_sz == sizeof(u_long)) {
7380				tu.ipft_vlong = *ta->ipft_plong;
7381				*ta->ipft_plong = in;
7382
7383			} else if (ta->ipft_sz == sizeof(u_int)) {
7384				tu.ipft_vint = *ta->ipft_pint;
7385				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7386
7387			} else if (ta->ipft_sz == sizeof(u_short)) {
7388				tu.ipft_vshort = *ta->ipft_pshort;
7389				*ta->ipft_pshort = (u_short)(in & 0xffff);
7390
7391			} else if (ta->ipft_sz == sizeof(u_char)) {
7392				tu.ipft_vchar = *ta->ipft_pchar;
7393				*ta->ipft_pchar = (u_char)(in & 0xff);
7394			}
7395			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7396		}
7397		break;
7398
7399	default :
7400		IPFERROR(80);
7401		error = EINVAL;
7402		break;
7403	}
7404
7405	return error;
7406}
7407
7408
7409/* ------------------------------------------------------------------------ */
7410/* Function:    ipf_zerostats                                               */
7411/* Returns:     int - 0 = success, else failure                             */
7412/* Parameters:  data(O) - pointer to pointer for copying data back to       */
7413/*                                                                          */
7414/* Copies the current statistics out to userspace and then zero's the       */
7415/* current ones in the kernel. The lock is only held across the bzero() as  */
7416/* the copyout may result in paging (ie network activity.)                  */
7417/* ------------------------------------------------------------------------ */
7418int
7419ipf_zerostats(softc, data)
7420	ipf_main_softc_t *softc;
7421	caddr_t	data;
7422{
7423	friostat_t fio;
7424	ipfobj_t obj;
7425	int error;
7426
7427	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7428	if (error != 0)
7429		return error;
7430	ipf_getstat(softc, &fio, obj.ipfo_rev);
7431	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7432	if (error != 0)
7433		return error;
7434
7435	WRITE_ENTER(&softc->ipf_mutex);
7436	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7437	RWLOCK_EXIT(&softc->ipf_mutex);
7438
7439	return 0;
7440}
7441
7442
7443/* ------------------------------------------------------------------------ */
7444/* Function:    ipf_resolvedest                                             */
7445/* Returns:     Nil                                                         */
7446/* Parameters:  softc(I) - pointer to soft context main structure           */
7447/*              base(I)  - where strings are stored                         */
7448/*              fdp(IO)  - pointer to destination information to resolve    */
7449/*              v(I)     - IP protocol version to match                     */
7450/*                                                                          */
7451/* Looks up an interface name in the frdest structure pointed to by fdp and */
7452/* if a matching name can be found for the particular IP protocol version   */
7453/* then store the interface pointer in the frdest struct.  If no match is   */
7454/* found, then set the interface pointer to be -1 as NULL is considered to  */
7455/* indicate there is no information at all in the structure.                */
7456/* ------------------------------------------------------------------------ */
7457int
7458ipf_resolvedest(softc, base, fdp, v)
7459	ipf_main_softc_t *softc;
7460	char *base;
7461	frdest_t *fdp;
7462	int v;
7463{
7464	int errval = 0;
7465	void *ifp;
7466
7467	ifp = NULL;
7468
7469	if (fdp->fd_name != -1) {
7470		if (fdp->fd_type == FRD_DSTLIST) {
7471			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7472						  IPLT_DSTLIST,
7473						  base + fdp->fd_name,
7474						  NULL);
7475			if (ifp == NULL) {
7476				IPFERROR(144);
7477				errval = ESRCH;
7478			}
7479		} else {
7480			ifp = GETIFP(base + fdp->fd_name, v);
7481			if (ifp == NULL)
7482				ifp = (void *)-1;
7483		}
7484	}
7485	fdp->fd_ptr = ifp;
7486
7487	return errval;
7488}
7489
7490
7491/* ------------------------------------------------------------------------ */
7492/* Function:    ipf_resolvenic                                              */
7493/* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7494/*                      pointer to interface structure for NIC              */
7495/* Parameters:  softc(I)- pointer to soft context main structure            */
7496/*              name(I) - complete interface name                           */
7497/*              v(I)    - IP protocol version                               */
7498/*                                                                          */
7499/* Look for a network interface structure that firstly has a matching name  */
7500/* to that passed in and that is also being used for that IP protocol       */
7501/* version (necessary on some platforms where there are separate listings   */
7502/* for both IPv4 and IPv6 on the same physical NIC.                         */
7503/* ------------------------------------------------------------------------ */
7504void *
7505ipf_resolvenic(softc, name, v)
7506	ipf_main_softc_t *softc;
7507	char *name;
7508	int v;
7509{
7510	void *nic;
7511
7512	softc = softc;	/* gcc -Wextra */
7513	if (name[0] == '\0')
7514		return NULL;
7515
7516	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7517		return NULL;
7518	}
7519
7520	nic = GETIFP(name, v);
7521	if (nic == NULL)
7522		nic = (void *)-1;
7523	return nic;
7524}
7525
7526
7527/* ------------------------------------------------------------------------ */
7528/* Function:    ipf_token_expire                                            */
7529/* Returns:     None.                                                       */
7530/* Parameters:  softc(I) - pointer to soft context main structure           */
7531/*                                                                          */
7532/* This function is run every ipf tick to see if there are any tokens that  */
7533/* have been held for too long and need to be freed up.                     */
7534/* ------------------------------------------------------------------------ */
7535void
7536ipf_token_expire(softc)
7537	ipf_main_softc_t *softc;
7538{
7539	ipftoken_t *it;
7540
7541	WRITE_ENTER(&softc->ipf_tokens);
7542	while ((it = softc->ipf_token_head) != NULL) {
7543		if (it->ipt_die > softc->ipf_ticks)
7544			break;
7545
7546		ipf_token_deref(softc, it);
7547	}
7548	RWLOCK_EXIT(&softc->ipf_tokens);
7549}
7550
7551
7552/* ------------------------------------------------------------------------ */
7553/* Function:    ipf_token_flush                                             */
7554/* Returns:     None.                                                       */
7555/* Parameters:  softc(I) - pointer to soft context main structure           */
7556/*                                                                          */
7557/* Loop through all of the existing tokens and call deref to see if they    */
7558/* can be freed. Normally a function like this might just loop on           */
7559/* ipf_token_head but there is a chance that a token might have a ref count */
7560/* of greater than one and in that case the the reference would drop twice  */
7561/* by code that is only entitled to drop it once.                           */
7562/* ------------------------------------------------------------------------ */
7563static void
7564ipf_token_flush(softc)
7565	ipf_main_softc_t *softc;
7566{
7567	ipftoken_t *it, *next;
7568
7569	WRITE_ENTER(&softc->ipf_tokens);
7570	for (it = softc->ipf_token_head; it != NULL; it = next) {
7571		next = it->ipt_next;
7572		(void) ipf_token_deref(softc, it);
7573	}
7574	RWLOCK_EXIT(&softc->ipf_tokens);
7575}
7576
7577
7578/* ------------------------------------------------------------------------ */
7579/* Function:    ipf_token_del                                               */
7580/* Returns:     int     - 0 = success, else error                           */
7581/* Parameters:  softc(I)- pointer to soft context main structure            */
7582/*              type(I) - the token type to match                           */
7583/*              uid(I)  - uid owning the token                              */
7584/*              ptr(I)  - context pointer for the token                     */
7585/*                                                                          */
7586/* This function looks for a a token in the current list that matches up    */
7587/* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7588/* call ipf_token_dewref() to remove it from the list. In the event that    */
7589/* the token has a reference held elsewhere, setting ipt_complete to 2      */
7590/* enables debugging to distinguish between the two paths that ultimately   */
7591/* lead to a token to be deleted.                                           */
7592/* ------------------------------------------------------------------------ */
7593int
7594ipf_token_del(softc, type, uid, ptr)
7595	ipf_main_softc_t *softc;
7596	int type, uid;
7597	void *ptr;
7598{
7599	ipftoken_t *it;
7600	int error;
7601
7602	IPFERROR(82);
7603	error = ESRCH;
7604
7605	WRITE_ENTER(&softc->ipf_tokens);
7606	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7607		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7608		    uid == it->ipt_uid) {
7609			it->ipt_complete = 2;
7610			ipf_token_deref(softc, it);
7611			error = 0;
7612			break;
7613		}
7614	}
7615	RWLOCK_EXIT(&softc->ipf_tokens);
7616
7617	return error;
7618}
7619
7620
7621/* ------------------------------------------------------------------------ */
7622/* Function:    ipf_token_mark_complete                                     */
7623/* Returns:     None.                                                       */
7624/* Parameters:  token(I) - pointer to token structure                       */
7625/*                                                                          */
7626/* Mark a token as being ineligable for being found with ipf_token_find.    */
7627/* ------------------------------------------------------------------------ */
7628void
7629ipf_token_mark_complete(token)
7630	ipftoken_t *token;
7631{
7632	if (token->ipt_complete == 0)
7633		token->ipt_complete = 1;
7634}
7635
7636
7637/* ------------------------------------------------------------------------ */
7638/* Function:    ipf_token_find                                               */
7639/* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7640/* Parameters:  softc(I)- pointer to soft context main structure            */
7641/*              type(I) - the token type to match                           */
7642/*              uid(I)  - uid owning the token                              */
7643/*              ptr(I)  - context pointer for the token                     */
7644/*                                                                          */
7645/* This function looks for a live token in the list of current tokens that  */
7646/* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7647/* allocated.  If one is found then it is moved to the top of the list of   */
7648/* currently active tokens.                                                 */
7649/* ------------------------------------------------------------------------ */
7650ipftoken_t *
7651ipf_token_find(softc, type, uid, ptr)
7652	ipf_main_softc_t *softc;
7653	int type, uid;
7654	void *ptr;
7655{
7656	ipftoken_t *it, *new;
7657
7658	KMALLOC(new, ipftoken_t *);
7659	if (new != NULL)
7660		bzero((char *)new, sizeof(*new));
7661
7662	WRITE_ENTER(&softc->ipf_tokens);
7663	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7664		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7665		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7666			break;
7667	}
7668
7669	if (it == NULL) {
7670		it = new;
7671		new = NULL;
7672		if (it == NULL) {
7673			RWLOCK_EXIT(&softc->ipf_tokens);
7674			return NULL;
7675		}
7676		it->ipt_ctx = ptr;
7677		it->ipt_uid = uid;
7678		it->ipt_type = type;
7679		it->ipt_ref = 1;
7680	} else {
7681		if (new != NULL) {
7682			KFREE(new);
7683			new = NULL;
7684		}
7685
7686		if (it->ipt_complete > 0)
7687			it = NULL;
7688		else
7689			ipf_token_unlink(softc, it);
7690	}
7691
7692	if (it != NULL) {
7693		it->ipt_pnext = softc->ipf_token_tail;
7694		*softc->ipf_token_tail = it;
7695		softc->ipf_token_tail = &it->ipt_next;
7696		it->ipt_next = NULL;
7697		it->ipt_ref++;
7698
7699		it->ipt_die = softc->ipf_ticks + 20;
7700	}
7701
7702	RWLOCK_EXIT(&softc->ipf_tokens);
7703
7704	return it;
7705}
7706
7707
7708/* ------------------------------------------------------------------------ */
7709/* Function:    ipf_token_unlink                                            */
7710/* Returns:     None.                                                       */
7711/* Parameters:  softc(I) - pointer to soft context main structure           */
7712/*              token(I) - pointer to token structure                       */
7713/* Write Locks: ipf_tokens                                                  */
7714/*                                                                          */
7715/* This function unlinks a token structure from the linked list of tokens   */
7716/* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7717/* but the tail does due to the linked list implementation.                 */
7718/* ------------------------------------------------------------------------ */
7719static void
7720ipf_token_unlink(softc, token)
7721	ipf_main_softc_t *softc;
7722	ipftoken_t *token;
7723{
7724
7725	if (softc->ipf_token_tail == &token->ipt_next)
7726		softc->ipf_token_tail = token->ipt_pnext;
7727
7728	*token->ipt_pnext = token->ipt_next;
7729	if (token->ipt_next != NULL)
7730		token->ipt_next->ipt_pnext = token->ipt_pnext;
7731	token->ipt_next = NULL;
7732	token->ipt_pnext = NULL;
7733}
7734
7735
7736/* ------------------------------------------------------------------------ */
7737/* Function:    ipf_token_deref                                             */
7738/* Returns:     int      - 0 == token freed, else reference count           */
7739/* Parameters:  softc(I) - pointer to soft context main structure           */
7740/*              token(I) - pointer to token structure                       */
7741/* Write Locks: ipf_tokens                                                  */
7742/*                                                                          */
7743/* Drop the reference count on the token structure and if it drops to zero, */
7744/* call the dereference function for the token type because it is then      */
7745/* possible to free the token data structure.                               */
7746/* ------------------------------------------------------------------------ */
7747int
7748ipf_token_deref(softc, token)
7749	ipf_main_softc_t *softc;
7750	ipftoken_t *token;
7751{
7752	void *data, **datap;
7753
7754	ASSERT(token->ipt_ref > 0);
7755	token->ipt_ref--;
7756	if (token->ipt_ref > 0)
7757		return token->ipt_ref;
7758
7759	data = token->ipt_data;
7760	datap = &data;
7761
7762	if ((data != NULL) && (data != (void *)-1)) {
7763		switch (token->ipt_type)
7764		{
7765		case IPFGENITER_IPF :
7766			(void) ipf_derefrule(softc, (frentry_t **)datap);
7767			break;
7768		case IPFGENITER_IPNAT :
7769			WRITE_ENTER(&softc->ipf_nat);
7770			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7771			RWLOCK_EXIT(&softc->ipf_nat);
7772			break;
7773		case IPFGENITER_NAT :
7774			ipf_nat_deref(softc, (nat_t **)datap);
7775			break;
7776		case IPFGENITER_STATE :
7777			ipf_state_deref(softc, (ipstate_t **)datap);
7778			break;
7779		case IPFGENITER_FRAG :
7780			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7781			break;
7782		case IPFGENITER_NATFRAG :
7783			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7784			break;
7785		case IPFGENITER_HOSTMAP :
7786			WRITE_ENTER(&softc->ipf_nat);
7787			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7788			RWLOCK_EXIT(&softc->ipf_nat);
7789			break;
7790		default :
7791			ipf_lookup_iterderef(softc, token->ipt_type, data);
7792			break;
7793		}
7794	}
7795
7796	ipf_token_unlink(softc, token);
7797	KFREE(token);
7798	return 0;
7799}
7800
7801
7802/* ------------------------------------------------------------------------ */
7803/* Function:    ipf_nextrule                                                */
7804/* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7805/* Parameters:  softc(I)    - pointer to soft context main structure        */
7806/*              fr(I)       - pointer to filter rule                        */
7807/*              out(I)      - 1 == out rules, 0 == input rules              */
7808/*                                                                          */
7809/* Starting with "fr", find the next rule to visit. This includes visiting  */
7810/* the list of rule groups if either fr is NULL (empty list) or it is the   */
7811/* last rule in the list. When walking rule lists, it is either input or    */
7812/* output rules that are returned, never both.                              */
7813/* ------------------------------------------------------------------------ */
7814static frentry_t *
7815ipf_nextrule(softc, active, unit, fr, out)
7816	ipf_main_softc_t *softc;
7817	int active, unit;
7818	frentry_t *fr;
7819	int out;
7820{
7821	frentry_t *next;
7822	frgroup_t *fg;
7823
7824	if (fr != NULL && fr->fr_group != -1) {
7825		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7826				   unit, active, NULL);
7827		if (fg != NULL)
7828			fg = fg->fg_next;
7829	} else {
7830		fg = softc->ipf_groups[unit][active];
7831	}
7832
7833	while (fg != NULL) {
7834		next = fg->fg_start;
7835		while (next != NULL) {
7836			if (out) {
7837				if (next->fr_flags & FR_OUTQUE)
7838					return next;
7839			} else if (next->fr_flags & FR_INQUE) {
7840				return next;
7841			}
7842			next = next->fr_next;
7843		}
7844		if (next == NULL)
7845			fg = fg->fg_next;
7846	}
7847
7848	return NULL;
7849}
7850
7851/* ------------------------------------------------------------------------ */
7852/* Function:    ipf_getnextrule                                             */
7853/* Returns:     int - 0 = success, else error                               */
7854/* Parameters:  softc(I)- pointer to soft context main structure            */
7855/*              t(I)   - pointer to destination information to resolve      */
7856/*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7857/*                                                                          */
7858/* This function's first job is to bring in the ipfruleiter_t structure via */
7859/* the ipfobj_t structure to determine what should be the next rule to      */
7860/* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7861/* find the 'next rule'.  This may include searching rule group lists or    */
7862/* just be as simple as looking at the 'next' field in the rule structure.  */
7863/* When we have found the rule to return, increase its reference count and  */
7864/* if we used an existing rule to get here, decrease its reference count.   */
7865/* ------------------------------------------------------------------------ */
7866int
7867ipf_getnextrule(softc, t, ptr)
7868	ipf_main_softc_t *softc;
7869	ipftoken_t *t;
7870	void *ptr;
7871{
7872	frentry_t *fr, *next, zero;
7873	ipfruleiter_t it;
7874	int error, out;
7875	frgroup_t *fg;
7876	ipfobj_t obj;
7877	int predict;
7878	char *dst;
7879	int unit;
7880
7881	if (t == NULL || ptr == NULL) {
7882		IPFERROR(84);
7883		return EFAULT;
7884	}
7885
7886	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7887	if (error != 0)
7888		return error;
7889
7890	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7891		IPFERROR(85);
7892		return EINVAL;
7893	}
7894	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7895		IPFERROR(86);
7896		return EINVAL;
7897	}
7898	if (it.iri_nrules == 0) {
7899		IPFERROR(87);
7900		return ENOSPC;
7901	}
7902	if (it.iri_rule == NULL) {
7903		IPFERROR(88);
7904		return EFAULT;
7905	}
7906
7907	fg = NULL;
7908	fr = t->ipt_data;
7909	if ((it.iri_inout & F_OUT) != 0)
7910		out = 1;
7911	else
7912		out = 0;
7913	if ((it.iri_inout & F_ACIN) != 0)
7914		unit = IPL_LOGCOUNT;
7915	else
7916		unit = IPL_LOGIPF;
7917
7918	READ_ENTER(&softc->ipf_mutex);
7919	if (fr == NULL) {
7920		if (*it.iri_group == '\0') {
7921			if (unit == IPL_LOGCOUNT) {
7922				next = softc->ipf_acct[out][it.iri_active];
7923			} else {
7924				next = softc->ipf_rules[out][it.iri_active];
7925			}
7926			if (next == NULL)
7927				next = ipf_nextrule(softc, it.iri_active,
7928						    unit, NULL, out);
7929		} else {
7930			fg = ipf_findgroup(softc, it.iri_group, unit,
7931					   it.iri_active, NULL);
7932			if (fg != NULL)
7933				next = fg->fg_start;
7934			else
7935				next = NULL;
7936		}
7937	} else {
7938		next = fr->fr_next;
7939		if (next == NULL)
7940			next = ipf_nextrule(softc, it.iri_active, unit,
7941					    fr, out);
7942	}
7943
7944	if (next != NULL && next->fr_next != NULL)
7945		predict = 1;
7946	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7947		predict = 1;
7948	else
7949		predict = 0;
7950
7951	if (fr != NULL)
7952		(void) ipf_derefrule(softc, &fr);
7953
7954	obj.ipfo_type = IPFOBJ_FRENTRY;
7955	dst = (char *)it.iri_rule;
7956
7957	if (next != NULL) {
7958		obj.ipfo_size = next->fr_size;
7959		MUTEX_ENTER(&next->fr_lock);
7960		next->fr_ref++;
7961		MUTEX_EXIT(&next->fr_lock);
7962		t->ipt_data = next;
7963	} else {
7964		obj.ipfo_size = sizeof(frentry_t);
7965		bzero(&zero, sizeof(zero));
7966		next = &zero;
7967		t->ipt_data = NULL;
7968	}
7969	it.iri_rule = predict ? next : NULL;
7970	if (predict == 0)
7971		ipf_token_mark_complete(t);
7972
7973	RWLOCK_EXIT(&softc->ipf_mutex);
7974
7975	obj.ipfo_ptr = dst;
7976	error = ipf_outobjk(softc, &obj, next);
7977	if (error == 0 && t->ipt_data != NULL) {
7978		dst += obj.ipfo_size;
7979		if (next->fr_data != NULL) {
7980			ipfobj_t dobj;
7981
7982			if (next->fr_type == FR_T_IPFEXPR)
7983				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7984			else
7985				dobj.ipfo_type = IPFOBJ_FRIPF;
7986			dobj.ipfo_size = next->fr_dsize;
7987			dobj.ipfo_rev = obj.ipfo_rev;
7988			dobj.ipfo_ptr = dst;
7989			error = ipf_outobjk(softc, &dobj, next->fr_data);
7990		}
7991	}
7992
7993	if ((fr != NULL) && (next == &zero))
7994		(void) ipf_derefrule(softc, &fr);
7995
7996	return error;
7997}
7998
7999
8000/* ------------------------------------------------------------------------ */
8001/* Function:    ipf_frruleiter                                              */
8002/* Returns:     int - 0 = success, else error                               */
8003/* Parameters:  softc(I)- pointer to soft context main structure            */
8004/*              data(I) - the token type to match                           */
8005/*              uid(I)  - uid owning the token                              */
8006/*              ptr(I)  - context pointer for the token                     */
8007/*                                                                          */
8008/* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8009/* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8010/* the process doing the ioctl and use that to ask for the next rule.       */
8011/* ------------------------------------------------------------------------ */
8012static int
8013ipf_frruleiter(softc, data, uid, ctx)
8014	ipf_main_softc_t *softc;
8015	void *data, *ctx;
8016	int uid;
8017{
8018	ipftoken_t *token;
8019	ipfruleiter_t it;
8020	ipfobj_t obj;
8021	int error;
8022
8023	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8024	if (token != NULL) {
8025		error = ipf_getnextrule(softc, token, data);
8026		WRITE_ENTER(&softc->ipf_tokens);
8027		ipf_token_deref(softc, token);
8028		RWLOCK_EXIT(&softc->ipf_tokens);
8029	} else {
8030		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8031		if (error != 0)
8032			return error;
8033		it.iri_rule = NULL;
8034		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8035	}
8036
8037	return error;
8038}
8039
8040
8041/* ------------------------------------------------------------------------ */
8042/* Function:    ipf_geniter                                                 */
8043/* Returns:     int - 0 = success, else error                               */
8044/* Parameters:  softc(I) - pointer to soft context main structure           */
8045/*              token(I) - pointer to ipftoken_t structure                  */
8046/*              itp(I)   - pointer to iterator data                         */
8047/*                                                                          */
8048/* Decide which iterator function to call using information passed through  */
8049/* the ipfgeniter_t structure at itp.                                       */
8050/* ------------------------------------------------------------------------ */
8051static int
8052ipf_geniter(softc, token, itp)
8053	ipf_main_softc_t *softc;
8054	ipftoken_t *token;
8055	ipfgeniter_t *itp;
8056{
8057	int error;
8058
8059	switch (itp->igi_type)
8060	{
8061	case IPFGENITER_FRAG :
8062		error = ipf_frag_pkt_next(softc, token, itp);
8063		break;
8064	default :
8065		IPFERROR(92);
8066		error = EINVAL;
8067		break;
8068	}
8069
8070	return error;
8071}
8072
8073
8074/* ------------------------------------------------------------------------ */
8075/* Function:    ipf_genericiter                                             */
8076/* Returns:     int - 0 = success, else error                               */
8077/* Parameters:  softc(I)- pointer to soft context main structure            */
8078/*              data(I) - the token type to match                           */
8079/*              uid(I)  - uid owning the token                              */
8080/*              ptr(I)  - context pointer for the token                     */
8081/*                                                                          */
8082/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8083/* ------------------------------------------------------------------------ */
8084int
8085ipf_genericiter(softc, data, uid, ctx)
8086	ipf_main_softc_t *softc;
8087	void *data, *ctx;
8088	int uid;
8089{
8090	ipftoken_t *token;
8091	ipfgeniter_t iter;
8092	int error;
8093
8094	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8095	if (error != 0)
8096		return error;
8097
8098	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8099	if (token != NULL) {
8100		token->ipt_subtype = iter.igi_type;
8101		error = ipf_geniter(softc, token, &iter);
8102		WRITE_ENTER(&softc->ipf_tokens);
8103		ipf_token_deref(softc, token);
8104		RWLOCK_EXIT(&softc->ipf_tokens);
8105	} else {
8106		IPFERROR(93);
8107		error = 0;
8108	}
8109
8110	return error;
8111}
8112
8113
8114/* ------------------------------------------------------------------------ */
8115/* Function:    ipf_ipf_ioctl                                               */
8116/* Returns:     int - 0 = success, else error                               */
8117/* Parameters:  softc(I)- pointer to soft context main structure           */
8118/*              data(I) - the token type to match                           */
8119/*              cmd(I)  - the ioctl command number                          */
8120/*              mode(I) - mode flags for the ioctl                          */
8121/*              uid(I)  - uid owning the token                              */
8122/*              ptr(I)  - context pointer for the token                     */
8123/*                                                                          */
8124/* This function handles all of the ioctl command that are actually isssued */
8125/* to the /dev/ipl device.                                                  */
8126/* ------------------------------------------------------------------------ */
8127int
8128ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8129	ipf_main_softc_t *softc;
8130	caddr_t data;
8131	ioctlcmd_t cmd;
8132	int mode, uid;
8133	void *ctx;
8134{
8135	friostat_t fio;
8136	int error, tmp;
8137	ipfobj_t obj;
8138	SPL_INT(s);
8139
8140	switch (cmd)
8141	{
8142	case SIOCFRENB :
8143		if (!(mode & FWRITE)) {
8144			IPFERROR(94);
8145			error = EPERM;
8146		} else {
8147			error = BCOPYIN(data, &tmp, sizeof(tmp));
8148			if (error != 0) {
8149				IPFERROR(95);
8150				error = EFAULT;
8151				break;
8152			}
8153
8154			WRITE_ENTER(&softc->ipf_global);
8155			if (tmp) {
8156				if (softc->ipf_running > 0)
8157					error = 0;
8158				else
8159					error = ipfattach(softc);
8160				if (error == 0)
8161					softc->ipf_running = 1;
8162				else
8163					(void) ipfdetach(softc);
8164			} else {
8165				if (softc->ipf_running == 1)
8166					error = ipfdetach(softc);
8167				else
8168					error = 0;
8169				if (error == 0)
8170					softc->ipf_running = -1;
8171			}
8172			RWLOCK_EXIT(&softc->ipf_global);
8173		}
8174		break;
8175
8176	case SIOCIPFSET :
8177		if (!(mode & FWRITE)) {
8178			IPFERROR(96);
8179			error = EPERM;
8180			break;
8181		}
8182		/* FALLTHRU */
8183	case SIOCIPFGETNEXT :
8184	case SIOCIPFGET :
8185		error = ipf_ipftune(softc, cmd, (void *)data);
8186		break;
8187
8188	case SIOCSETFF :
8189		if (!(mode & FWRITE)) {
8190			IPFERROR(97);
8191			error = EPERM;
8192		} else {
8193			error = BCOPYIN(data, &softc->ipf_flags,
8194					sizeof(softc->ipf_flags));
8195			if (error != 0) {
8196				IPFERROR(98);
8197				error = EFAULT;
8198			}
8199		}
8200		break;
8201
8202	case SIOCGETFF :
8203		error = BCOPYOUT(&softc->ipf_flags, data,
8204				 sizeof(softc->ipf_flags));
8205		if (error != 0) {
8206			IPFERROR(99);
8207			error = EFAULT;
8208		}
8209		break;
8210
8211	case SIOCFUNCL :
8212		error = ipf_resolvefunc(softc, (void *)data);
8213		break;
8214
8215	case SIOCINAFR :
8216	case SIOCRMAFR :
8217	case SIOCADAFR :
8218	case SIOCZRLST :
8219		if (!(mode & FWRITE)) {
8220			IPFERROR(100);
8221			error = EPERM;
8222		} else {
8223			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8224					  softc->ipf_active, 1);
8225		}
8226		break;
8227
8228	case SIOCINIFR :
8229	case SIOCRMIFR :
8230	case SIOCADIFR :
8231		if (!(mode & FWRITE)) {
8232			IPFERROR(101);
8233			error = EPERM;
8234		} else {
8235			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8236					  1 - softc->ipf_active, 1);
8237		}
8238		break;
8239
8240	case SIOCSWAPA :
8241		if (!(mode & FWRITE)) {
8242			IPFERROR(102);
8243			error = EPERM;
8244		} else {
8245			WRITE_ENTER(&softc->ipf_mutex);
8246			error = BCOPYOUT(&softc->ipf_active, data,
8247					 sizeof(softc->ipf_active));
8248			if (error != 0) {
8249				IPFERROR(103);
8250				error = EFAULT;
8251			} else {
8252				softc->ipf_active = 1 - softc->ipf_active;
8253			}
8254			RWLOCK_EXIT(&softc->ipf_mutex);
8255		}
8256		break;
8257
8258	case SIOCGETFS :
8259		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8260				  IPFOBJ_IPFSTAT);
8261		if (error != 0)
8262			break;
8263		ipf_getstat(softc, &fio, obj.ipfo_rev);
8264		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8265		break;
8266
8267	case SIOCFRZST :
8268		if (!(mode & FWRITE)) {
8269			IPFERROR(104);
8270			error = EPERM;
8271		} else
8272			error = ipf_zerostats(softc, (caddr_t)data);
8273		break;
8274
8275	case SIOCIPFFL :
8276		if (!(mode & FWRITE)) {
8277			IPFERROR(105);
8278			error = EPERM;
8279		} else {
8280			error = BCOPYIN(data, &tmp, sizeof(tmp));
8281			if (!error) {
8282				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8283				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8284				if (error != 0) {
8285					IPFERROR(106);
8286					error = EFAULT;
8287				}
8288			} else {
8289				IPFERROR(107);
8290				error = EFAULT;
8291			}
8292		}
8293		break;
8294
8295#ifdef USE_INET6
8296	case SIOCIPFL6 :
8297		if (!(mode & FWRITE)) {
8298			IPFERROR(108);
8299			error = EPERM;
8300		} else {
8301			error = BCOPYIN(data, &tmp, sizeof(tmp));
8302			if (!error) {
8303				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8304				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8305				if (error != 0) {
8306					IPFERROR(109);
8307					error = EFAULT;
8308				}
8309			} else {
8310				IPFERROR(110);
8311				error = EFAULT;
8312			}
8313		}
8314		break;
8315#endif
8316
8317	case SIOCSTLCK :
8318		if (!(mode & FWRITE)) {
8319			IPFERROR(122);
8320			error = EPERM;
8321		} else {
8322			error = BCOPYIN(data, &tmp, sizeof(tmp));
8323			if (error == 0) {
8324				ipf_state_setlock(softc->ipf_state_soft, tmp);
8325				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8326				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8327				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8328			} else {
8329				IPFERROR(111);
8330				error = EFAULT;
8331			}
8332		}
8333		break;
8334
8335#ifdef	IPFILTER_LOG
8336	case SIOCIPFFB :
8337		if (!(mode & FWRITE)) {
8338			IPFERROR(112);
8339			error = EPERM;
8340		} else {
8341			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8342			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8343			if (error) {
8344				IPFERROR(113);
8345				error = EFAULT;
8346			}
8347		}
8348		break;
8349#endif /* IPFILTER_LOG */
8350
8351	case SIOCFRSYN :
8352		if (!(mode & FWRITE)) {
8353			IPFERROR(114);
8354			error = EPERM;
8355		} else {
8356			WRITE_ENTER(&softc->ipf_global);
8357#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8358			error = ipfsync();
8359#else
8360			ipf_sync(softc, NULL);
8361			error = 0;
8362#endif
8363			RWLOCK_EXIT(&softc->ipf_global);
8364
8365		}
8366		break;
8367
8368	case SIOCGFRST :
8369		error = ipf_outobj(softc, (void *)data,
8370				   ipf_frag_stats(softc->ipf_frag_soft),
8371				   IPFOBJ_FRAGSTAT);
8372		break;
8373
8374#ifdef	IPFILTER_LOG
8375	case FIONREAD :
8376		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8377		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8378		break;
8379#endif
8380
8381	case SIOCIPFITER :
8382		SPL_SCHED(s);
8383		error = ipf_frruleiter(softc, data, uid, ctx);
8384		SPL_X(s);
8385		break;
8386
8387	case SIOCGENITER :
8388		SPL_SCHED(s);
8389		error = ipf_genericiter(softc, data, uid, ctx);
8390		SPL_X(s);
8391		break;
8392
8393	case SIOCIPFDELTOK :
8394		error = BCOPYIN(data, &tmp, sizeof(tmp));
8395		if (error == 0) {
8396			SPL_SCHED(s);
8397			error = ipf_token_del(softc, tmp, uid, ctx);
8398			SPL_X(s);
8399		}
8400		break;
8401
8402	default :
8403		IPFERROR(115);
8404		error = EINVAL;
8405		break;
8406	}
8407
8408	return error;
8409}
8410
8411
8412/* ------------------------------------------------------------------------ */
8413/* Function:    ipf_decaps                                                  */
8414/* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8415/*                           flags indicating packet filtering decision.    */
8416/* Parameters:  fin(I)     - pointer to packet information                  */
8417/*              pass(I)    - IP protocol version to match                   */
8418/*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8419/*                                                                          */
8420/* This function is called for packets that are wrapt up in other packets,  */
8421/* for example, an IP packet that is the entire data segment for another IP */
8422/* packet.  If the basic constraints for this are satisfied, change the     */
8423/* buffer to point to the start of the inner packet and start processing    */
8424/* rules belonging to the head group this rule specifies.                   */
8425/* ------------------------------------------------------------------------ */
8426u_32_t
8427ipf_decaps(fin, pass, l5proto)
8428	fr_info_t *fin;
8429	u_32_t pass;
8430	int l5proto;
8431{
8432	fr_info_t fin2, *fino = NULL;
8433	int elen, hlen, nh;
8434	grehdr_t gre;
8435	ip_t *ip;
8436	mb_t *m;
8437
8438	if ((fin->fin_flx & FI_COALESCE) == 0)
8439		if (ipf_coalesce(fin) == -1)
8440			goto cantdecaps;
8441
8442	m = fin->fin_m;
8443	hlen = fin->fin_hlen;
8444
8445	switch (fin->fin_p)
8446	{
8447	case IPPROTO_UDP :
8448		/*
8449		 * In this case, the specific protocol being decapsulated
8450		 * inside UDP frames comes from the rule.
8451		 */
8452		nh = fin->fin_fr->fr_icode;
8453		break;
8454
8455	case IPPROTO_GRE :	/* 47 */
8456		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8457		hlen += sizeof(grehdr_t);
8458		if (gre.gr_R|gre.gr_s)
8459			goto cantdecaps;
8460		if (gre.gr_C)
8461			hlen += 4;
8462		if (gre.gr_K)
8463			hlen += 4;
8464		if (gre.gr_S)
8465			hlen += 4;
8466
8467		nh = IPPROTO_IP;
8468
8469		/*
8470		 * If the routing options flag is set, validate that it is
8471		 * there and bounce over it.
8472		 */
8473#if 0
8474		/* This is really heavy weight and lots of room for error, */
8475		/* so for now, put it off and get the simple stuff right.  */
8476		if (gre.gr_R) {
8477			u_char off, len, *s;
8478			u_short af;
8479			int end;
8480
8481			end = 0;
8482			s = fin->fin_dp;
8483			s += hlen;
8484			aplen = fin->fin_plen - hlen;
8485			while (aplen > 3) {
8486				af = (s[0] << 8) | s[1];
8487				off = s[2];
8488				len = s[3];
8489				aplen -= 4;
8490				s += 4;
8491				if (af == 0 && len == 0) {
8492					end = 1;
8493					break;
8494				}
8495				if (aplen < len)
8496					break;
8497				s += len;
8498				aplen -= len;
8499			}
8500			if (end != 1)
8501				goto cantdecaps;
8502			hlen = s - (u_char *)fin->fin_dp;
8503		}
8504#endif
8505		break;
8506
8507#ifdef IPPROTO_IPIP
8508	case IPPROTO_IPIP :	/* 4 */
8509#endif
8510		nh = IPPROTO_IP;
8511		break;
8512
8513	default :	/* Includes ESP, AH is special for IPv4 */
8514		goto cantdecaps;
8515	}
8516
8517	switch (nh)
8518	{
8519	case IPPROTO_IP :
8520	case IPPROTO_IPV6 :
8521		break;
8522	default :
8523		goto cantdecaps;
8524	}
8525
8526	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8527	fino = fin;
8528	fin = &fin2;
8529	elen = hlen;
8530#if defined(MENTAT) && defined(_KERNEL)
8531	m->b_rptr += elen;
8532#else
8533	m->m_data += elen;
8534	m->m_len -= elen;
8535#endif
8536	fin->fin_plen -= elen;
8537
8538	ip = (ip_t *)((char *)fin->fin_ip + elen);
8539
8540	/*
8541	 * Make sure we have at least enough data for the network layer
8542	 * header.
8543	 */
8544	if (IP_V(ip) == 4)
8545		hlen = IP_HL(ip) << 2;
8546#ifdef USE_INET6
8547	else if (IP_V(ip) == 6)
8548		hlen = sizeof(ip6_t);
8549#endif
8550	else
8551		goto cantdecaps2;
8552
8553	if (fin->fin_plen < hlen)
8554		goto cantdecaps2;
8555
8556	fin->fin_dp = (char *)ip + hlen;
8557
8558	if (IP_V(ip) == 4) {
8559		/*
8560		 * Perform IPv4 header checksum validation.
8561		 */
8562		if (ipf_cksum((u_short *)ip, hlen))
8563			goto cantdecaps2;
8564	}
8565
8566	if (ipf_makefrip(hlen, ip, fin) == -1) {
8567cantdecaps2:
8568		if (m != NULL) {
8569#if defined(MENTAT) && defined(_KERNEL)
8570			m->b_rptr -= elen;
8571#else
8572			m->m_data -= elen;
8573			m->m_len += elen;
8574#endif
8575		}
8576cantdecaps:
8577		DT1(frb_decapfrip, fr_info_t *, fin);
8578		pass &= ~FR_CMDMASK;
8579		pass |= FR_BLOCK|FR_QUICK;
8580		fin->fin_reason = FRB_DECAPFRIP;
8581		return -1;
8582	}
8583
8584	pass = ipf_scanlist(fin, pass);
8585
8586	/*
8587	 * Copy the packet filter "result" fields out of the fr_info_t struct
8588	 * that is local to the decapsulation processing and back into the
8589	 * one we were called with.
8590	 */
8591	fino->fin_flx = fin->fin_flx;
8592	fino->fin_rev = fin->fin_rev;
8593	fino->fin_icode = fin->fin_icode;
8594	fino->fin_rule = fin->fin_rule;
8595	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8596	fino->fin_fr = fin->fin_fr;
8597	fino->fin_error = fin->fin_error;
8598	fino->fin_mp = fin->fin_mp;
8599	fino->fin_m = fin->fin_m;
8600	m = fin->fin_m;
8601	if (m != NULL) {
8602#if defined(MENTAT) && defined(_KERNEL)
8603		m->b_rptr -= elen;
8604#else
8605		m->m_data -= elen;
8606		m->m_len += elen;
8607#endif
8608	}
8609	return pass;
8610}
8611
8612
8613/* ------------------------------------------------------------------------ */
8614/* Function:    ipf_matcharray_load                                         */
8615/* Returns:     int         - 0 = success, else error                       */
8616/* Parameters:  softc(I)    - pointer to soft context main structure        */
8617/*              data(I)     - pointer to ioctl data                         */
8618/*              objp(I)     - ipfobj_t structure to load data into          */
8619/*              arrayptr(I) - pointer to location to store array pointer    */
8620/*                                                                          */
8621/* This function loads in a mathing array through the ipfobj_t struct that  */
8622/* describes it.  Sanity checking and array size limitations are enforced   */
8623/* in this function to prevent userspace from trying to load in something   */
8624/* that is insanely big.  Once the size of the array is known, the memory   */
8625/* required is malloc'd and returned through changing *arrayptr.  The       */
8626/* contents of the array are verified before returning.  Only in the event  */
8627/* of a successful call is the caller required to free up the malloc area.  */
8628/* ------------------------------------------------------------------------ */
8629int
8630ipf_matcharray_load(softc, data, objp, arrayptr)
8631	ipf_main_softc_t *softc;
8632	caddr_t data;
8633	ipfobj_t *objp;
8634	int **arrayptr;
8635{
8636	int arraysize, *array, error;
8637
8638	*arrayptr = NULL;
8639
8640	error = BCOPYIN(data, objp, sizeof(*objp));
8641	if (error != 0) {
8642		IPFERROR(116);
8643		return EFAULT;
8644	}
8645
8646	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8647		IPFERROR(117);
8648		return EINVAL;
8649	}
8650
8651	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8652	    (objp->ipfo_size > 1024)) {
8653		IPFERROR(118);
8654		return EINVAL;
8655	}
8656
8657	arraysize = objp->ipfo_size * sizeof(*array);
8658	KMALLOCS(array, int *, arraysize);
8659	if (array == NULL) {
8660		IPFERROR(119);
8661		return ENOMEM;
8662	}
8663
8664	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8665	if (error != 0) {
8666		KFREES(array, arraysize);
8667		IPFERROR(120);
8668		return EFAULT;
8669	}
8670
8671	if (ipf_matcharray_verify(array, arraysize) != 0) {
8672		KFREES(array, arraysize);
8673		IPFERROR(121);
8674		return EINVAL;
8675	}
8676
8677	*arrayptr = array;
8678	return 0;
8679}
8680
8681
8682/* ------------------------------------------------------------------------ */
8683/* Function:    ipf_matcharray_verify                                       */
8684/* Returns:     Nil                                                         */
8685/* Parameters:  array(I)     - pointer to matching array                    */
8686/*              arraysize(I) - number of elements in the array              */
8687/*                                                                          */
8688/* Verify the contents of a matching array by stepping through each element */
8689/* in it.  The actual commands in the array are not verified for            */
8690/* correctness, only that all of the sizes are correctly within limits.     */
8691/* ------------------------------------------------------------------------ */
8692int
8693ipf_matcharray_verify(array, arraysize)
8694	int *array, arraysize;
8695{
8696	int i, nelem, maxidx;
8697	ipfexp_t *e;
8698
8699	nelem = arraysize / sizeof(*array);
8700
8701	/*
8702	 * Currently, it makes no sense to have an array less than 6
8703	 * elements long - the initial size at the from, a single operation
8704	 * (minimum 4 in length) and a trailer, for a total of 6.
8705	 */
8706	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8707		return -1;
8708	}
8709
8710	/*
8711	 * Verify the size of data pointed to by array with how long
8712	 * the array claims to be itself.
8713	 */
8714	if (array[0] * sizeof(*array) != arraysize) {
8715		return -1;
8716	}
8717
8718	maxidx = nelem - 1;
8719	/*
8720	 * The last opcode in this array should be an IPF_EXP_END.
8721	 */
8722	if (array[maxidx] != IPF_EXP_END) {
8723		return -1;
8724	}
8725
8726	for (i = 1; i < maxidx; ) {
8727		e = (ipfexp_t *)(array + i);
8728
8729		/*
8730		 * The length of the bits to check must be at least 1
8731		 * (or else there is nothing to comapre with!) and it
8732		 * cannot exceed the length of the data present.
8733		 */
8734		if ((e->ipfe_size < 1 ) ||
8735		    (e->ipfe_size + i > maxidx)) {
8736			return -1;
8737		}
8738		i += e->ipfe_size;
8739	}
8740	return 0;
8741}
8742
8743
8744/* ------------------------------------------------------------------------ */
8745/* Function:    ipf_fr_matcharray                                           */
8746/* Returns:     int      - 0 = match failed, else positive match            */
8747/* Parameters:  fin(I)   - pointer to packet information                    */
8748/*              array(I) - pointer to matching array                        */
8749/*                                                                          */
8750/* This function is used to apply a matching array against a packet and     */
8751/* return an indication of whether or not the packet successfully matches   */
8752/* all of the commands in it.                                               */
8753/* ------------------------------------------------------------------------ */
8754static int
8755ipf_fr_matcharray(fin, array)
8756	fr_info_t *fin;
8757	int *array;
8758{
8759	int i, n, *x, rv, p;
8760	ipfexp_t *e;
8761
8762	rv = 0;
8763	n = array[0];
8764	x = array + 1;
8765
8766	for (; n > 0; x += 3 + x[3], rv = 0) {
8767		e = (ipfexp_t *)x;
8768		if (e->ipfe_cmd == IPF_EXP_END)
8769			break;
8770		n -= e->ipfe_size;
8771
8772		/*
8773		 * The upper 16 bits currently store the protocol value.
8774		 * This is currently used with TCP and UDP port compares and
8775		 * allows "tcp.port = 80" without requiring an explicit
8776		 " "ip.pr = tcp" first.
8777		 */
8778		p = e->ipfe_cmd >> 16;
8779		if ((p != 0) && (p != fin->fin_p))
8780			break;
8781
8782		switch (e->ipfe_cmd)
8783		{
8784		case IPF_EXP_IP_PR :
8785			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8786				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8787			}
8788			break;
8789
8790		case IPF_EXP_IP_SRCADDR :
8791			if (fin->fin_v != 4)
8792				break;
8793			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8794				rv |= ((fin->fin_saddr &
8795					e->ipfe_arg0[i * 2 + 1]) ==
8796				       e->ipfe_arg0[i * 2]);
8797			}
8798			break;
8799
8800		case IPF_EXP_IP_DSTADDR :
8801			if (fin->fin_v != 4)
8802				break;
8803			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8804				rv |= ((fin->fin_daddr &
8805					e->ipfe_arg0[i * 2 + 1]) ==
8806				       e->ipfe_arg0[i * 2]);
8807			}
8808			break;
8809
8810		case IPF_EXP_IP_ADDR :
8811			if (fin->fin_v != 4)
8812				break;
8813			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8814				rv |= ((fin->fin_saddr &
8815					e->ipfe_arg0[i * 2 + 1]) ==
8816				       e->ipfe_arg0[i * 2]) ||
8817				      ((fin->fin_daddr &
8818					e->ipfe_arg0[i * 2 + 1]) ==
8819				       e->ipfe_arg0[i * 2]);
8820			}
8821			break;
8822
8823#ifdef USE_INET6
8824		case IPF_EXP_IP6_SRCADDR :
8825			if (fin->fin_v != 6)
8826				break;
8827			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8828				rv |= IP6_MASKEQ(&fin->fin_src6,
8829						 &e->ipfe_arg0[i * 8 + 4],
8830						 &e->ipfe_arg0[i * 8]);
8831			}
8832			break;
8833
8834		case IPF_EXP_IP6_DSTADDR :
8835			if (fin->fin_v != 6)
8836				break;
8837			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8838				rv |= IP6_MASKEQ(&fin->fin_dst6,
8839						 &e->ipfe_arg0[i * 8 + 4],
8840						 &e->ipfe_arg0[i * 8]);
8841			}
8842			break;
8843
8844		case IPF_EXP_IP6_ADDR :
8845			if (fin->fin_v != 6)
8846				break;
8847			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8848				rv |= IP6_MASKEQ(&fin->fin_src6,
8849						 &e->ipfe_arg0[i * 8 + 4],
8850						 &e->ipfe_arg0[i * 8]) ||
8851				      IP6_MASKEQ(&fin->fin_dst6,
8852						 &e->ipfe_arg0[i * 8 + 4],
8853						 &e->ipfe_arg0[i * 8]);
8854			}
8855			break;
8856#endif
8857
8858		case IPF_EXP_UDP_PORT :
8859		case IPF_EXP_TCP_PORT :
8860			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8861				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8862				      (fin->fin_dport == e->ipfe_arg0[i]);
8863			}
8864			break;
8865
8866		case IPF_EXP_UDP_SPORT :
8867		case IPF_EXP_TCP_SPORT :
8868			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8869				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8870			}
8871			break;
8872
8873		case IPF_EXP_UDP_DPORT :
8874		case IPF_EXP_TCP_DPORT :
8875			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8876				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8877			}
8878			break;
8879
8880		case IPF_EXP_TCP_FLAGS :
8881			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8882				rv |= ((fin->fin_tcpf &
8883					e->ipfe_arg0[i * 2 + 1]) ==
8884				       e->ipfe_arg0[i * 2]);
8885			}
8886			break;
8887		}
8888		rv ^= e->ipfe_not;
8889
8890		if (rv == 0)
8891			break;
8892	}
8893
8894	return rv;
8895}
8896
8897
8898/* ------------------------------------------------------------------------ */
8899/* Function:    ipf_queueflush                                              */
8900/* Returns:     int - number of entries flushed (0 = none)                  */
8901/* Parameters:  softc(I)    - pointer to soft context main structure        */
8902/*              deletefn(I) - function to call to delete entry              */
8903/*              ipfqs(I)    - top of the list of ipf internal queues        */
8904/*              userqs(I)   - top of the list of user defined timeouts      */
8905/*                                                                          */
8906/* This fucntion gets called when the state/NAT hash tables fill up and we  */
8907/* need to try a bit harder to free up some space.  The algorithm used here */
8908/* split into two parts but both halves have the same goal: to reduce the   */
8909/* number of connections considered to be "active" to the low watermark.    */
8910/* There are two steps in doing this:                                       */
8911/* 1) Remove any TCP connections that are already considered to be "closed" */
8912/*    but have not yet been removed from the state table.  The two states   */
8913/*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8914/*    candidates for this style of removal.  If freeing up entries in       */
8915/*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8916/*    we do not go on to step 2.                                            */
8917/*                                                                          */
8918/* 2) Look for the oldest entries on each timeout queue and free them if    */
8919/*    they are within the given window we are considering.  Where the       */
8920/*    window starts and the steps taken to increase its size depend upon    */
8921/*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8922/*    last 30 seconds is not touched.                                       */
8923/*                                              touched                     */
8924/*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8925/*           |          |        |           |     |     |                  */
8926/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8927/*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8928/*                                                                          */
8929/* Points to note:                                                          */
8930/* - tqe_die is the time, in the future, when entries die.                  */
8931/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8932/*   ticks.                                                                 */
8933/* - tqe_touched is when the entry was last used by NAT/state               */
8934/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8935/*   ipf_ticks any given timeout queue and vice versa.                      */
8936/* - both tqe_die and tqe_touched increase over time                        */
8937/* - timeout queues are sorted with the highest value of tqe_die at the     */
8938/*   bottom and therefore the smallest values of each are at the top        */
8939/* - the pointer passed in as ipfqs should point to an array of timeout     */
8940/*   queues representing each of the TCP states                             */
8941/*                                                                          */
8942/* We start by setting up a maximum range to scan for things to move of     */
8943/* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8944/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8945/* we start again with a new value for "iend" and "istart".  This is        */
8946/* continued until we either finish the scan of 30 second intervals or the  */
8947/* low water mark is reached.                                               */
8948/* ------------------------------------------------------------------------ */
8949int
8950ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8951	ipf_main_softc_t *softc;
8952	ipftq_delete_fn_t deletefn;
8953	ipftq_t *ipfqs, *userqs;
8954	u_int *activep;
8955	int size, low;
8956{
8957	u_long interval, istart, iend;
8958	ipftq_t *ifq, *ifqnext;
8959	ipftqent_t *tqe, *tqn;
8960	int removed = 0;
8961
8962	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8963		tqn = tqe->tqe_next;
8964		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8965			removed++;
8966	}
8967	if ((*activep * 100 / size) > low) {
8968		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8969		     ((tqe = tqn) != NULL); ) {
8970			tqn = tqe->tqe_next;
8971			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8972				removed++;
8973		}
8974	}
8975
8976	if ((*activep * 100 / size) <= low) {
8977		return removed;
8978	}
8979
8980	/*
8981	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8982	 *       used then the operations are upgraded to floating point
8983	 *       and kernels don't like floating point...
8984	 */
8985	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8986		istart = IPF_TTLVAL(86400 * 4);
8987		interval = IPF_TTLVAL(43200);
8988	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8989		istart = IPF_TTLVAL(43200);
8990		interval = IPF_TTLVAL(1800);
8991	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8992		istart = IPF_TTLVAL(1800);
8993		interval = IPF_TTLVAL(30);
8994	} else {
8995		return 0;
8996	}
8997	if (istart > softc->ipf_ticks) {
8998		if (softc->ipf_ticks - interval < interval)
8999			istart = interval;
9000		else
9001			istart = (softc->ipf_ticks / interval) * interval;
9002	}
9003
9004	iend = softc->ipf_ticks - interval;
9005
9006	while ((*activep * 100 / size) > low) {
9007		u_long try;
9008
9009		try = softc->ipf_ticks - istart;
9010
9011		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9012			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9013				if (try < tqe->tqe_touched)
9014					break;
9015				tqn = tqe->tqe_next;
9016				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9017					removed++;
9018			}
9019		}
9020
9021		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9022			ifqnext = ifq->ifq_next;
9023
9024			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9025				if (try < tqe->tqe_touched)
9026					break;
9027				tqn = tqe->tqe_next;
9028				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9029					removed++;
9030			}
9031		}
9032
9033		if (try >= iend) {
9034			if (interval == IPF_TTLVAL(43200)) {
9035				interval = IPF_TTLVAL(1800);
9036			} else if (interval == IPF_TTLVAL(1800)) {
9037				interval = IPF_TTLVAL(30);
9038			} else {
9039				break;
9040			}
9041			if (interval >= softc->ipf_ticks)
9042				break;
9043
9044			iend = softc->ipf_ticks - interval;
9045		}
9046		istart -= interval;
9047	}
9048
9049	return removed;
9050}
9051
9052
9053/* ------------------------------------------------------------------------ */
9054/* Function:    ipf_deliverlocal                                            */
9055/* Returns:     int - 1 = local address, 0 = non-local address              */
9056/* Parameters:  softc(I)     - pointer to soft context main structure       */
9057/*              ipversion(I) - IP protocol version (4 or 6)                 */
9058/*              ifp(I)       - network interface pointer                    */
9059/*              ipaddr(I)    - IPv4/6 destination address                   */
9060/*                                                                          */
9061/* This fucntion is used to determine in the address "ipaddr" belongs to    */
9062/* the network interface represented by ifp.                                */
9063/* ------------------------------------------------------------------------ */
9064int
9065ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9066	ipf_main_softc_t *softc;
9067	int ipversion;
9068	void *ifp;
9069	i6addr_t *ipaddr;
9070{
9071	i6addr_t addr;
9072	int islocal = 0;
9073
9074	if (ipversion == 4) {
9075		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9076			if (addr.in4.s_addr == ipaddr->in4.s_addr)
9077				islocal = 1;
9078		}
9079
9080#ifdef USE_INET6
9081	} else if (ipversion == 6) {
9082		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9083			if (IP6_EQ(&addr, ipaddr))
9084				islocal = 1;
9085		}
9086#endif
9087	}
9088
9089	return islocal;
9090}
9091
9092
9093/* ------------------------------------------------------------------------ */
9094/* Function:    ipf_settimeout                                              */
9095/* Returns:     int - 0 = success, -1 = failure                             */
9096/* Parameters:  softc(I) - pointer to soft context main structure           */
9097/*              t(I)     - pointer to tuneable array entry                  */
9098/*              p(I)     - pointer to values passed in to apply             */
9099/*                                                                          */
9100/* This function is called to set the timeout values for each distinct      */
9101/* queue timeout that is available.  When called, it calls into both the    */
9102/* state and NAT code, telling them to update their timeout queues.         */
9103/* ------------------------------------------------------------------------ */
9104static int
9105ipf_settimeout(softc, t, p)
9106	struct ipf_main_softc_s *softc;
9107	ipftuneable_t *t;
9108	ipftuneval_t *p;
9109{
9110
9111	/*
9112	 * ipf_interror should be set by the functions called here, not
9113	 * by this function - it's just a middle man.
9114	 */
9115	if (ipf_state_settimeout(softc, t, p) == -1)
9116		return -1;
9117	if (ipf_nat_settimeout(softc, t, p) == -1)
9118		return -1;
9119	return 0;
9120}
9121
9122
9123/* ------------------------------------------------------------------------ */
9124/* Function:    ipf_apply_timeout                                           */
9125/* Returns:     int - 0 = success, -1 = failure                             */
9126/* Parameters:  head(I)    - pointer to tuneable array entry                */
9127/*              seconds(I) - pointer to values passed in to apply           */
9128/*                                                                          */
9129/* This function applies a timeout of "seconds" to the timeout queue that   */
9130/* is pointed to by "head".  All entries on this list have an expiration    */
9131/* set to be the current tick value of ipf plus the ttl.  Given that this   */
9132/* function should only be called when the delta is non-zero, the task is   */
9133/* to walk the entire list and apply the change.  The sort order will not   */
9134/* change.  The only catch is that this is O(n) across the list, so if the  */
9135/* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9136/* could take a relatively long time to work through them all.              */
9137/* ------------------------------------------------------------------------ */
9138void
9139ipf_apply_timeout(head, seconds)
9140	ipftq_t *head;
9141	u_int seconds;
9142{
9143	u_int oldtimeout, newtimeout;
9144	ipftqent_t *tqe;
9145	int delta;
9146
9147	MUTEX_ENTER(&head->ifq_lock);
9148	oldtimeout = head->ifq_ttl;
9149	newtimeout = IPF_TTLVAL(seconds);
9150	delta = oldtimeout - newtimeout;
9151
9152	head->ifq_ttl = newtimeout;
9153
9154	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9155		tqe->tqe_die += delta;
9156	}
9157	MUTEX_EXIT(&head->ifq_lock);
9158}
9159
9160
9161/* ------------------------------------------------------------------------ */
9162/* Function:   ipf_settimeout_tcp                                           */
9163/* Returns:    int - 0 = successfully applied, -1 = failed                  */
9164/* Parameters: t(I)   - pointer to tuneable to change                       */
9165/*             p(I)   - pointer to new timeout information                  */
9166/*             tab(I) - pointer to table of TCP queues                      */
9167/*                                                                          */
9168/* This function applies the new timeout (p) to the TCP tunable (t) and     */
9169/* updates all of the entries on the relevant timeout queue by calling      */
9170/* ipf_apply_timeout().                                                     */
9171/* ------------------------------------------------------------------------ */
9172int
9173ipf_settimeout_tcp(t, p, tab)
9174	ipftuneable_t *t;
9175	ipftuneval_t *p;
9176	ipftq_t *tab;
9177{
9178	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9179	    !strcmp(t->ipft_name, "tcp_established")) {
9180		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9181	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9182		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9183	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9184		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9185	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9186		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9187		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9188		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9189	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
9190		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9191	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9192		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9193	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
9194		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9195	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9196		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9197	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9198		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9199	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
9200		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9201	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9202		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9203	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9204		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9205	} else {
9206		/*
9207		 * ipf_interror isn't set here because it should be set
9208		 * by whatever called this function.
9209		 */
9210		return -1;
9211	}
9212	return 0;
9213}
9214
9215
9216/* ------------------------------------------------------------------------ */
9217/* Function:   ipf_main_soft_create                                         */
9218/* Returns:    NULL = failure, else success                                 */
9219/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9220/*                                                                          */
9221/* Create the foundation soft context structure. In circumstances where it  */
9222/* is not required to dynamically allocate the context, a pointer can be    */
9223/* passed in (rather than NULL) to a structure to be initialised.           */
9224/* The main thing of interest is that a number of locks are initialised     */
9225/* here instead of in the where might be expected - in the relevant create  */
9226/* function elsewhere.  This is done because the current locking design has */
9227/* some areas where these locks are used outside of their module.           */
9228/* Possibly the most important exercise that is done here is setting of all */
9229/* the timeout values, allowing them to be changed before init().           */
9230/* ------------------------------------------------------------------------ */
9231void *
9232ipf_main_soft_create(arg)
9233	void *arg;
9234{
9235	ipf_main_softc_t *softc;
9236
9237	if (arg == NULL) {
9238		KMALLOC(softc, ipf_main_softc_t *);
9239		if (softc == NULL)
9240			return NULL;
9241	} else {
9242		softc = arg;
9243	}
9244
9245	bzero((char *)softc, sizeof(*softc));
9246
9247	/*
9248	 * This serves as a flag as to whether or not the softc should be
9249	 * free'd when _destroy is called.
9250	 */
9251	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9252
9253	softc->ipf_tuners = ipf_tune_array_copy(softc,
9254						sizeof(ipf_main_tuneables),
9255						ipf_main_tuneables);
9256	if (softc->ipf_tuners == NULL) {
9257		ipf_main_soft_destroy(softc);
9258		return NULL;
9259	}
9260
9261	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9262	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9263	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9264	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9265	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9266	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9267	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9268	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9269	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9270
9271	softc->ipf_token_head = NULL;
9272	softc->ipf_token_tail = &softc->ipf_token_head;
9273
9274	softc->ipf_tcpidletimeout = FIVE_DAYS;
9275	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9276	softc->ipf_tcplastack = IPF_TTLVAL(30);
9277	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9278	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9279	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9280	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9281	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9282	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9283	softc->ipf_udptimeout = IPF_TTLVAL(120);
9284	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9285	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9286	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9287	softc->ipf_iptimeout = IPF_TTLVAL(60);
9288
9289#if defined(IPFILTER_DEFAULT_BLOCK)
9290	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9291#else
9292	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9293#endif
9294	softc->ipf_minttl = 4;
9295	softc->ipf_icmpminfragmtu = 68;
9296	softc->ipf_flags = IPF_LOGGING;
9297
9298	return softc;
9299}
9300
9301/* ------------------------------------------------------------------------ */
9302/* Function:   ipf_main_soft_init                                           */
9303/* Returns:    0 = success, -1 = failure                                    */
9304/* Parameters: softc(I) - pointer to soft context main structure            */
9305/*                                                                          */
9306/* A null-op function that exists as a placeholder so that the flow in      */
9307/* other functions is obvious.                                              */
9308/* ------------------------------------------------------------------------ */
9309/*ARGSUSED*/
9310int
9311ipf_main_soft_init(softc)
9312	ipf_main_softc_t *softc;
9313{
9314	return 0;
9315}
9316
9317
9318/* ------------------------------------------------------------------------ */
9319/* Function:   ipf_main_soft_destroy                                        */
9320/* Returns:    void                                                         */
9321/* Parameters: softc(I) - pointer to soft context main structure            */
9322/*                                                                          */
9323/* Undo everything that we did in ipf_main_soft_create.                     */
9324/*                                                                          */
9325/* The most important check that needs to be made here is whether or not    */
9326/* the structure was allocated by ipf_main_soft_create() by checking what   */
9327/* value is stored in ipf_dynamic_main.                                     */
9328/* ------------------------------------------------------------------------ */
9329/*ARGSUSED*/
9330void
9331ipf_main_soft_destroy(softc)
9332	ipf_main_softc_t *softc;
9333{
9334
9335	RW_DESTROY(&softc->ipf_frag);
9336	RW_DESTROY(&softc->ipf_poolrw);
9337	RW_DESTROY(&softc->ipf_nat);
9338	RW_DESTROY(&softc->ipf_state);
9339	RW_DESTROY(&softc->ipf_tokens);
9340	RW_DESTROY(&softc->ipf_mutex);
9341	RW_DESTROY(&softc->ipf_global);
9342	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9343	MUTEX_DESTROY(&softc->ipf_rw);
9344
9345	if (softc->ipf_tuners != NULL) {
9346		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9347	}
9348	if (softc->ipf_dynamic_softc == 1) {
9349		KFREE(softc);
9350	}
9351}
9352
9353
9354/* ------------------------------------------------------------------------ */
9355/* Function:   ipf_main_soft_fini                                           */
9356/* Returns:    0 = success, -1 = failure                                    */
9357/* Parameters: softc(I) - pointer to soft context main structure            */
9358/*                                                                          */
9359/* Clean out the rules which have been added since _init was last called,   */
9360/* the only dynamic part of the mainline.                                   */
9361/* ------------------------------------------------------------------------ */
9362int
9363ipf_main_soft_fini(softc)
9364	ipf_main_softc_t *softc;
9365{
9366	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9367	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9368	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9369	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9370
9371	return 0;
9372}
9373
9374
9375/* ------------------------------------------------------------------------ */
9376/* Function:   ipf_main_load                                                */
9377/* Returns:    0 = success, -1 = failure                                    */
9378/* Parameters: none                                                         */
9379/*                                                                          */
9380/* Handle global initialisation that needs to be done for the base part of  */
9381/* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9382/* arrays that get used by the state/NAT code.                              */
9383/* ------------------------------------------------------------------------ */
9384int
9385ipf_main_load()
9386{
9387	int i;
9388
9389	/* fill icmp reply type table */
9390	for (i = 0; i <= ICMP_MAXTYPE; i++)
9391		icmpreplytype4[i] = -1;
9392	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9393	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9394	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9395	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9396
9397#ifdef  USE_INET6
9398	/* fill icmp reply type table */
9399	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9400		icmpreplytype6[i] = -1;
9401	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9402	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9403	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9404	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9405	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9406#endif
9407
9408	return 0;
9409}
9410
9411
9412/* ------------------------------------------------------------------------ */
9413/* Function:   ipf_main_unload                                              */
9414/* Returns:    0 = success, -1 = failure                                    */
9415/* Parameters: none                                                         */
9416/*                                                                          */
9417/* A null-op function that exists as a placeholder so that the flow in      */
9418/* other functions is obvious.                                              */
9419/* ------------------------------------------------------------------------ */
9420int
9421ipf_main_unload()
9422{
9423	return 0;
9424}
9425
9426
9427/* ------------------------------------------------------------------------ */
9428/* Function:   ipf_load_all                                                 */
9429/* Returns:    0 = success, -1 = failure                                    */
9430/* Parameters: none                                                         */
9431/*                                                                          */
9432/* Work through all of the subsystems inside IPFilter and call the load     */
9433/* function for each in an order that won't lead to a crash :)              */
9434/* ------------------------------------------------------------------------ */
9435int
9436ipf_load_all()
9437{
9438	if (ipf_main_load() == -1)
9439		return -1;
9440
9441	if (ipf_state_main_load() == -1)
9442		return -1;
9443
9444	if (ipf_nat_main_load() == -1)
9445		return -1;
9446
9447	if (ipf_frag_main_load() == -1)
9448		return -1;
9449
9450	if (ipf_auth_main_load() == -1)
9451		return -1;
9452
9453	if (ipf_proxy_main_load() == -1)
9454		return -1;
9455
9456	return 0;
9457}
9458
9459
9460/* ------------------------------------------------------------------------ */
9461/* Function:   ipf_unload_all                                               */
9462/* Returns:    0 = success, -1 = failure                                    */
9463/* Parameters: none                                                         */
9464/*                                                                          */
9465/* Work through all of the subsystems inside IPFilter and call the unload   */
9466/* function for each in an order that won't lead to a crash :)              */
9467/* ------------------------------------------------------------------------ */
9468int
9469ipf_unload_all()
9470{
9471	if (ipf_proxy_main_unload() == -1)
9472		return -1;
9473
9474	if (ipf_auth_main_unload() == -1)
9475		return -1;
9476
9477	if (ipf_frag_main_unload() == -1)
9478		return -1;
9479
9480	if (ipf_nat_main_unload() == -1)
9481		return -1;
9482
9483	if (ipf_state_main_unload() == -1)
9484		return -1;
9485
9486	if (ipf_main_unload() == -1)
9487		return -1;
9488
9489	return 0;
9490}
9491
9492
9493/* ------------------------------------------------------------------------ */
9494/* Function:   ipf_create_all                                               */
9495/* Returns:    NULL = failure, else success                                 */
9496/* Parameters: arg(I) - pointer to soft context main structure              */
9497/*                                                                          */
9498/* Work through all of the subsystems inside IPFilter and call the create   */
9499/* function for each in an order that won't lead to a crash :)              */
9500/* ------------------------------------------------------------------------ */
9501ipf_main_softc_t *
9502ipf_create_all(arg)
9503	void *arg;
9504{
9505	ipf_main_softc_t *softc;
9506
9507	softc = ipf_main_soft_create(arg);
9508	if (softc == NULL)
9509		return NULL;
9510
9511#ifdef IPFILTER_LOG
9512	softc->ipf_log_soft = ipf_log_soft_create(softc);
9513	if (softc->ipf_log_soft == NULL) {
9514		ipf_destroy_all(softc);
9515		return NULL;
9516	}
9517#endif
9518
9519	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9520	if (softc->ipf_lookup_soft == NULL) {
9521		ipf_destroy_all(softc);
9522		return NULL;
9523	}
9524
9525	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9526	if (softc->ipf_sync_soft == NULL) {
9527		ipf_destroy_all(softc);
9528		return NULL;
9529	}
9530
9531	softc->ipf_state_soft = ipf_state_soft_create(softc);
9532	if (softc->ipf_state_soft == NULL) {
9533		ipf_destroy_all(softc);
9534		return NULL;
9535	}
9536
9537	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9538	if (softc->ipf_nat_soft == NULL) {
9539		ipf_destroy_all(softc);
9540		return NULL;
9541	}
9542
9543	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9544	if (softc->ipf_frag_soft == NULL) {
9545		ipf_destroy_all(softc);
9546		return NULL;
9547	}
9548
9549	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9550	if (softc->ipf_auth_soft == NULL) {
9551		ipf_destroy_all(softc);
9552		return NULL;
9553	}
9554
9555	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9556	if (softc->ipf_proxy_soft == NULL) {
9557		ipf_destroy_all(softc);
9558		return NULL;
9559	}
9560
9561	return softc;
9562}
9563
9564
9565/* ------------------------------------------------------------------------ */
9566/* Function:   ipf_destroy_all                                              */
9567/* Returns:    void                                                         */
9568/* Parameters: softc(I) - pointer to soft context main structure            */
9569/*                                                                          */
9570/* Work through all of the subsystems inside IPFilter and call the destroy  */
9571/* function for each in an order that won't lead to a crash :)              */
9572/*                                                                          */
9573/* Every one of these functions is expected to succeed, so there is no      */
9574/* checking of return values.                                               */
9575/* ------------------------------------------------------------------------ */
9576void
9577ipf_destroy_all(softc)
9578	ipf_main_softc_t *softc;
9579{
9580
9581	if (softc->ipf_state_soft != NULL) {
9582		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9583		softc->ipf_state_soft = NULL;
9584	}
9585
9586	if (softc->ipf_nat_soft != NULL) {
9587		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9588		softc->ipf_nat_soft = NULL;
9589	}
9590
9591	if (softc->ipf_frag_soft != NULL) {
9592		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9593		softc->ipf_frag_soft = NULL;
9594	}
9595
9596	if (softc->ipf_auth_soft != NULL) {
9597		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9598		softc->ipf_auth_soft = NULL;
9599	}
9600
9601	if (softc->ipf_proxy_soft != NULL) {
9602		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9603		softc->ipf_proxy_soft = NULL;
9604	}
9605
9606	if (softc->ipf_sync_soft != NULL) {
9607		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9608		softc->ipf_sync_soft = NULL;
9609	}
9610
9611	if (softc->ipf_lookup_soft != NULL) {
9612		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9613		softc->ipf_lookup_soft = NULL;
9614	}
9615
9616#ifdef IPFILTER_LOG
9617	if (softc->ipf_log_soft != NULL) {
9618		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9619		softc->ipf_log_soft = NULL;
9620	}
9621#endif
9622
9623	ipf_main_soft_destroy(softc);
9624}
9625
9626
9627/* ------------------------------------------------------------------------ */
9628/* Function:   ipf_init_all                                                 */
9629/* Returns:    0 = success, -1 = failure                                    */
9630/* Parameters: softc(I) - pointer to soft context main structure            */
9631/*                                                                          */
9632/* Work through all of the subsystems inside IPFilter and call the init     */
9633/* function for each in an order that won't lead to a crash :)              */
9634/* ------------------------------------------------------------------------ */
9635int
9636ipf_init_all(softc)
9637	ipf_main_softc_t *softc;
9638{
9639
9640	if (ipf_main_soft_init(softc) == -1)
9641		return -1;
9642
9643#ifdef IPFILTER_LOG
9644	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9645		return -1;
9646#endif
9647
9648	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9649		return -1;
9650
9651	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9652		return -1;
9653
9654	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9655		return -1;
9656
9657	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9658		return -1;
9659
9660	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9661		return -1;
9662
9663	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9664		return -1;
9665
9666	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9667		return -1;
9668
9669	return 0;
9670}
9671
9672
9673/* ------------------------------------------------------------------------ */
9674/* Function:   ipf_fini_all                                                 */
9675/* Returns:    0 = success, -1 = failure                                    */
9676/* Parameters: softc(I) - pointer to soft context main structure            */
9677/*                                                                          */
9678/* Work through all of the subsystems inside IPFilter and call the fini     */
9679/* function for each in an order that won't lead to a crash :)              */
9680/* ------------------------------------------------------------------------ */
9681int
9682ipf_fini_all(softc)
9683	ipf_main_softc_t *softc;
9684{
9685
9686	ipf_token_flush(softc);
9687
9688	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9689		return -1;
9690
9691	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9692		return -1;
9693
9694	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9695		return -1;
9696
9697	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9698		return -1;
9699
9700	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9701		return -1;
9702
9703	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9704		return -1;
9705
9706	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9707		return -1;
9708
9709#ifdef IPFILTER_LOG
9710	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9711		return -1;
9712#endif
9713
9714	if (ipf_main_soft_fini(softc) == -1)
9715		return -1;
9716
9717	return 0;
9718}
9719
9720
9721/* ------------------------------------------------------------------------ */
9722/* Function:    ipf_rule_expire                                             */
9723/* Returns:     Nil                                                         */
9724/* Parameters:  softc(I) - pointer to soft context main structure           */
9725/*                                                                          */
9726/* At present this function exists just to support temporary addition of    */
9727/* firewall rules. Both inactive and active lists are scanned for items to  */
9728/* purge, as by rights, the expiration is computed as soon as the rule is   */
9729/* loaded in.                                                               */
9730/* ------------------------------------------------------------------------ */
9731void
9732ipf_rule_expire(softc)
9733	ipf_main_softc_t *softc;
9734{
9735	frentry_t *fr;
9736
9737	if ((softc->ipf_rule_explist[0] == NULL) &&
9738	    (softc->ipf_rule_explist[1] == NULL))
9739		return;
9740
9741	WRITE_ENTER(&softc->ipf_mutex);
9742
9743	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9744		/*
9745		 * Because the list is kept sorted on insertion, the fist
9746		 * one that dies in the future means no more work to do.
9747		 */
9748		if (fr->fr_die > softc->ipf_ticks)
9749			break;
9750		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9751	}
9752
9753	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9754		/*
9755		 * Because the list is kept sorted on insertion, the fist
9756		 * one that dies in the future means no more work to do.
9757		 */
9758		if (fr->fr_die > softc->ipf_ticks)
9759			break;
9760		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9761	}
9762
9763	RWLOCK_EXIT(&softc->ipf_mutex);
9764}
9765
9766
9767static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9768static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9769				      i6addr_t *));
9770
9771host_node_t RBI_ZERO(ipf_rb);
9772RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9773
9774
9775/* ------------------------------------------------------------------------ */
9776/* Function:    ipf_ht_node_cmp                                             */
9777/* Returns:     int   - 0 == nodes are the same, ..                         */
9778/* Parameters:  k1(I) - pointer to first key to compare                     */
9779/*              k2(I) - pointer to second key to compare                    */
9780/*                                                                          */
9781/* The "key" for the node is a combination of two fields: the address       */
9782/* family and the address itself.                                           */
9783/*                                                                          */
9784/* Because we're not actually interpreting the address data, it isn't       */
9785/* necessary to convert them to/from network/host byte order. The mask is   */
9786/* just used to remove bits that aren't significant - it doesn't matter     */
9787/* where they are, as long as they're always in the same place.             */
9788/*                                                                          */
9789/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9790/* this is where individual ones will differ the most - but not true for    */
9791/* for /48's, etc.                                                          */
9792/* ------------------------------------------------------------------------ */
9793static int
9794ipf_ht_node_cmp(k1, k2)
9795	struct host_node_s *k1, *k2;
9796{
9797	int i;
9798
9799	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9800	if (i != 0)
9801		return i;
9802
9803	if (k1->hn_addr.adf_family == AF_INET)
9804		return (k2->hn_addr.adf_addr.in4.s_addr -
9805			k1->hn_addr.adf_addr.in4.s_addr);
9806
9807	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9808	if (i != 0)
9809		return i;
9810	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9811	if (i != 0)
9812		return i;
9813	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9814	if (i != 0)
9815		return i;
9816	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9817	return i;
9818}
9819
9820
9821/* ------------------------------------------------------------------------ */
9822/* Function:    ipf_ht_node_make_key                                        */
9823/* Returns:     Nil                                                         */
9824/* parameters:  htp(I)    - pointer to address tracking structure           */
9825/*              key(I)    - where to store masked address for lookup        */
9826/*              family(I) - protocol family of address                      */
9827/*              addr(I)   - pointer to network address                      */
9828/*                                                                          */
9829/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9830/* copy the address passed in into the key structure whilst masking out the */
9831/* bits that we don't want.                                                 */
9832/*                                                                          */
9833/* Because the parser will set ht_netmask to 128 if there is no protocol    */
9834/* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9835/* have to be wary of that and not allow 32-128 to happen.                  */
9836/* ------------------------------------------------------------------------ */
9837static void
9838ipf_ht_node_make_key(htp, key, family, addr)
9839	host_track_t *htp;
9840	host_node_t *key;
9841	int family;
9842	i6addr_t *addr;
9843{
9844	key->hn_addr.adf_family = family;
9845	if (family == AF_INET) {
9846		u_32_t mask;
9847		int bits;
9848
9849		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9850		bits = htp->ht_netmask;
9851		if (bits >= 32) {
9852			mask = 0xffffffff;
9853		} else {
9854			mask = htonl(0xffffffff << (32 - bits));
9855		}
9856		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9857#ifdef USE_INET6
9858	} else {
9859		int bits = htp->ht_netmask;
9860
9861		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9862		if (bits > 96) {
9863			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9864					     htonl(0xffffffff << (128 - bits));
9865			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9866			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9867			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9868		} else if (bits > 64) {
9869			key->hn_addr.adf_addr.i6[3] = 0;
9870			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9871					     htonl(0xffffffff << (96 - bits));
9872			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9873			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9874		} else if (bits > 32) {
9875			key->hn_addr.adf_addr.i6[3] = 0;
9876			key->hn_addr.adf_addr.i6[2] = 0;
9877			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9878					     htonl(0xffffffff << (64 - bits));
9879			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9880		} else {
9881			key->hn_addr.adf_addr.i6[3] = 0;
9882			key->hn_addr.adf_addr.i6[2] = 0;
9883			key->hn_addr.adf_addr.i6[1] = 0;
9884			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9885					     htonl(0xffffffff << (32 - bits));
9886		}
9887#endif
9888	}
9889}
9890
9891
9892/* ------------------------------------------------------------------------ */
9893/* Function:    ipf_ht_node_add                                             */
9894/* Returns:     int       - 0 == success,  -1 == failure                    */
9895/* Parameters:  softc(I)  - pointer to soft context main structure          */
9896/*              htp(I)    - pointer to address tracking structure           */
9897/*              family(I) - protocol family of address                      */
9898/*              addr(I)   - pointer to network address                      */
9899/*                                                                          */
9900/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9901/*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9902/*                                                                          */
9903/* After preparing the key with the address information to find, look in    */
9904/* the red-black tree to see if the address is known. A successful call to  */
9905/* this function can mean one of two things: a new node was added to the    */
9906/* tree or a matching node exists and we're able to bump up its activity.   */
9907/* ------------------------------------------------------------------------ */
9908int
9909ipf_ht_node_add(softc, htp, family, addr)
9910	ipf_main_softc_t *softc;
9911	host_track_t *htp;
9912	int family;
9913	i6addr_t *addr;
9914{
9915	host_node_t *h;
9916	host_node_t k;
9917
9918	ipf_ht_node_make_key(htp, &k, family, addr);
9919
9920	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9921	if (h == NULL) {
9922		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9923			return -1;
9924		KMALLOC(h, host_node_t *);
9925		if (h == NULL) {
9926			DT(ipf_rb_no_mem);
9927			LBUMP(ipf_rb_no_mem);
9928			return -1;
9929		}
9930
9931		/*
9932		 * If there was a macro to initialise the RB node then that
9933		 * would get used here, but there isn't...
9934		 */
9935		bzero((char *)h, sizeof(*h));
9936		h->hn_addr = k.hn_addr;
9937		h->hn_addr.adf_family = k.hn_addr.adf_family;
9938		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9939		htp->ht_cur_nodes++;
9940	} else {
9941		if ((htp->ht_max_per_node != 0) &&
9942		    (h->hn_active >= htp->ht_max_per_node)) {
9943			DT(ipf_rb_node_max);
9944			LBUMP(ipf_rb_node_max);
9945			return -1;
9946		}
9947	}
9948
9949	h->hn_active++;
9950
9951	return 0;
9952}
9953
9954
9955/* ------------------------------------------------------------------------ */
9956/* Function:    ipf_ht_node_del                                             */
9957/* Returns:     int       - 0 == success,  -1 == failure                    */
9958/* parameters:  htp(I)    - pointer to address tracking structure           */
9959/*              family(I) - protocol family of address                      */
9960/*              addr(I)   - pointer to network address                      */
9961/*                                                                          */
9962/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9963/*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9964/*                                                                          */
9965/* Try and find the address passed in amongst the leavese on this tree to   */
9966/* be friend. If found then drop the active account for that node drops by  */
9967/* one. If that count reaches 0, it is time to free it all up.              */
9968/* ------------------------------------------------------------------------ */
9969int
9970ipf_ht_node_del(htp, family, addr)
9971	host_track_t *htp;
9972	int family;
9973	i6addr_t *addr;
9974{
9975	host_node_t *h;
9976	host_node_t k;
9977
9978	ipf_ht_node_make_key(htp, &k, family, addr);
9979
9980	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9981	if (h == NULL) {
9982		return -1;
9983	} else {
9984		h->hn_active--;
9985		if (h->hn_active == 0) {
9986			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9987			htp->ht_cur_nodes--;
9988			KFREE(h);
9989		}
9990	}
9991
9992	return 0;
9993}
9994
9995
9996/* ------------------------------------------------------------------------ */
9997/* Function:    ipf_rb_ht_init                                              */
9998/* Returns:     Nil                                                         */
9999/* Parameters:  head(I) - pointer to host tracking structure                */
10000/*                                                                          */
10001/* Initialise the host tracking structure to be ready for use above.        */
10002/* ------------------------------------------------------------------------ */
10003void
10004ipf_rb_ht_init(head)
10005	host_track_t *head;
10006{
10007	RBI_INIT(ipf_rb, &head->ht_root);
10008}
10009
10010
10011/* ------------------------------------------------------------------------ */
10012/* Function:    ipf_rb_ht_freenode                                          */
10013/* Returns:     Nil                                                         */
10014/* Parameters:  head(I) - pointer to host tracking structure                */
10015/*              arg(I)  - additional argument from walk caller              */
10016/*                                                                          */
10017/* Free an actual host_node_t structure.                                    */
10018/* ------------------------------------------------------------------------ */
10019void
10020ipf_rb_ht_freenode(node, arg)
10021	host_node_t *node;
10022	void *arg;
10023{
10024	KFREE(node);
10025}
10026
10027
10028/* ------------------------------------------------------------------------ */
10029/* Function:    ipf_rb_ht_flush                                             */
10030/* Returns:     Nil                                                         */
10031/* Parameters:  head(I) - pointer to host tracking structure                */
10032/*                                                                          */
10033/* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10034/* and free'ing each one.                                                   */
10035/* ------------------------------------------------------------------------ */
10036void
10037ipf_rb_ht_flush(head)
10038	host_track_t *head;
10039{
10040	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10041}
10042
10043
10044/* ------------------------------------------------------------------------ */
10045/* Function:    ipf_slowtimer                                               */
10046/* Returns:     Nil                                                         */
10047/* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10048/*                                                                          */
10049/* Slowly expire held state for fragments.  Timeouts are set * in           */
10050/* expectation of this being called twice per second.                       */
10051/* ------------------------------------------------------------------------ */
10052void
10053ipf_slowtimer(softc)
10054	ipf_main_softc_t *softc;
10055{
10056
10057	ipf_token_expire(softc);
10058	ipf_frag_expire(softc);
10059	ipf_state_expire(softc);
10060	ipf_nat_expire(softc);
10061	ipf_auth_expire(softc);
10062	ipf_lookup_expire(softc);
10063	ipf_rule_expire(softc);
10064	ipf_sync_expire(softc);
10065	softc->ipf_ticks++;
10066}
10067
10068
10069/* ------------------------------------------------------------------------ */
10070/* Function:    ipf_inet_mask_add                                           */
10071/* Returns:     Nil                                                         */
10072/* Parameters:  bits(I) - pointer to nat context information                */
10073/*              mtab(I) - pointer to mask hash table structure              */
10074/*                                                                          */
10075/* When called, bits represents the mask of a new NAT rule that has just    */
10076/* been added. This function inserts a bitmask into the array of masks to   */
10077/* search when searching for a matching NAT rule for a packet.              */
10078/* Prevention of duplicate masks is achieved by checking the use count for  */
10079/* a given netmask.                                                         */
10080/* ------------------------------------------------------------------------ */
10081void
10082ipf_inet_mask_add(bits, mtab)
10083	int bits;
10084	ipf_v4_masktab_t *mtab;
10085{
10086	u_32_t mask;
10087	int i, j;
10088
10089	mtab->imt4_masks[bits]++;
10090	if (mtab->imt4_masks[bits] > 1)
10091		return;
10092
10093	if (bits == 0)
10094		mask = 0;
10095	else
10096		mask = 0xffffffff << (32 - bits);
10097
10098	for (i = 0; i < 33; i++) {
10099		if (ntohl(mtab->imt4_active[i]) < mask) {
10100			for (j = 32; j > i; j--)
10101				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10102			mtab->imt4_active[i] = htonl(mask);
10103			break;
10104		}
10105	}
10106	mtab->imt4_max++;
10107}
10108
10109
10110/* ------------------------------------------------------------------------ */
10111/* Function:    ipf_inet_mask_del                                           */
10112/* Returns:     Nil                                                         */
10113/* Parameters:  bits(I) - number of bits set in the netmask                 */
10114/*              mtab(I) - pointer to mask hash table structure              */
10115/*                                                                          */
10116/* Remove the 32bit bitmask represented by "bits" from the collection of    */
10117/* netmasks stored inside of mtab.                                          */
10118/* ------------------------------------------------------------------------ */
10119void
10120ipf_inet_mask_del(bits, mtab)
10121	int bits;
10122	ipf_v4_masktab_t *mtab;
10123{
10124	u_32_t mask;
10125	int i, j;
10126
10127	mtab->imt4_masks[bits]--;
10128	if (mtab->imt4_masks[bits] > 0)
10129		return;
10130
10131	mask = htonl(0xffffffff << (32 - bits));
10132	for (i = 0; i < 33; i++) {
10133		if (mtab->imt4_active[i] == mask) {
10134			for (j = i + 1; j < 33; j++)
10135				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10136			break;
10137		}
10138	}
10139	mtab->imt4_max--;
10140	ASSERT(mtab->imt4_max >= 0);
10141}
10142
10143
10144#ifdef USE_INET6
10145/* ------------------------------------------------------------------------ */
10146/* Function:    ipf_inet6_mask_add                                          */
10147/* Returns:     Nil                                                         */
10148/* Parameters:  bits(I) - number of bits set in mask                        */
10149/*              mask(I) - pointer to mask to add                            */
10150/*              mtab(I) - pointer to mask hash table structure              */
10151/*                                                                          */
10152/* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10153/* has just been added. This function inserts a bitmask into the array of   */
10154/* masks to search when searching for a matching NAT rule for a packet.     */
10155/* Prevention of duplicate masks is achieved by checking the use count for  */
10156/* a given netmask.                                                         */
10157/* ------------------------------------------------------------------------ */
10158void
10159ipf_inet6_mask_add(bits, mask, mtab)
10160	int bits;
10161	i6addr_t *mask;
10162	ipf_v6_masktab_t *mtab;
10163{
10164	i6addr_t zero;
10165	int i, j;
10166
10167	mtab->imt6_masks[bits]++;
10168	if (mtab->imt6_masks[bits] > 1)
10169		return;
10170
10171	if (bits == 0) {
10172		mask = &zero;
10173		zero.i6[0] = 0;
10174		zero.i6[1] = 0;
10175		zero.i6[2] = 0;
10176		zero.i6[3] = 0;
10177	}
10178
10179	for (i = 0; i < 129; i++) {
10180		if (IP6_LT(&mtab->imt6_active[i], mask)) {
10181			for (j = 128; j > i; j--)
10182				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10183			mtab->imt6_active[i] = *mask;
10184			break;
10185		}
10186	}
10187	mtab->imt6_max++;
10188}
10189
10190
10191/* ------------------------------------------------------------------------ */
10192/* Function:    ipf_inet6_mask_del                                          */
10193/* Returns:     Nil                                                         */
10194/* Parameters:  bits(I) - number of bits set in mask                        */
10195/*              mask(I) - pointer to mask to remove                         */
10196/*              mtab(I) - pointer to mask hash table structure              */
10197/*                                                                          */
10198/* Remove the 128bit bitmask represented by "bits" from the collection of   */
10199/* netmasks stored inside of mtab.                                          */
10200/* ------------------------------------------------------------------------ */
10201void
10202ipf_inet6_mask_del(bits, mask, mtab)
10203	int bits;
10204	i6addr_t *mask;
10205	ipf_v6_masktab_t *mtab;
10206{
10207	i6addr_t zero;
10208	int i, j;
10209
10210	mtab->imt6_masks[bits]--;
10211	if (mtab->imt6_masks[bits] > 0)
10212		return;
10213
10214	if (bits == 0)
10215		mask = &zero;
10216	zero.i6[0] = 0;
10217	zero.i6[1] = 0;
10218	zero.i6[2] = 0;
10219	zero.i6[3] = 0;
10220
10221	for (i = 0; i < 129; i++) {
10222		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10223			for (j = i + 1; j < 129; j++) {
10224				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10225				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10226					break;
10227			}
10228			break;
10229		}
10230	}
10231	mtab->imt6_max--;
10232	ASSERT(mtab->imt6_max >= 0);
10233}
10234
10235#ifdef	_KERNEL
10236static u_int
10237ipf_pcksum6(fin, ip6, off, len)
10238	fr_info_t *fin;
10239	ip6_t *ip6;
10240	u_int32_t off;
10241	u_int32_t len;
10242{
10243	struct mbuf *m;
10244	int sum;
10245
10246	m = fin->fin_m;
10247	if (m->m_len < sizeof(struct ip6_hdr)) {
10248		return 0xffff;
10249	}
10250
10251	sum = in6_cksum(m, ip6->ip6_nxt, off, len);
10252	return(sum);
10253}
10254#else
10255static u_int
10256ipf_pcksum6(fin, ip6, off, len)
10257	fr_info_t *fin;
10258	ip6_t *ip6;
10259	u_int32_t off;
10260	u_int32_t len;
10261{
10262	u_short *sp;
10263	u_int sum;
10264
10265	sp = (u_short *)&ip6->ip6_src;
10266	sum = *sp++;   /* ip6_src */
10267	sum += *sp++;
10268	sum += *sp++;
10269	sum += *sp++;
10270	sum += *sp++;
10271	sum += *sp++;
10272	sum += *sp++;
10273	sum += *sp++;
10274	sum += *sp++;   /* ip6_dst */
10275	sum += *sp++;
10276	sum += *sp++;
10277	sum += *sp++;
10278	sum += *sp++;
10279	sum += *sp++;
10280	sum += *sp++;
10281	sum += *sp++;
10282	return(ipf_pcksum(fin, off, sum));
10283}
10284#endif
10285#endif
10286