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