fil.c revision 369245
1/*	$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 369245 2021-02-09 13:47:46Z git2svn $	*/
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 369245 2021-02-09 13:47:46Z git2svn $";
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 FASTROUTE_RECURSION
119
120#define	LBUMP(x)	softc->x++
121#define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
122
123static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
124static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
125static	u_32_t		ipf_checkripso(u_char *);
126static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
127#ifdef IPFILTER_LOG
128static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
129#endif
130static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
131static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **,
132					      int);
133static	ipfunc_t	ipf_findfunc(ipfunc_t);
134static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
135					     i6addr_t *, i6addr_t *);
136static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
137static	int		ipf_fr_matcharray(fr_info_t *, int *);
138static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int,
139					    void *);
140static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);
141static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
142static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
143					 ipfgeniter_t *);
144static	void		ipf_getstat(ipf_main_softc_t *,
145					 struct friostat *, int);
146static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
147static	void		ipf_group_free(frgroup_t *);
148static	int		ipf_grpmapfini(struct ipf_main_softc_s *,
149					    frentry_t *);
150static	int		ipf_grpmapinit(struct ipf_main_softc_s *,
151					    frentry_t *);
152static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
153					   frentry_t *, int);
154static	int		ipf_portcheck(frpcmp_t *, u_32_t);
155static	INLINE int	ipf_pr_ah(fr_info_t *);
156static	INLINE void	ipf_pr_esp(fr_info_t *);
157static	INLINE void	ipf_pr_gre(fr_info_t *);
158static	INLINE void	ipf_pr_udp(fr_info_t *);
159static	INLINE void	ipf_pr_tcp(fr_info_t *);
160static	INLINE void	ipf_pr_icmp(fr_info_t *);
161static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
162static	INLINE void	ipf_pr_short(fr_info_t *, int);
163static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
164static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
165static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
166					     int, int);
167static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
168						    frentry_t *, int);
169static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *,
170					  void *);
171static	void		ipf_token_flush(ipf_main_softc_t *);
172static	void		ipf_token_unlink(ipf_main_softc_t *,
173					      ipftoken_t *);
174static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *,
175						  const char *);
176static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
177						    void **);
178static	int		ipf_updateipid(fr_info_t *);
179static	int		ipf_settimeout(struct ipf_main_softc_s *,
180					    struct ipftuneable *,
181					    ipftuneval_t *);
182#if !defined(_KERNEL) || SOLARIS
183static	int		ppsratecheck(struct timeval *, int *, int);
184#endif
185
186
187/*
188 * bit values for identifying presence of individual IP options
189 * All of these tables should be ordered by increasing key value on the left
190 * hand side to allow for binary searching of the array and include a trailer
191 * with a 0 for the bitmask for linear searches to easily find the end with.
192 */
193static const	struct	optlist	ipopts[] = {
194	{ IPOPT_NOP,	0x000001 },
195	{ IPOPT_RR,	0x000002 },
196	{ IPOPT_ZSU,	0x000004 },
197	{ IPOPT_MTUP,	0x000008 },
198	{ IPOPT_MTUR,	0x000010 },
199	{ IPOPT_ENCODE,	0x000020 },
200	{ IPOPT_TS,	0x000040 },
201	{ IPOPT_TR,	0x000080 },
202	{ IPOPT_SECURITY, 0x000100 },
203	{ IPOPT_LSRR,	0x000200 },
204	{ IPOPT_E_SEC,	0x000400 },
205	{ IPOPT_CIPSO,	0x000800 },
206	{ IPOPT_SATID,	0x001000 },
207	{ IPOPT_SSRR,	0x002000 },
208	{ IPOPT_ADDEXT,	0x004000 },
209	{ IPOPT_VISA,	0x008000 },
210	{ IPOPT_IMITD,	0x010000 },
211	{ IPOPT_EIP,	0x020000 },
212	{ IPOPT_FINN,	0x040000 },
213	{ 0,		0x000000 }
214};
215
216#ifdef USE_INET6
217static const struct optlist ip6exthdr[] = {
218	{ IPPROTO_HOPOPTS,		0x000001 },
219	{ IPPROTO_IPV6,			0x000002 },
220	{ IPPROTO_ROUTING,		0x000004 },
221	{ IPPROTO_FRAGMENT,		0x000008 },
222	{ IPPROTO_ESP,			0x000010 },
223	{ IPPROTO_AH,			0x000020 },
224	{ IPPROTO_NONE,			0x000040 },
225	{ IPPROTO_DSTOPTS,		0x000080 },
226	{ IPPROTO_MOBILITY,		0x000100 },
227	{ 0,				0 }
228};
229#endif
230
231/*
232 * bit values for identifying presence of individual IP security options
233 */
234static const	struct	optlist	secopt[] = {
235	{ IPSO_CLASS_RES4,	0x01 },
236	{ IPSO_CLASS_TOPS,	0x02 },
237	{ IPSO_CLASS_SECR,	0x04 },
238	{ IPSO_CLASS_RES3,	0x08 },
239	{ IPSO_CLASS_CONF,	0x10 },
240	{ IPSO_CLASS_UNCL,	0x20 },
241	{ IPSO_CLASS_RES2,	0x40 },
242	{ IPSO_CLASS_RES1,	0x80 }
243};
244
245char	ipfilter_version[] = IPL_VERSION;
246
247int	ipf_features = 0
248#ifdef	IPFILTER_LKM
249		| IPF_FEAT_LKM
250#endif
251#ifdef	IPFILTER_LOG
252		| IPF_FEAT_LOG
253#endif
254		| IPF_FEAT_LOOKUP
255#ifdef	IPFILTER_BPF
256		| IPF_FEAT_BPF
257#endif
258#ifdef	IPFILTER_COMPILED
259		| IPF_FEAT_COMPILED
260#endif
261#ifdef	IPFILTER_CKSUM
262		| IPF_FEAT_CKSUM
263#endif
264		| IPF_FEAT_SYNC
265#ifdef	IPFILTER_SCAN
266		| IPF_FEAT_SCAN
267#endif
268#ifdef	USE_INET6
269		| IPF_FEAT_IPV6
270#endif
271	;
272
273
274/*
275 * Table of functions available for use with call rules.
276 */
277static ipfunc_resolve_t ipf_availfuncs[] = {
278	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280	{ "",	      NULL,	      NULL,	      NULL }
281};
282
283static ipftuneable_t ipf_main_tuneables[] = {
284	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285		"ipf_flags",		0,	0xffffffff,
286		stsizeof(ipf_main_softc_t, ipf_flags),
287		0,			NULL,	NULL },
288	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
289		"active",		0,	0,
290		stsizeof(ipf_main_softc_t, ipf_active),
291		IPFT_RDONLY,		NULL,	NULL },
292	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293		"control_forwarding",	0, 1,
294		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
295		0,			NULL,	NULL },
296	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
297		"update_ipid",		0,	1,
298		stsizeof(ipf_main_softc_t, ipf_update_ipid),
299		0,			NULL,	NULL },
300	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
301		"chksrc",		0,	1,
302		stsizeof(ipf_main_softc_t, ipf_chksrc),
303		0,			NULL,	NULL },
304	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
305		"min_ttl",		0,	1,
306		stsizeof(ipf_main_softc_t, ipf_minttl),
307		0,			NULL,	NULL },
308	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309		"icmp_minfragmtu",	0,	1,
310		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
311		0,			NULL,	NULL },
312	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313		"default_pass",		0,	0xffffffff,
314		stsizeof(ipf_main_softc_t, ipf_pass),
315		0,			NULL,	NULL },
316	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317		"tcp_idle_timeout",	1,	0x7fffffff,
318		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319		0,			NULL,	ipf_settimeout },
320	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321		"tcp_close_wait",	1,	0x7fffffff,
322		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323		0,			NULL,	ipf_settimeout },
324	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325		"tcp_last_ack",		1,	0x7fffffff,
326		stsizeof(ipf_main_softc_t, ipf_tcplastack),
327		0,			NULL,	ipf_settimeout },
328	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329		"tcp_timeout",		1,	0x7fffffff,
330		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331		0,			NULL,	ipf_settimeout },
332	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333		"tcp_syn_sent",		1,	0x7fffffff,
334		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335		0,			NULL,	ipf_settimeout },
336	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337		"tcp_syn_received",	1,	0x7fffffff,
338		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339		0,			NULL,	ipf_settimeout },
340	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341		"tcp_closed",		1,	0x7fffffff,
342		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343		0,			NULL,	ipf_settimeout },
344	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345		"tcp_half_closed",	1,	0x7fffffff,
346		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347		0,			NULL,	ipf_settimeout },
348	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349		"tcp_time_wait",	1,	0x7fffffff,
350		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351		0,			NULL,	ipf_settimeout },
352	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353		"udp_timeout",		1,	0x7fffffff,
354		stsizeof(ipf_main_softc_t, ipf_udptimeout),
355		0,			NULL,	ipf_settimeout },
356	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357		"udp_ack_timeout",	1,	0x7fffffff,
358		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359		0,			NULL,	ipf_settimeout },
360	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361		"icmp_timeout",		1,	0x7fffffff,
362		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363		0,			NULL,	ipf_settimeout },
364	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365		"icmp_ack_timeout",	1,	0x7fffffff,
366		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367		0,			NULL,	ipf_settimeout },
368	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369		"ip_timeout",		1,	0x7fffffff,
370		stsizeof(ipf_main_softc_t, ipf_iptimeout),
371		0,			NULL,	ipf_settimeout },
372#if defined(INSTANCES) && defined(_KERNEL)
373	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374		"intercept_loopback",	0,	1,
375		stsizeof(ipf_main_softc_t, ipf_get_loopback),
376		0,			NULL,	ipf_set_loopback },
377#endif
378	{ { 0 },
379		NULL,			0,	0,
380		0,
381		0,			NULL,	NULL }
382};
383
384
385/*
386 * The next section of code is a collection of small routines that set
387 * fields in the fr_info_t structure passed based on properties of the
388 * current packet.  There are different routines for the same protocol
389 * for each of IPv4 and IPv6.  Adding a new protocol, for which there
390 * will "special" inspection for setup, is now more easily done by adding
391 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392 * adding more code to a growing switch statement.
393 */
394#ifdef USE_INET6
395static	INLINE int	ipf_pr_ah6(fr_info_t *);
396static	INLINE void	ipf_pr_esp6(fr_info_t *);
397static	INLINE void	ipf_pr_gre6(fr_info_t *);
398static	INLINE void	ipf_pr_udp6(fr_info_t *);
399static	INLINE void	ipf_pr_tcp6(fr_info_t *);
400static	INLINE void	ipf_pr_icmp6(fr_info_t *);
401static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
402static	INLINE void	ipf_pr_short6(fr_info_t *, int);
403static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
404static	INLINE int	ipf_pr_mobility6(fr_info_t *);
405static	INLINE int	ipf_pr_routing6(fr_info_t *);
406static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
407static	INLINE int	ipf_pr_fragment6(fr_info_t *);
408static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
409
410
411/* ------------------------------------------------------------------------ */
412/* Function:    ipf_pr_short6                                               */
413/* Returns:     void                                                        */
414/* Parameters:  fin(I)  - pointer to packet information                     */
415/*              xmin(I) - minimum header size                               */
416/*                                                                          */
417/* IPv6 Only                                                                */
418/* This is function enforces the 'is a packet too short to be legit' rule   */
419/* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
420/* for ipf_pr_short() for more details.                                     */
421/* ------------------------------------------------------------------------ */
422static INLINE void
423ipf_pr_short6(fin, xmin)
424	fr_info_t *fin;
425	int xmin;
426{
427
428	if (fin->fin_dlen < xmin)
429		fin->fin_flx |= FI_SHORT;
430}
431
432
433/* ------------------------------------------------------------------------ */
434/* Function:    ipf_pr_ipv6hdr                                              */
435/* Returns:     void                                                        */
436/* Parameters:  fin(I) - pointer to packet information                      */
437/*                                                                          */
438/* IPv6 Only                                                                */
439/* Copy values from the IPv6 header into the fr_info_t struct and call the  */
440/* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
441/* analyzer may pullup or free the packet itself so we need to be vigiliant */
442/* of that possibility arising.                                             */
443/* ------------------------------------------------------------------------ */
444static INLINE void
445ipf_pr_ipv6hdr(fin)
446	fr_info_t *fin;
447{
448	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449	int p, go = 1, i, hdrcount;
450	fr_ip_t *fi = &fin->fin_fi;
451
452	fin->fin_off = 0;
453
454	fi->fi_tos = 0;
455	fi->fi_optmsk = 0;
456	fi->fi_secmsk = 0;
457	fi->fi_auth = 0;
458
459	p = ip6->ip6_nxt;
460	fin->fin_crc = p;
461	fi->fi_ttl = ip6->ip6_hlim;
462	fi->fi_src.in6 = ip6->ip6_src;
463	fin->fin_crc += fi->fi_src.i6[0];
464	fin->fin_crc += fi->fi_src.i6[1];
465	fin->fin_crc += fi->fi_src.i6[2];
466	fin->fin_crc += fi->fi_src.i6[3];
467	fi->fi_dst.in6 = ip6->ip6_dst;
468	fin->fin_crc += fi->fi_dst.i6[0];
469	fin->fin_crc += fi->fi_dst.i6[1];
470	fin->fin_crc += fi->fi_dst.i6[2];
471	fin->fin_crc += fi->fi_dst.i6[3];
472	fin->fin_id = 0;
473	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
475
476	hdrcount = 0;
477	while (go && !(fin->fin_flx & FI_SHORT)) {
478		switch (p)
479		{
480		case IPPROTO_UDP :
481			ipf_pr_udp6(fin);
482			go = 0;
483			break;
484
485		case IPPROTO_TCP :
486			ipf_pr_tcp6(fin);
487			go = 0;
488			break;
489
490		case IPPROTO_ICMPV6 :
491			ipf_pr_icmp6(fin);
492			go = 0;
493			break;
494
495		case IPPROTO_GRE :
496			ipf_pr_gre6(fin);
497			go = 0;
498			break;
499
500		case IPPROTO_HOPOPTS :
501			p = ipf_pr_hopopts6(fin);
502			break;
503
504		case IPPROTO_MOBILITY :
505			p = ipf_pr_mobility6(fin);
506			break;
507
508		case IPPROTO_DSTOPTS :
509			p = ipf_pr_dstopts6(fin);
510			break;
511
512		case IPPROTO_ROUTING :
513			p = ipf_pr_routing6(fin);
514			break;
515
516		case IPPROTO_AH :
517			p = ipf_pr_ah6(fin);
518			break;
519
520		case IPPROTO_ESP :
521			ipf_pr_esp6(fin);
522			go = 0;
523			break;
524
525		case IPPROTO_IPV6 :
526			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527				if (ip6exthdr[i].ol_val == p) {
528					fin->fin_flx |= ip6exthdr[i].ol_bit;
529					break;
530				}
531			go = 0;
532			break;
533
534		case IPPROTO_NONE :
535			go = 0;
536			break;
537
538		case IPPROTO_FRAGMENT :
539			p = ipf_pr_fragment6(fin);
540			/*
541			 * Given that the only fragments we want to let through
542			 * (where fin_off != 0) are those where the non-first
543			 * fragments only have data, we can safely stop looking
544			 * at headers if this is a non-leading fragment.
545			 */
546			if (fin->fin_off != 0)
547				go = 0;
548			break;
549
550		default :
551			go = 0;
552			break;
553		}
554		hdrcount++;
555
556		/*
557		 * It is important to note that at this point, for the
558		 * extension headers (go != 0), the entire header may not have
559		 * been pulled up when the code gets to this point.  This is
560		 * only done for "go != 0" because the other header handlers
561		 * will all pullup their complete header.  The other indicator
562		 * of an incomplete packet is that this was just an extension
563		 * header.
564		 */
565		if ((go != 0) && (p != IPPROTO_NONE) &&
566		    (ipf_pr_pullup(fin, 0) == -1)) {
567			p = IPPROTO_NONE;
568			break;
569		}
570	}
571
572	/*
573	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574	 * and destroy whatever packet was here.  The caller of this function
575	 * expects us to return if there is a problem with ipf_pullup.
576	 */
577	if (fin->fin_m == NULL) {
578		ipf_main_softc_t *softc = fin->fin_main_soft;
579
580		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
581		return;
582	}
583
584	fi->fi_p = p;
585
586	/*
587	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
589	 */
590	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591		ipf_main_softc_t *softc = fin->fin_main_soft;
592
593		fin->fin_flx |= FI_BAD;
594		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
597	}
598}
599
600
601/* ------------------------------------------------------------------------ */
602/* Function:    ipf_pr_ipv6exthdr                                           */
603/* Returns:     struct ip6_ext * - pointer to the start of the next header  */
604/*                                 or NULL if there is a prolblem.          */
605/* Parameters:  fin(I)      - pointer to packet information                 */
606/*              multiple(I) - flag indicating yes/no if multiple occurances */
607/*                            of this extension header are allowed.         */
608/*              proto(I)    - protocol number for this extension header     */
609/*                                                                          */
610/* IPv6 Only                                                                */
611/* This function embodies a number of common checks that all IPv6 extension */
612/* headers must be subjected to.  For example, making sure the packet is    */
613/* big enough for it to be in, checking if it is repeated and setting a     */
614/* flag to indicate its presence.                                           */
615/* ------------------------------------------------------------------------ */
616static INLINE struct ip6_ext *
617ipf_pr_ipv6exthdr(fin, multiple, proto)
618	fr_info_t *fin;
619	int multiple, proto;
620{
621	ipf_main_softc_t *softc = fin->fin_main_soft;
622	struct ip6_ext *hdr;
623	u_short shift;
624	int i;
625
626	fin->fin_flx |= FI_V6EXTHDR;
627
628				/* 8 is default length of extension hdr */
629	if ((fin->fin_dlen - 8) < 0) {
630		fin->fin_flx |= FI_SHORT;
631		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
632		return NULL;
633	}
634
635	if (ipf_pr_pullup(fin, 8) == -1) {
636		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
637		return NULL;
638	}
639
640	hdr = fin->fin_dp;
641	switch (proto)
642	{
643	case IPPROTO_FRAGMENT :
644		shift = 8;
645		break;
646	default :
647		shift = 8 + (hdr->ip6e_len << 3);
648		break;
649	}
650
651	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
652		fin->fin_flx |= FI_BAD;
653		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
655		return NULL;
656	}
657
658	fin->fin_dp = (char *)fin->fin_dp + shift;
659	fin->fin_dlen -= shift;
660
661	/*
662	 * If we have seen a fragment header, do not set any flags to indicate
663	 * the presence of this extension header as it has no impact on the
664	 * end result until after it has been defragmented.
665	 */
666	if (fin->fin_flx & FI_FRAG)
667		return hdr;
668
669	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670		if (ip6exthdr[i].ol_val == proto) {
671			/*
672			 * Most IPv6 extension headers are only allowed once.
673			 */
674			if ((multiple == 0) &&
675			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676				fin->fin_flx |= FI_BAD;
677				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
678			} else
679				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
680			break;
681		}
682
683	return hdr;
684}
685
686
687/* ------------------------------------------------------------------------ */
688/* Function:    ipf_pr_hopopts6                                             */
689/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
690/* Parameters:  fin(I) - pointer to packet information                      */
691/*                                                                          */
692/* IPv6 Only                                                                */
693/* This is function checks pending hop by hop options extension header      */
694/* ------------------------------------------------------------------------ */
695static INLINE int
696ipf_pr_hopopts6(fin)
697	fr_info_t *fin;
698{
699	struct ip6_ext *hdr;
700
701	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
702	if (hdr == NULL)
703		return IPPROTO_NONE;
704	return hdr->ip6e_nxt;
705}
706
707
708/* ------------------------------------------------------------------------ */
709/* Function:    ipf_pr_mobility6                                            */
710/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
711/* Parameters:  fin(I) - pointer to packet information                      */
712/*                                                                          */
713/* IPv6 Only                                                                */
714/* This is function checks the IPv6 mobility extension header               */
715/* ------------------------------------------------------------------------ */
716static INLINE int
717ipf_pr_mobility6(fin)
718	fr_info_t *fin;
719{
720	struct ip6_ext *hdr;
721
722	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
723	if (hdr == NULL)
724		return IPPROTO_NONE;
725	return hdr->ip6e_nxt;
726}
727
728
729/* ------------------------------------------------------------------------ */
730/* Function:    ipf_pr_routing6                                             */
731/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
732/* Parameters:  fin(I) - pointer to packet information                      */
733/*                                                                          */
734/* IPv6 Only                                                                */
735/* This is function checks pending routing extension header                 */
736/* ------------------------------------------------------------------------ */
737static INLINE int
738ipf_pr_routing6(fin)
739	fr_info_t *fin;
740{
741	struct ip6_routing *hdr;
742
743	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
744	if (hdr == NULL)
745		return IPPROTO_NONE;
746
747	switch (hdr->ip6r_type)
748	{
749	case 0 :
750		/*
751		 * Nasty extension header length?
752		 */
753		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755			ipf_main_softc_t *softc = fin->fin_main_soft;
756
757			fin->fin_flx |= FI_BAD;
758			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
760			return IPPROTO_NONE;
761		}
762		break;
763
764	default :
765		break;
766	}
767
768	return hdr->ip6r_nxt;
769}
770
771
772/* ------------------------------------------------------------------------ */
773/* Function:    ipf_pr_fragment6                                            */
774/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
775/* Parameters:  fin(I) - pointer to packet information                      */
776/*                                                                          */
777/* IPv6 Only                                                                */
778/* Examine the IPv6 fragment header and extract fragment offset information.*/
779/*                                                                          */
780/* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781/* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
782/* packets with a fragment header can fit into.  They are as follows:       */
783/*                                                                          */
784/* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
785/* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
786/* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
787/* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
788/* 5.  [IPV6][0-n EH][FH][data]                                             */
789/*                                                                          */
790/* IPV6 = IPv6 header, FH = Fragment Header,                                */
791/* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
792/*                                                                          */
793/* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
794/* scenario in which they happen is in extreme circumstances that are most  */
795/* likely to be an indication of an attack rather than normal traffic.      */
796/* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
797/* are two rules that can be used to guard against type 3 packets: L4       */
798/* headers must always be in a packet that has the offset field set to 0    */
799/* and no packet is allowed to overlay that where offset = 0.               */
800/* ------------------------------------------------------------------------ */
801static INLINE int
802ipf_pr_fragment6(fin)
803	fr_info_t *fin;
804{
805	ipf_main_softc_t *softc = fin->fin_main_soft;
806	struct ip6_frag *frag;
807
808	fin->fin_flx |= FI_FRAG;
809
810	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
811	if (frag == NULL) {
812		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
813		return IPPROTO_NONE;
814	}
815
816	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
817		/*
818		 * Any fragment that isn't the last fragment must have its
819		 * length as a multiple of 8.
820		 */
821		if ((fin->fin_plen & 7) != 0) {
822			fin->fin_flx |= FI_BAD;
823			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
824		}
825	}
826
827	fin->fin_fraghdr = frag;
828	fin->fin_id = frag->ip6f_ident;
829	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830	if (fin->fin_off != 0)
831		fin->fin_flx |= FI_FRAGBODY;
832
833	/*
834	 * Jumbograms aren't handled, so the max. length is 64k
835	 */
836	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837		  fin->fin_flx |= FI_BAD;
838		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
839	}
840
841	/*
842	 * We don't know where the transport layer header (or whatever is next
843	 * is), as it could be behind destination options (amongst others) so
844	 * return the fragment header as the type of packet this is.  Note that
845	 * this effectively disables the fragment cache for > 1 protocol at a
846	 * time.
847	 */
848	return frag->ip6f_nxt;
849}
850
851
852/* ------------------------------------------------------------------------ */
853/* Function:    ipf_pr_dstopts6                                             */
854/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
855/* Parameters:  fin(I) - pointer to packet information                      */
856/*                                                                          */
857/* IPv6 Only                                                                */
858/* This is function checks pending destination options extension header     */
859/* ------------------------------------------------------------------------ */
860static INLINE int
861ipf_pr_dstopts6(fin)
862	fr_info_t *fin;
863{
864	ipf_main_softc_t *softc = fin->fin_main_soft;
865	struct ip6_ext *hdr;
866
867	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
868	if (hdr == NULL) {
869		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
870		return IPPROTO_NONE;
871	}
872	return hdr->ip6e_nxt;
873}
874
875
876/* ------------------------------------------------------------------------ */
877/* Function:    ipf_pr_icmp6                                                */
878/* Returns:     void                                                        */
879/* Parameters:  fin(I) - pointer to packet information                      */
880/*                                                                          */
881/* IPv6 Only                                                                */
882/* This routine is mainly concerned with determining the minimum valid size */
883/* for an ICMPv6 packet.                                                    */
884/* ------------------------------------------------------------------------ */
885static INLINE void
886ipf_pr_icmp6(fin)
887	fr_info_t *fin;
888{
889	int minicmpsz = sizeof(struct icmp6_hdr);
890	struct icmp6_hdr *icmp6;
891
892	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893		ipf_main_softc_t *softc = fin->fin_main_soft;
894
895		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
896		return;
897	}
898
899	if (fin->fin_dlen > 1) {
900		ip6_t *ip6;
901
902		icmp6 = fin->fin_dp;
903
904		fin->fin_data[0] = *(u_short *)icmp6;
905
906		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907			fin->fin_flx |= FI_ICMPQUERY;
908
909		switch (icmp6->icmp6_type)
910		{
911		case ICMP6_ECHO_REPLY :
912		case ICMP6_ECHO_REQUEST :
913			if (fin->fin_dlen >= 6)
914				fin->fin_data[1] = icmp6->icmp6_id;
915			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
916			break;
917
918		case ICMP6_DST_UNREACH :
919		case ICMP6_PACKET_TOO_BIG :
920		case ICMP6_TIME_EXCEEDED :
921		case ICMP6_PARAM_PROB :
922			fin->fin_flx |= FI_ICMPERR;
923			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
925				break;
926
927			if (M_LEN(fin->fin_m) < fin->fin_plen) {
928				if (ipf_coalesce(fin) != 1)
929					return;
930			}
931
932			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
933				return;
934
935			/*
936			 * If the destination of this packet doesn't match the
937			 * source of the original packet then this packet is
938			 * not correct.
939			 */
940			icmp6 = fin->fin_dp;
941			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942			if (IP6_NEQ(&fin->fin_fi.fi_dst,
943				    (i6addr_t *)&ip6->ip6_src)) {
944				fin->fin_flx |= FI_BAD;
945				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
946			}
947			break;
948		default :
949			break;
950		}
951	}
952
953	ipf_pr_short6(fin, minicmpsz);
954	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955		u_char p = fin->fin_p;
956
957		fin->fin_p = IPPROTO_ICMPV6;
958		ipf_checkv6sum(fin);
959		fin->fin_p = p;
960	}
961}
962
963
964/* ------------------------------------------------------------------------ */
965/* Function:    ipf_pr_udp6                                                 */
966/* Returns:     void                                                        */
967/* Parameters:  fin(I) - pointer to packet information                      */
968/*                                                                          */
969/* IPv6 Only                                                                */
970/* Analyse the packet for IPv6/UDP properties.                              */
971/* Is not expected to be called for fragmented packets.                     */
972/* ------------------------------------------------------------------------ */
973static INLINE void
974ipf_pr_udp6(fin)
975	fr_info_t *fin;
976{
977
978	if (ipf_pr_udpcommon(fin) == 0) {
979		u_char p = fin->fin_p;
980
981		fin->fin_p = IPPROTO_UDP;
982		ipf_checkv6sum(fin);
983		fin->fin_p = p;
984	}
985}
986
987
988/* ------------------------------------------------------------------------ */
989/* Function:    ipf_pr_tcp6                                                 */
990/* Returns:     void                                                        */
991/* Parameters:  fin(I) - pointer to packet information                      */
992/*                                                                          */
993/* IPv6 Only                                                                */
994/* Analyse the packet for IPv6/TCP properties.                              */
995/* Is not expected to be called for fragmented packets.                     */
996/* ------------------------------------------------------------------------ */
997static INLINE void
998ipf_pr_tcp6(fin)
999	fr_info_t *fin;
1000{
1001
1002	if (ipf_pr_tcpcommon(fin) == 0) {
1003		u_char p = fin->fin_p;
1004
1005		fin->fin_p = IPPROTO_TCP;
1006		ipf_checkv6sum(fin);
1007		fin->fin_p = p;
1008	}
1009}
1010
1011
1012/* ------------------------------------------------------------------------ */
1013/* Function:    ipf_pr_esp6                                                 */
1014/* Returns:     void                                                        */
1015/* Parameters:  fin(I) - pointer to packet information                      */
1016/*                                                                          */
1017/* IPv6 Only                                                                */
1018/* Analyse the packet for ESP properties.                                   */
1019/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1020/* even though the newer ESP packets must also have a sequence number that  */
1021/* is 32bits as well, it is not possible(?) to determine the version from a */
1022/* simple packet header.                                                    */
1023/* ------------------------------------------------------------------------ */
1024static INLINE void
1025ipf_pr_esp6(fin)
1026	fr_info_t *fin;
1027{
1028
1029	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030		ipf_main_softc_t *softc = fin->fin_main_soft;
1031
1032		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033		return;
1034	}
1035}
1036
1037
1038/* ------------------------------------------------------------------------ */
1039/* Function:    ipf_pr_ah6                                                  */
1040/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1041/* Parameters:  fin(I) - pointer to packet information                      */
1042/*                                                                          */
1043/* IPv6 Only                                                                */
1044/* Analyse the packet for AH properties.                                    */
1045/* The minimum length is taken to be the combination of all fields in the   */
1046/* header being present and no authentication data (null algorithm used.)   */
1047/* ------------------------------------------------------------------------ */
1048static INLINE int
1049ipf_pr_ah6(fin)
1050	fr_info_t *fin;
1051{
1052	authhdr_t *ah;
1053
1054	fin->fin_flx |= FI_AH;
1055
1056	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1057	if (ah == NULL) {
1058		ipf_main_softc_t *softc = fin->fin_main_soft;
1059
1060		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061		return IPPROTO_NONE;
1062	}
1063
1064	ipf_pr_short6(fin, sizeof(*ah));
1065
1066	/*
1067	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068	 * enough data to satisfy ah_next (the very first one.)
1069	 */
1070	return ah->ah_next;
1071}
1072
1073
1074/* ------------------------------------------------------------------------ */
1075/* Function:    ipf_pr_gre6                                                 */
1076/* Returns:     void                                                        */
1077/* Parameters:  fin(I) - pointer to packet information                      */
1078/*                                                                          */
1079/* Analyse the packet for GRE properties.                                   */
1080/* ------------------------------------------------------------------------ */
1081static INLINE void
1082ipf_pr_gre6(fin)
1083	fr_info_t *fin;
1084{
1085	grehdr_t *gre;
1086
1087	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088		ipf_main_softc_t *softc = fin->fin_main_soft;
1089
1090		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1091		return;
1092	}
1093
1094	gre = fin->fin_dp;
1095	if (GRE_REV(gre->gr_flags) == 1)
1096		fin->fin_data[0] = gre->gr_call;
1097}
1098#endif	/* USE_INET6 */
1099
1100
1101/* ------------------------------------------------------------------------ */
1102/* Function:    ipf_pr_pullup                                               */
1103/* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1104/* Parameters:  fin(I)  - pointer to packet information                     */
1105/*              plen(I) - length (excluding L3 header) to pullup            */
1106/*                                                                          */
1107/* Short inline function to cut down on code duplication to perform a call  */
1108/* to ipf_pullup to ensure there is the required amount of data,            */
1109/* consecutively in the packet buffer.                                      */
1110/*                                                                          */
1111/* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1112/* points to the first byte after the complete layer 3 header, which will   */
1113/* include all of the known extension headers for IPv6 or options for IPv4. */
1114/*                                                                          */
1115/* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1116/* is necessary to add those we can already assume to be pulled up (fin_dp  */
1117/* - fin_ip) to what is passed through.                                     */
1118/* ------------------------------------------------------------------------ */
1119int
1120ipf_pr_pullup(fin, plen)
1121	fr_info_t *fin;
1122	int plen;
1123{
1124	ipf_main_softc_t *softc = fin->fin_main_soft;
1125
1126	if (fin->fin_m != NULL) {
1127		if (fin->fin_dp != NULL)
1128			plen += (char *)fin->fin_dp -
1129				((char *)fin->fin_ip + fin->fin_hlen);
1130		plen += fin->fin_hlen;
1131		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132#if defined(_KERNEL)
1133			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134				DT(ipf_pullup_fail);
1135				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1136				return -1;
1137			}
1138			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1139#else
1140			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1141			/*
1142			 * Fake ipf_pullup failing
1143			 */
1144			fin->fin_reason = FRB_PULLUP;
1145			*fin->fin_mp = NULL;
1146			fin->fin_m = NULL;
1147			fin->fin_ip = NULL;
1148			return -1;
1149#endif
1150		}
1151	}
1152	return 0;
1153}
1154
1155
1156/* ------------------------------------------------------------------------ */
1157/* Function:    ipf_pr_short                                                */
1158/* Returns:     void                                                        */
1159/* Parameters:  fin(I)  - pointer to packet information                     */
1160/*              xmin(I) - minimum header size                               */
1161/*                                                                          */
1162/* Check if a packet is "short" as defined by xmin.  The rule we are        */
1163/* applying here is that the packet must not be fragmented within the layer */
1164/* 4 header.  That is, it must not be a fragment that has its offset set to */
1165/* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1166/* entire layer 4 header must be present (min).                             */
1167/* ------------------------------------------------------------------------ */
1168static INLINE void
1169ipf_pr_short(fin, xmin)
1170	fr_info_t *fin;
1171	int xmin;
1172{
1173
1174	if (fin->fin_off == 0) {
1175		if (fin->fin_dlen < xmin)
1176			fin->fin_flx |= FI_SHORT;
1177	} else if (fin->fin_off < xmin) {
1178		fin->fin_flx |= FI_SHORT;
1179	}
1180}
1181
1182
1183/* ------------------------------------------------------------------------ */
1184/* Function:    ipf_pr_icmp                                                 */
1185/* Returns:     void                                                        */
1186/* Parameters:  fin(I) - pointer to packet information                      */
1187/*                                                                          */
1188/* IPv4 Only                                                                */
1189/* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1190/* except extrememly bad packets, both type and code will be present.       */
1191/* The expected minimum size of an ICMP packet is very much dependent on    */
1192/* the type of it.                                                          */
1193/*                                                                          */
1194/* XXX - other ICMP sanity checks?                                          */
1195/* ------------------------------------------------------------------------ */
1196static INLINE void
1197ipf_pr_icmp(fin)
1198	fr_info_t *fin;
1199{
1200	ipf_main_softc_t *softc = fin->fin_main_soft;
1201	int minicmpsz = sizeof(struct icmp);
1202	icmphdr_t *icmp;
1203	ip_t *oip;
1204
1205	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1206
1207	if (fin->fin_off != 0) {
1208		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1209		return;
1210	}
1211
1212	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1214		return;
1215	}
1216
1217	icmp = fin->fin_dp;
1218
1219	fin->fin_data[0] = *(u_short *)icmp;
1220	fin->fin_data[1] = icmp->icmp_id;
1221
1222	switch (icmp->icmp_type)
1223	{
1224	case ICMP_ECHOREPLY :
1225	case ICMP_ECHO :
1226	/* Router discovery messaes - RFC 1256 */
1227	case ICMP_ROUTERADVERT :
1228	case ICMP_ROUTERSOLICIT :
1229		fin->fin_flx |= FI_ICMPQUERY;
1230		minicmpsz = ICMP_MINLEN;
1231		break;
1232	/*
1233	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234	 * 3 * timestamp(3 * 4)
1235	 */
1236	case ICMP_TSTAMP :
1237	case ICMP_TSTAMPREPLY :
1238		fin->fin_flx |= FI_ICMPQUERY;
1239		minicmpsz = 20;
1240		break;
1241	/*
1242	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1243	 * mask(4)
1244	 */
1245	case ICMP_IREQ :
1246	case ICMP_IREQREPLY :
1247	case ICMP_MASKREQ :
1248	case ICMP_MASKREPLY :
1249		fin->fin_flx |= FI_ICMPQUERY;
1250		minicmpsz = 12;
1251		break;
1252	/*
1253	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1254	 */
1255	case ICMP_UNREACH :
1256#ifdef icmp_nextmtu
1257		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259				fin->fin_flx |= FI_BAD;
1260				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1261			}
1262		}
1263#endif
1264		/* FALLTHROUGH */
1265	case ICMP_SOURCEQUENCH :
1266	case ICMP_REDIRECT :
1267	case ICMP_TIMXCEED :
1268	case ICMP_PARAMPROB :
1269		fin->fin_flx |= FI_ICMPERR;
1270		if (ipf_coalesce(fin) != 1) {
1271			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1272			return;
1273		}
1274
1275		/*
1276		 * ICMP error packets should not be generated for IP
1277		 * packets that are a fragment that isn't the first
1278		 * fragment.
1279		 */
1280		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282			fin->fin_flx |= FI_BAD;
1283			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1284		}
1285
1286		/*
1287		 * If the destination of this packet doesn't match the
1288		 * source of the original packet then this packet is
1289		 * not correct.
1290		 */
1291		if (oip->ip_src.s_addr != fin->fin_daddr) {
1292			fin->fin_flx |= FI_BAD;
1293			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1294		}
1295		break;
1296	default :
1297		break;
1298	}
1299
1300	ipf_pr_short(fin, minicmpsz);
1301
1302	ipf_checkv4sum(fin);
1303}
1304
1305
1306/* ------------------------------------------------------------------------ */
1307/* Function:    ipf_pr_tcpcommon                                            */
1308/* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1309/* Parameters:  fin(I) - pointer to packet information                      */
1310/*                                                                          */
1311/* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1312/* and make some checks with how they interact with other fields.           */
1313/* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1314/* valid and mark the packet as bad if not.                                 */
1315/* ------------------------------------------------------------------------ */
1316static INLINE int
1317ipf_pr_tcpcommon(fin)
1318	fr_info_t *fin;
1319{
1320	ipf_main_softc_t *softc = fin->fin_main_soft;
1321	int flags, tlen;
1322	tcphdr_t *tcp;
1323
1324	fin->fin_flx |= FI_TCPUDP;
1325	if (fin->fin_off != 0) {
1326		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1327		return 0;
1328	}
1329
1330	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1332		return -1;
1333	}
1334
1335	tcp = fin->fin_dp;
1336	if (fin->fin_dlen > 3) {
1337		fin->fin_sport = ntohs(tcp->th_sport);
1338		fin->fin_dport = ntohs(tcp->th_dport);
1339	}
1340
1341	if ((fin->fin_flx & FI_SHORT) != 0) {
1342		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1343		return 1;
1344	}
1345
1346	/*
1347	 * Use of the TCP data offset *must* result in a value that is at
1348	 * least the same size as the TCP header.
1349	 */
1350	tlen = TCP_OFF(tcp) << 2;
1351	if (tlen < sizeof(tcphdr_t)) {
1352		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353		fin->fin_flx |= FI_BAD;
1354		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1355		return 1;
1356	}
1357
1358	flags = tcp->th_flags;
1359	fin->fin_tcpf = tcp->th_flags;
1360
1361	/*
1362	 * If the urgent flag is set, then the urgent pointer must
1363	 * also be set and vice versa.  Good TCP packets do not have
1364	 * just one of these set.
1365	 */
1366	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367		fin->fin_flx |= FI_BAD;
1368		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1369#if 0
1370	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1371		/*
1372		 * Ignore this case (#if 0) as it shows up in "real"
1373		 * traffic with bogus values in the urgent pointer field.
1374		 */
1375		fin->fin_flx |= FI_BAD;
1376		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1377#endif
1378	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381		fin->fin_flx |= FI_BAD;
1382		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1383#if 1
1384	} else if (((flags & TH_SYN) != 0) &&
1385		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1386		/*
1387		 * SYN with URG and PUSH set is not for normal TCP but it is
1388		 * possible(?) with T/TCP...but who uses T/TCP?
1389		 */
1390		fin->fin_flx |= FI_BAD;
1391		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1392#endif
1393	} else if (!(flags & TH_ACK)) {
1394		/*
1395		 * If the ack bit isn't set, then either the SYN or
1396		 * RST bit must be set.  If the SYN bit is set, then
1397		 * we expect the ACK field to be 0.  If the ACK is
1398		 * not set and if URG, PSH or FIN are set, consdier
1399		 * that to indicate a bad TCP packet.
1400		 */
1401		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1402			/*
1403			 * Cisco PIX sets the ACK field to a random value.
1404			 * In light of this, do not set FI_BAD until a patch
1405			 * is available from Cisco to ensure that
1406			 * interoperability between existing systems is
1407			 * achieved.
1408			 */
1409			/*fin->fin_flx |= FI_BAD*/;
1410			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411		} else if (!(flags & (TH_RST|TH_SYN))) {
1412			fin->fin_flx |= FI_BAD;
1413			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415			fin->fin_flx |= FI_BAD;
1416			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1417		}
1418	}
1419	if (fin->fin_flx & FI_BAD) {
1420		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1421		return 1;
1422	}
1423
1424	/*
1425	 * At this point, it's not exactly clear what is to be gained by
1426	 * marking up which TCP options are and are not present.  The one we
1427	 * are most interested in is the TCP window scale.  This is only in
1428	 * a SYN packet [RFC1323] so we don't need this here...?
1429	 * Now if we were to analyse the header for passive fingerprinting,
1430	 * then that might add some weight to adding this...
1431	 */
1432	if (tlen == sizeof(tcphdr_t)) {
1433		return 0;
1434	}
1435
1436	if (ipf_pr_pullup(fin, tlen) == -1) {
1437		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1438		return -1;
1439	}
1440
1441#if 0
1442	tcp = fin->fin_dp;
1443	ip = fin->fin_ip;
1444	s = (u_char *)(tcp + 1);
1445	off = IP_HL(ip) << 2;
1446# ifdef _KERNEL
1447	if (fin->fin_mp != NULL) {
1448		mb_t *m = *fin->fin_mp;
1449
1450		if (off + tlen > M_LEN(m))
1451			return;
1452	}
1453# endif
1454	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1455		opt = *s;
1456		if (opt == '\0')
1457			break;
1458		else if (opt == TCPOPT_NOP)
1459			ol = 1;
1460		else {
1461			if (tlen < 2)
1462				break;
1463			ol = (int)*(s + 1);
1464			if (ol < 2 || ol > tlen)
1465				break;
1466		}
1467
1468		for (i = 9, mv = 4; mv >= 0; ) {
1469			op = ipopts + i;
1470			if (opt == (u_char)op->ol_val) {
1471				optmsk |= op->ol_bit;
1472				break;
1473			}
1474		}
1475		tlen -= ol;
1476		s += ol;
1477	}
1478#endif /* 0 */
1479
1480	return 0;
1481}
1482
1483
1484
1485/* ------------------------------------------------------------------------ */
1486/* Function:    ipf_pr_udpcommon                                            */
1487/* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1488/* Parameters:  fin(I) - pointer to packet information                      */
1489/*                                                                          */
1490/* Extract the UDP source and destination ports, if present.  If compiled   */
1491/* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1492/* ------------------------------------------------------------------------ */
1493static INLINE int
1494ipf_pr_udpcommon(fin)
1495	fr_info_t *fin;
1496{
1497	udphdr_t *udp;
1498
1499	fin->fin_flx |= FI_TCPUDP;
1500
1501	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503			ipf_main_softc_t *softc = fin->fin_main_soft;
1504
1505			fin->fin_flx |= FI_SHORT;
1506			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1507			return 1;
1508		}
1509
1510		udp = fin->fin_dp;
1511
1512		fin->fin_sport = ntohs(udp->uh_sport);
1513		fin->fin_dport = ntohs(udp->uh_dport);
1514	}
1515
1516	return 0;
1517}
1518
1519
1520/* ------------------------------------------------------------------------ */
1521/* Function:    ipf_pr_tcp                                                  */
1522/* Returns:     void                                                        */
1523/* Parameters:  fin(I) - pointer to packet information                      */
1524/*                                                                          */
1525/* IPv4 Only                                                                */
1526/* Analyse the packet for IPv4/TCP properties.                              */
1527/* ------------------------------------------------------------------------ */
1528static INLINE void
1529ipf_pr_tcp(fin)
1530	fr_info_t *fin;
1531{
1532
1533	ipf_pr_short(fin, sizeof(tcphdr_t));
1534
1535	if (ipf_pr_tcpcommon(fin) == 0)
1536		ipf_checkv4sum(fin);
1537}
1538
1539
1540/* ------------------------------------------------------------------------ */
1541/* Function:    ipf_pr_udp                                                  */
1542/* Returns:     void                                                        */
1543/* Parameters:  fin(I) - pointer to packet information                      */
1544/*                                                                          */
1545/* IPv4 Only                                                                */
1546/* Analyse the packet for IPv4/UDP properties.                              */
1547/* ------------------------------------------------------------------------ */
1548static INLINE void
1549ipf_pr_udp(fin)
1550	fr_info_t *fin;
1551{
1552
1553	ipf_pr_short(fin, sizeof(udphdr_t));
1554
1555	if (ipf_pr_udpcommon(fin) == 0)
1556		ipf_checkv4sum(fin);
1557}
1558
1559
1560/* ------------------------------------------------------------------------ */
1561/* Function:    ipf_pr_esp                                                  */
1562/* Returns:     void                                                        */
1563/* Parameters:  fin(I) - pointer to packet information                      */
1564/*                                                                          */
1565/* Analyse the packet for ESP properties.                                   */
1566/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1567/* even though the newer ESP packets must also have a sequence number that  */
1568/* is 32bits as well, it is not possible(?) to determine the version from a */
1569/* simple packet header.                                                    */
1570/* ------------------------------------------------------------------------ */
1571static INLINE void
1572ipf_pr_esp(fin)
1573	fr_info_t *fin;
1574{
1575
1576	if (fin->fin_off == 0) {
1577		ipf_pr_short(fin, 8);
1578		if (ipf_pr_pullup(fin, 8) == -1) {
1579			ipf_main_softc_t *softc = fin->fin_main_soft;
1580
1581			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1582		}
1583	}
1584}
1585
1586
1587/* ------------------------------------------------------------------------ */
1588/* Function:    ipf_pr_ah                                                   */
1589/* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1590/* Parameters:  fin(I) - pointer to packet information                      */
1591/*                                                                          */
1592/* Analyse the packet for AH properties.                                    */
1593/* The minimum length is taken to be the combination of all fields in the   */
1594/* header being present and no authentication data (null algorithm used.)   */
1595/* ------------------------------------------------------------------------ */
1596static INLINE int
1597ipf_pr_ah(fin)
1598	fr_info_t *fin;
1599{
1600	ipf_main_softc_t *softc = fin->fin_main_soft;
1601	authhdr_t *ah;
1602	int len;
1603
1604	fin->fin_flx |= FI_AH;
1605	ipf_pr_short(fin, sizeof(*ah));
1606
1607	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609		return IPPROTO_NONE;
1610	}
1611
1612	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613		DT(fr_v4_ah_pullup_1);
1614		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615		return IPPROTO_NONE;
1616	}
1617
1618	ah = (authhdr_t *)fin->fin_dp;
1619
1620	len = (ah->ah_plen + 2) << 2;
1621	ipf_pr_short(fin, len);
1622	if (ipf_pr_pullup(fin, len) == -1) {
1623		DT(fr_v4_ah_pullup_2);
1624		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625		return IPPROTO_NONE;
1626	}
1627
1628	/*
1629	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1630	 * header.
1631	 */
1632	fin->fin_dp = (char *)fin->fin_dp + len;
1633	fin->fin_dlen -= len;
1634	return ah->ah_next;
1635}
1636
1637
1638/* ------------------------------------------------------------------------ */
1639/* Function:    ipf_pr_gre                                                  */
1640/* Returns:     void                                                        */
1641/* Parameters:  fin(I) - pointer to packet information                      */
1642/*                                                                          */
1643/* Analyse the packet for GRE properties.                                   */
1644/* ------------------------------------------------------------------------ */
1645static INLINE void
1646ipf_pr_gre(fin)
1647	fr_info_t *fin;
1648{
1649	ipf_main_softc_t *softc = fin->fin_main_soft;
1650	grehdr_t *gre;
1651
1652	ipf_pr_short(fin, sizeof(grehdr_t));
1653
1654	if (fin->fin_off != 0) {
1655		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1656		return;
1657	}
1658
1659	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1661		return;
1662	}
1663
1664	gre = fin->fin_dp;
1665	if (GRE_REV(gre->gr_flags) == 1)
1666		fin->fin_data[0] = gre->gr_call;
1667}
1668
1669
1670/* ------------------------------------------------------------------------ */
1671/* Function:    ipf_pr_ipv4hdr                                              */
1672/* Returns:     void                                                        */
1673/* Parameters:  fin(I) - pointer to packet information                      */
1674/*                                                                          */
1675/* IPv4 Only                                                                */
1676/* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1677/* Check all options present and flag their presence if any exist.          */
1678/* ------------------------------------------------------------------------ */
1679static INLINE void
1680ipf_pr_ipv4hdr(fin)
1681	fr_info_t *fin;
1682{
1683	u_short optmsk = 0, secmsk = 0, auth = 0;
1684	int hlen, ol, mv, p, i;
1685	const struct optlist *op;
1686	u_char *s, opt;
1687	u_short off;
1688	fr_ip_t *fi;
1689	ip_t *ip;
1690
1691	fi = &fin->fin_fi;
1692	hlen = fin->fin_hlen;
1693
1694	ip = fin->fin_ip;
1695	p = ip->ip_p;
1696	fi->fi_p = p;
1697	fin->fin_crc = p;
1698	fi->fi_tos = ip->ip_tos;
1699	fin->fin_id = ntohs(ip->ip_id);
1700	off = ntohs(ip->ip_off);
1701
1702	/* Get both TTL and protocol */
1703	fi->fi_p = ip->ip_p;
1704	fi->fi_ttl = ip->ip_ttl;
1705
1706	/* Zero out bits not used in IPv6 address */
1707	fi->fi_src.i6[1] = 0;
1708	fi->fi_src.i6[2] = 0;
1709	fi->fi_src.i6[3] = 0;
1710	fi->fi_dst.i6[1] = 0;
1711	fi->fi_dst.i6[2] = 0;
1712	fi->fi_dst.i6[3] = 0;
1713
1714	fi->fi_saddr = ip->ip_src.s_addr;
1715	fin->fin_crc += fi->fi_saddr;
1716	fi->fi_daddr = ip->ip_dst.s_addr;
1717	fin->fin_crc += fi->fi_daddr;
1718	if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1720
1721	/*
1722	 * set packet attribute flags based on the offset and
1723	 * calculate the byte offset that it represents.
1724	 */
1725	off &= IP_MF|IP_OFFMASK;
1726	if (off != 0) {
1727		int morefrag = off & IP_MF;
1728
1729		fi->fi_flx |= FI_FRAG;
1730		off &= IP_OFFMASK;
1731		if (off == 1 && p == IPPROTO_TCP) {
1732			fin->fin_flx |= FI_SHORT;	/* RFC 3128 */
1733			DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1734		}
1735		if (off != 0) {
1736			fin->fin_flx |= FI_FRAGBODY;
1737			off <<= 3;
1738			if ((off + fin->fin_dlen > 65535) ||
1739			    (fin->fin_dlen == 0) ||
1740			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1741				/*
1742				 * The length of the packet, starting at its
1743				 * offset cannot exceed 65535 (0xffff) as the
1744				 * length of an IP packet is only 16 bits.
1745				 *
1746				 * Any fragment that isn't the last fragment
1747				 * must have a length greater than 0 and it
1748				 * must be an even multiple of 8.
1749				 */
1750				fi->fi_flx |= FI_BAD;
1751				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1752			}
1753		}
1754	}
1755	fin->fin_off = off;
1756
1757	/*
1758	 * Call per-protocol setup and checking
1759	 */
1760	if (p == IPPROTO_AH) {
1761		/*
1762		 * Treat AH differently because we expect there to be another
1763		 * layer 4 header after it.
1764		 */
1765		p = ipf_pr_ah(fin);
1766	}
1767
1768	switch (p)
1769	{
1770	case IPPROTO_UDP :
1771		ipf_pr_udp(fin);
1772		break;
1773	case IPPROTO_TCP :
1774		ipf_pr_tcp(fin);
1775		break;
1776	case IPPROTO_ICMP :
1777		ipf_pr_icmp(fin);
1778		break;
1779	case IPPROTO_ESP :
1780		ipf_pr_esp(fin);
1781		break;
1782	case IPPROTO_GRE :
1783		ipf_pr_gre(fin);
1784		break;
1785	}
1786
1787	ip = fin->fin_ip;
1788	if (ip == NULL)
1789		return;
1790
1791	/*
1792	 * If it is a standard IP header (no options), set the flag fields
1793	 * which relate to options to 0.
1794	 */
1795	if (hlen == sizeof(*ip)) {
1796		fi->fi_optmsk = 0;
1797		fi->fi_secmsk = 0;
1798		fi->fi_auth = 0;
1799		return;
1800	}
1801
1802	/*
1803	 * So the IP header has some IP options attached.  Walk the entire
1804	 * list of options present with this packet and set flags to indicate
1805	 * which ones are here and which ones are not.  For the somewhat out
1806	 * of date and obscure security classification options, set a flag to
1807	 * represent which classification is present.
1808	 */
1809	fi->fi_flx |= FI_OPTIONS;
1810
1811	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1812		opt = *s;
1813		if (opt == '\0')
1814			break;
1815		else if (opt == IPOPT_NOP)
1816			ol = 1;
1817		else {
1818			if (hlen < 2)
1819				break;
1820			ol = (int)*(s + 1);
1821			if (ol < 2 || ol > hlen)
1822				break;
1823		}
1824		for (i = 9, mv = 4; mv >= 0; ) {
1825			op = ipopts + i;
1826
1827			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1828				u_32_t doi;
1829
1830				switch (opt)
1831				{
1832				case IPOPT_SECURITY :
1833					if (optmsk & op->ol_bit) {
1834						fin->fin_flx |= FI_BAD;
1835						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1836					} else {
1837						doi = ipf_checkripso(s);
1838						secmsk = doi >> 16;
1839						auth = doi & 0xffff;
1840					}
1841					break;
1842
1843				case IPOPT_CIPSO :
1844
1845					if (optmsk & op->ol_bit) {
1846						fin->fin_flx |= FI_BAD;
1847						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1848					} else {
1849						doi = ipf_checkcipso(fin,
1850								     s, ol);
1851						secmsk = doi >> 16;
1852						auth = doi & 0xffff;
1853					}
1854					break;
1855				}
1856				optmsk |= op->ol_bit;
1857			}
1858
1859			if (opt < op->ol_val)
1860				i -= mv;
1861			else
1862				i += mv;
1863			mv--;
1864		}
1865		hlen -= ol;
1866		s += ol;
1867	}
1868
1869	/*
1870	 *
1871	 */
1872	if (auth && !(auth & 0x0100))
1873		auth &= 0xff00;
1874	fi->fi_optmsk = optmsk;
1875	fi->fi_secmsk = secmsk;
1876	fi->fi_auth = auth;
1877}
1878
1879
1880/* ------------------------------------------------------------------------ */
1881/* Function:    ipf_checkripso                                              */
1882/* Returns:     void                                                        */
1883/* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1884/*                                                                          */
1885/* ------------------------------------------------------------------------ */
1886static u_32_t
1887ipf_checkripso(s)
1888	u_char *s;
1889{
1890	const struct optlist *sp;
1891	u_short secmsk = 0, auth = 0;
1892	u_char sec;
1893	int j, m;
1894
1895	sec = *(s + 2);	/* classification */
1896	for (j = 3, m = 2; m >= 0; ) {
1897		sp = secopt + j;
1898		if (sec == sp->ol_val) {
1899			secmsk |= sp->ol_bit;
1900			auth = *(s + 3);
1901			auth *= 256;
1902			auth += *(s + 4);
1903			break;
1904		}
1905		if (sec < sp->ol_val)
1906			j -= m;
1907		else
1908			j += m;
1909		m--;
1910	}
1911
1912	return (secmsk << 16) | auth;
1913}
1914
1915
1916/* ------------------------------------------------------------------------ */
1917/* Function:    ipf_checkcipso                                              */
1918/* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1919/* Parameters:  fin(IO) - pointer to packet information                     */
1920/*              s(I)    - pointer to start of CIPSO option                  */
1921/*              ol(I)   - length of CIPSO option field                      */
1922/*                                                                          */
1923/* This function returns the domain of integrity (DOI) field from the CIPSO */
1924/* header and returns that whilst also storing the highest sensitivity      */
1925/* value found in the fr_info_t structure.                                  */
1926/*                                                                          */
1927/* No attempt is made to extract the category bitmaps as these are defined  */
1928/* by the user (rather than the protocol) and can be rather numerous on the */
1929/* end nodes.                                                               */
1930/* ------------------------------------------------------------------------ */
1931static u_32_t
1932ipf_checkcipso(fin, s, ol)
1933	fr_info_t *fin;
1934	u_char *s;
1935	int ol;
1936{
1937	ipf_main_softc_t *softc = fin->fin_main_soft;
1938	fr_ip_t *fi;
1939	u_32_t doi;
1940	u_char *t, tag, tlen, sensitivity;
1941	int len;
1942
1943	if (ol < 6 || ol > 40) {
1944		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1945		fin->fin_flx |= FI_BAD;
1946		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1947		return 0;
1948	}
1949
1950	fi = &fin->fin_fi;
1951	fi->fi_sensitivity = 0;
1952	/*
1953	 * The DOI field MUST be there.
1954	 */
1955	bcopy(s + 2, &doi, sizeof(doi));
1956
1957	t = (u_char *)s + 6;
1958	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1959		tag = *t;
1960		tlen = *(t + 1);
1961		if (tlen > len || tlen < 4 || tlen > 34) {
1962			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1963			fin->fin_flx |= FI_BAD;
1964			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1965			return 0;
1966		}
1967
1968		sensitivity = 0;
1969		/*
1970		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1971		 * draft (16 July 1992) that has expired.
1972		 */
1973		if (tag == 0) {
1974			fin->fin_flx |= FI_BAD;
1975			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1976			continue;
1977		} else if (tag == 1) {
1978			if (*(t + 2) != 0) {
1979				fin->fin_flx |= FI_BAD;
1980				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1981				continue;
1982			}
1983			sensitivity = *(t + 3);
1984			/* Category bitmap for categories 0-239 */
1985
1986		} else if (tag == 4) {
1987			if (*(t + 2) != 0) {
1988				fin->fin_flx |= FI_BAD;
1989				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1990				continue;
1991			}
1992			sensitivity = *(t + 3);
1993			/* Enumerated categories, 16bits each, upto 15 */
1994
1995		} else if (tag == 5) {
1996			if (*(t + 2) != 0) {
1997				fin->fin_flx |= FI_BAD;
1998				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1999				continue;
2000			}
2001			sensitivity = *(t + 3);
2002			/* Range of categories (2*16bits), up to 7 pairs */
2003
2004		} else if (tag > 127) {
2005			/* Custom defined DOI */
2006			;
2007		} else {
2008			fin->fin_flx |= FI_BAD;
2009			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2010			continue;
2011		}
2012
2013		if (sensitivity > fi->fi_sensitivity)
2014			fi->fi_sensitivity = sensitivity;
2015	}
2016
2017	return doi;
2018}
2019
2020
2021/* ------------------------------------------------------------------------ */
2022/* Function:    ipf_makefrip                                                */
2023/* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2024/* Parameters:  hlen(I) - length of IP packet header                        */
2025/*              ip(I)   - pointer to the IP header                          */
2026/*              fin(IO) - pointer to packet information                     */
2027/*                                                                          */
2028/* Compact the IP header into a structure which contains just the info.     */
2029/* which is useful for comparing IP headers with and store this information */
2030/* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2031/* this function will be called with either an IPv4 or IPv6 packet.         */
2032/* ------------------------------------------------------------------------ */
2033int
2034ipf_makefrip(hlen, ip, fin)
2035	int hlen;
2036	ip_t *ip;
2037	fr_info_t *fin;
2038{
2039	ipf_main_softc_t *softc = fin->fin_main_soft;
2040	int v;
2041
2042	fin->fin_depth = 0;
2043	fin->fin_hlen = (u_short)hlen;
2044	fin->fin_ip = ip;
2045	fin->fin_rule = 0xffffffff;
2046	fin->fin_group[0] = -1;
2047	fin->fin_group[1] = '\0';
2048	fin->fin_dp = (char *)ip + hlen;
2049
2050	v = fin->fin_v;
2051	if (v == 4) {
2052		fin->fin_plen = ntohs(ip->ip_len);
2053		fin->fin_dlen = fin->fin_plen - hlen;
2054		ipf_pr_ipv4hdr(fin);
2055#ifdef	USE_INET6
2056	} else if (v == 6) {
2057		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2058		fin->fin_dlen = fin->fin_plen;
2059		fin->fin_plen += hlen;
2060
2061		ipf_pr_ipv6hdr(fin);
2062#endif
2063	}
2064	if (fin->fin_ip == NULL) {
2065		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2066		return -1;
2067	}
2068	return 0;
2069}
2070
2071
2072/* ------------------------------------------------------------------------ */
2073/* Function:    ipf_portcheck                                               */
2074/* Returns:     int - 1 == port matched, 0 == port match failed             */
2075/* Parameters:  frp(I) - pointer to port check `expression'                 */
2076/*              pop(I) - port number to evaluate                            */
2077/*                                                                          */
2078/* Perform a comparison of a port number against some other(s), using a     */
2079/* structure with compare information stored in it.                         */
2080/* ------------------------------------------------------------------------ */
2081static INLINE int
2082ipf_portcheck(frp, pop)
2083	frpcmp_t *frp;
2084	u_32_t pop;
2085{
2086	int err = 1;
2087	u_32_t po;
2088
2089	po = frp->frp_port;
2090
2091	/*
2092	 * Do opposite test to that required and continue if that succeeds.
2093	 */
2094	switch (frp->frp_cmp)
2095	{
2096	case FR_EQUAL :
2097		if (pop != po) /* EQUAL */
2098			err = 0;
2099		break;
2100	case FR_NEQUAL :
2101		if (pop == po) /* NOTEQUAL */
2102			err = 0;
2103		break;
2104	case FR_LESST :
2105		if (pop >= po) /* LESSTHAN */
2106			err = 0;
2107		break;
2108	case FR_GREATERT :
2109		if (pop <= po) /* GREATERTHAN */
2110			err = 0;
2111		break;
2112	case FR_LESSTE :
2113		if (pop > po) /* LT or EQ */
2114			err = 0;
2115		break;
2116	case FR_GREATERTE :
2117		if (pop < po) /* GT or EQ */
2118			err = 0;
2119		break;
2120	case FR_OUTRANGE :
2121		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2122			err = 0;
2123		break;
2124	case FR_INRANGE :
2125		if (pop <= po || pop >= frp->frp_top) /* In range */
2126			err = 0;
2127		break;
2128	case FR_INCRANGE :
2129		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2130			err = 0;
2131		break;
2132	default :
2133		break;
2134	}
2135	return err;
2136}
2137
2138
2139/* ------------------------------------------------------------------------ */
2140/* Function:    ipf_tcpudpchk                                               */
2141/* Returns:     int - 1 == protocol matched, 0 == check failed              */
2142/* Parameters:  fda(I) - pointer to packet information                      */
2143/*              ft(I)  - pointer to structure with comparison data          */
2144/*                                                                          */
2145/* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2146/* structure containing information that we want to match against.          */
2147/* ------------------------------------------------------------------------ */
2148int
2149ipf_tcpudpchk(fi, ft)
2150	fr_ip_t *fi;
2151	frtuc_t *ft;
2152{
2153	int err = 1;
2154
2155	/*
2156	 * Both ports should *always* be in the first fragment.
2157	 * So far, I cannot find any cases where they can not be.
2158	 *
2159	 * compare destination ports
2160	 */
2161	if (ft->ftu_dcmp)
2162		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2163
2164	/*
2165	 * compare source ports
2166	 */
2167	if (err && ft->ftu_scmp)
2168		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2169
2170	/*
2171	 * If we don't have all the TCP/UDP header, then how can we
2172	 * expect to do any sort of match on it ?  If we were looking for
2173	 * TCP flags, then NO match.  If not, then match (which should
2174	 * satisfy the "short" class too).
2175	 */
2176	if (err && (fi->fi_p == IPPROTO_TCP)) {
2177		if (fi->fi_flx & FI_SHORT)
2178			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2179		/*
2180		 * Match the flags ?  If not, abort this match.
2181		 */
2182		if (ft->ftu_tcpfm &&
2183		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2184			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2185				 ft->ftu_tcpfm, ft->ftu_tcpf));
2186			err = 0;
2187		}
2188	}
2189	return err;
2190}
2191
2192
2193/* ------------------------------------------------------------------------ */
2194/* Function:    ipf_check_ipf                                               */
2195/* Returns:     int - 0 == match, else no match                             */
2196/* Parameters:  fin(I)     - pointer to packet information                  */
2197/*              fr(I)      - pointer to filter rule                         */
2198/*              portcmp(I) - flag indicating whether to attempt matching on */
2199/*                           TCP/UDP port data.                             */
2200/*                                                                          */
2201/* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2202/* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2203/* this function.                                                           */
2204/* ------------------------------------------------------------------------ */
2205static INLINE int
2206ipf_check_ipf(fin, fr, portcmp)
2207	fr_info_t *fin;
2208	frentry_t *fr;
2209	int portcmp;
2210{
2211	u_32_t	*ld, *lm, *lip;
2212	fripf_t *fri;
2213	fr_ip_t *fi;
2214	int i;
2215
2216	fi = &fin->fin_fi;
2217	fri = fr->fr_ipf;
2218	lip = (u_32_t *)fi;
2219	lm = (u_32_t *)&fri->fri_mip;
2220	ld = (u_32_t *)&fri->fri_ip;
2221
2222	/*
2223	 * first 32 bits to check coversion:
2224	 * IP version, TOS, TTL, protocol
2225	 */
2226	i = ((*lip & *lm) != *ld);
2227	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2228		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2229	if (i)
2230		return 1;
2231
2232	/*
2233	 * Next 32 bits is a constructed bitmask indicating which IP options
2234	 * are present (if any) in this packet.
2235	 */
2236	lip++, lm++, ld++;
2237	i = ((*lip & *lm) != *ld);
2238	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2239		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2240	if (i != 0)
2241		return 1;
2242
2243	lip++, lm++, ld++;
2244	/*
2245	 * Unrolled loops (4 each, for 32 bits) for address checks.
2246	 */
2247	/*
2248	 * Check the source address.
2249	 */
2250	if (fr->fr_satype == FRI_LOOKUP) {
2251		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2252				      fi->fi_v, lip, fin->fin_plen);
2253		if (i == -1)
2254			return 1;
2255		lip += 3;
2256		lm += 3;
2257		ld += 3;
2258	} else {
2259		i = ((*lip & *lm) != *ld);
2260		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2261			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262		if (fi->fi_v == 6) {
2263			lip++, lm++, ld++;
2264			i |= ((*lip & *lm) != *ld);
2265			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2266				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2267			lip++, lm++, ld++;
2268			i |= ((*lip & *lm) != *ld);
2269			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2270				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271			lip++, lm++, ld++;
2272			i |= ((*lip & *lm) != *ld);
2273			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2274				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2275		} else {
2276			lip += 3;
2277			lm += 3;
2278			ld += 3;
2279		}
2280	}
2281	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2282	if (i != 0)
2283		return 1;
2284
2285	/*
2286	 * Check the destination address.
2287	 */
2288	lip++, lm++, ld++;
2289	if (fr->fr_datype == FRI_LOOKUP) {
2290		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2291				      fi->fi_v, lip, fin->fin_plen);
2292		if (i == -1)
2293			return 1;
2294		lip += 3;
2295		lm += 3;
2296		ld += 3;
2297	} else {
2298		i = ((*lip & *lm) != *ld);
2299		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2300			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2301		if (fi->fi_v == 6) {
2302			lip++, lm++, ld++;
2303			i |= ((*lip & *lm) != *ld);
2304			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2305				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2306			lip++, lm++, ld++;
2307			i |= ((*lip & *lm) != *ld);
2308			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2309				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310			lip++, lm++, ld++;
2311			i |= ((*lip & *lm) != *ld);
2312			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2313				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2314		} else {
2315			lip += 3;
2316			lm += 3;
2317			ld += 3;
2318		}
2319	}
2320	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2321	if (i != 0)
2322		return 1;
2323	/*
2324	 * IP addresses matched.  The next 32bits contains:
2325	 * mast of old IP header security & authentication bits.
2326	 */
2327	lip++, lm++, ld++;
2328	i = (*ld - (*lip & *lm));
2329	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2330
2331	/*
2332	 * Next we have 32 bits of packet flags.
2333	 */
2334	lip++, lm++, ld++;
2335	i |= (*ld - (*lip & *lm));
2336	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2337
2338	if (i == 0) {
2339		/*
2340		 * If a fragment, then only the first has what we're
2341		 * looking for here...
2342		 */
2343		if (portcmp) {
2344			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2345				i = 1;
2346		} else {
2347			if (fr->fr_dcmp || fr->fr_scmp ||
2348			    fr->fr_tcpf || fr->fr_tcpfm)
2349				i = 1;
2350			if (fr->fr_icmpm || fr->fr_icmp) {
2351				if (((fi->fi_p != IPPROTO_ICMP) &&
2352				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2353				    fin->fin_off || (fin->fin_dlen < 2))
2354					i = 1;
2355				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2356					 fr->fr_icmp) {
2357					FR_DEBUG(("i. %#x & %#x != %#x\n",
2358						 fin->fin_data[0],
2359						 fr->fr_icmpm, fr->fr_icmp));
2360					i = 1;
2361				}
2362			}
2363		}
2364	}
2365	return i;
2366}
2367
2368
2369/* ------------------------------------------------------------------------ */
2370/* Function:    ipf_scanlist                                                */
2371/* Returns:     int - result flags of scanning filter list                  */
2372/* Parameters:  fin(I) - pointer to packet information                      */
2373/*              pass(I) - default result to return for filtering            */
2374/*                                                                          */
2375/* Check the input/output list of rules for a match to the current packet.  */
2376/* If a match is found, the value of fr_flags from the rule becomes the     */
2377/* return value and fin->fin_fr points to the matched rule.                 */
2378/*                                                                          */
2379/* This function may be called recusively upto 16 times (limit inbuilt.)    */
2380/* When unwinding, it should finish up with fin_depth as 0.                 */
2381/*                                                                          */
2382/* Could be per interface, but this gets real nasty when you don't have,    */
2383/* or can't easily change, the kernel source code to .                      */
2384/* ------------------------------------------------------------------------ */
2385int
2386ipf_scanlist(fin, pass)
2387	fr_info_t *fin;
2388	u_32_t pass;
2389{
2390	ipf_main_softc_t *softc = fin->fin_main_soft;
2391	int rulen, portcmp, off, skip;
2392	struct frentry *fr, *fnext;
2393	u_32_t passt, passo;
2394
2395	/*
2396	 * Do not allow nesting deeper than 16 levels.
2397	 */
2398	if (fin->fin_depth >= 16)
2399		return pass;
2400
2401	fr = fin->fin_fr;
2402
2403	/*
2404	 * If there are no rules in this list, return now.
2405	 */
2406	if (fr == NULL)
2407		return pass;
2408
2409	skip = 0;
2410	portcmp = 0;
2411	fin->fin_depth++;
2412	fin->fin_fr = NULL;
2413	off = fin->fin_off;
2414
2415	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2416		portcmp = 1;
2417
2418	for (rulen = 0; fr; fr = fnext, rulen++) {
2419		fnext = fr->fr_next;
2420		if (skip != 0) {
2421			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2422			skip--;
2423			continue;
2424		}
2425
2426		/*
2427		 * In all checks below, a null (zero) value in the
2428		 * filter struture is taken to mean a wildcard.
2429		 *
2430		 * check that we are working for the right interface
2431		 */
2432#ifdef	_KERNEL
2433		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2434			continue;
2435#else
2436		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2437			printf("\n");
2438		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2439				  FR_ISPASS(pass) ? 'p' :
2440				  FR_ISACCOUNT(pass) ? 'A' :
2441				  FR_ISAUTH(pass) ? 'a' :
2442				  (pass & FR_NOMATCH) ? 'n' :'b'));
2443		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2444			continue;
2445		FR_VERBOSE((":i"));
2446#endif
2447
2448		switch (fr->fr_type)
2449		{
2450		case FR_T_IPF :
2451		case FR_T_IPF_BUILTIN :
2452			if (ipf_check_ipf(fin, fr, portcmp))
2453				continue;
2454			break;
2455#if defined(IPFILTER_BPF)
2456		case FR_T_BPFOPC :
2457		case FR_T_BPFOPC_BUILTIN :
2458		    {
2459			u_char *mc;
2460			int wlen;
2461
2462			if (*fin->fin_mp == NULL)
2463				continue;
2464			if (fin->fin_family != fr->fr_family)
2465				continue;
2466			mc = (u_char *)fin->fin_m;
2467			wlen = fin->fin_dlen + fin->fin_hlen;
2468			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2469				continue;
2470			break;
2471		    }
2472#endif
2473		case FR_T_CALLFUNC_BUILTIN :
2474		    {
2475			frentry_t *f;
2476
2477			f = (*fr->fr_func)(fin, &pass);
2478			if (f != NULL)
2479				fr = f;
2480			else
2481				continue;
2482			break;
2483		    }
2484
2485		case FR_T_IPFEXPR :
2486		case FR_T_IPFEXPR_BUILTIN :
2487			if (fin->fin_family != fr->fr_family)
2488				continue;
2489			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2490				continue;
2491			break;
2492
2493		default :
2494			break;
2495		}
2496
2497		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2498			if (fin->fin_nattag == NULL)
2499				continue;
2500			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2501				continue;
2502		}
2503		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2504
2505		passt = fr->fr_flags;
2506
2507		/*
2508		 * If the rule is a "call now" rule, then call the function
2509		 * in the rule, if it exists and use the results from that.
2510		 * If the function pointer is bad, just make like we ignore
2511		 * it, except for increasing the hit counter.
2512		 */
2513		if ((passt & FR_CALLNOW) != 0) {
2514			frentry_t *frs;
2515
2516			ATOMIC_INC64(fr->fr_hits);
2517			if ((fr->fr_func == NULL) ||
2518			    (fr->fr_func == (ipfunc_t)-1))
2519				continue;
2520
2521			frs = fin->fin_fr;
2522			fin->fin_fr = fr;
2523			fr = (*fr->fr_func)(fin, &passt);
2524			if (fr == NULL) {
2525				fin->fin_fr = frs;
2526				continue;
2527			}
2528			passt = fr->fr_flags;
2529		}
2530		fin->fin_fr = fr;
2531
2532#ifdef  IPFILTER_LOG
2533		/*
2534		 * Just log this packet...
2535		 */
2536		if ((passt & FR_LOGMASK) == FR_LOG) {
2537			if (ipf_log_pkt(fin, passt) == -1) {
2538				if (passt & FR_LOGORBLOCK) {
2539					DT(frb_logfail);
2540					passt &= ~FR_CMDMASK;
2541					passt |= FR_BLOCK|FR_QUICK;
2542					fin->fin_reason = FRB_LOGFAIL;
2543				}
2544			}
2545		}
2546#endif /* IPFILTER_LOG */
2547
2548		MUTEX_ENTER(&fr->fr_lock);
2549		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2550		fr->fr_hits++;
2551		MUTEX_EXIT(&fr->fr_lock);
2552		fin->fin_rule = rulen;
2553
2554		passo = pass;
2555		if (FR_ISSKIP(passt)) {
2556			skip = fr->fr_arg;
2557			continue;
2558		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2559			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2560			pass = passt;
2561		}
2562
2563		if (passt & (FR_RETICMP|FR_FAKEICMP))
2564			fin->fin_icode = fr->fr_icode;
2565
2566		if (fr->fr_group != -1) {
2567			(void) strncpy(fin->fin_group,
2568				       FR_NAME(fr, fr_group),
2569				       strlen(FR_NAME(fr, fr_group)));
2570		} else {
2571			fin->fin_group[0] = '\0';
2572		}
2573
2574		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2575
2576		if (fr->fr_grphead != NULL) {
2577			fin->fin_fr = fr->fr_grphead->fg_start;
2578			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2579
2580			if (FR_ISDECAPS(passt))
2581				passt = ipf_decaps(fin, pass, fr->fr_icode);
2582			else
2583				passt = ipf_scanlist(fin, pass);
2584
2585			if (fin->fin_fr == NULL) {
2586				fin->fin_rule = rulen;
2587				if (fr->fr_group != -1)
2588					(void) strncpy(fin->fin_group,
2589						       fr->fr_names +
2590						       fr->fr_group,
2591						       strlen(fr->fr_names +
2592							      fr->fr_group));
2593				fin->fin_fr = fr;
2594				passt = pass;
2595			}
2596			pass = passt;
2597		}
2598
2599		if (pass & FR_QUICK) {
2600			/*
2601			 * Finally, if we've asked to track state for this
2602			 * packet, set it up.  Add state for "quick" rules
2603			 * here so that if the action fails we can consider
2604			 * the rule to "not match" and keep on processing
2605			 * filter rules.
2606			 */
2607			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2608			    !(fin->fin_flx & FI_STATE)) {
2609				int out = fin->fin_out;
2610
2611				fin->fin_fr = fr;
2612				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2613					LBUMPD(ipf_stats[out], fr_ads);
2614				} else {
2615					LBUMPD(ipf_stats[out], fr_bads);
2616					pass = passo;
2617					continue;
2618				}
2619			}
2620			break;
2621		}
2622	}
2623	fin->fin_depth--;
2624	return pass;
2625}
2626
2627
2628/* ------------------------------------------------------------------------ */
2629/* Function:    ipf_acctpkt                                                 */
2630/* Returns:     frentry_t* - always returns NULL                            */
2631/* Parameters:  fin(I) - pointer to packet information                      */
2632/*              passp(IO) - pointer to current/new filter decision (unused) */
2633/*                                                                          */
2634/* Checks a packet against accounting rules, if there are any for the given */
2635/* IP protocol version.                                                     */
2636/*                                                                          */
2637/* N.B.: this function returns NULL to match the prototype used by other    */
2638/* functions called from the IPFilter "mainline" in ipf_check().            */
2639/* ------------------------------------------------------------------------ */
2640frentry_t *
2641ipf_acctpkt(fin, passp)
2642	fr_info_t *fin;
2643	u_32_t *passp;
2644{
2645	ipf_main_softc_t *softc = fin->fin_main_soft;
2646	char group[FR_GROUPLEN];
2647	frentry_t *fr, *frsave;
2648	u_32_t pass, rulen;
2649
2650	passp = passp;
2651	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2652
2653	if (fr != NULL) {
2654		frsave = fin->fin_fr;
2655		bcopy(fin->fin_group, group, FR_GROUPLEN);
2656		rulen = fin->fin_rule;
2657		fin->fin_fr = fr;
2658		pass = ipf_scanlist(fin, FR_NOMATCH);
2659		if (FR_ISACCOUNT(pass)) {
2660			LBUMPD(ipf_stats[0], fr_acct);
2661		}
2662		fin->fin_fr = frsave;
2663		bcopy(group, fin->fin_group, FR_GROUPLEN);
2664		fin->fin_rule = rulen;
2665	}
2666	return NULL;
2667}
2668
2669
2670/* ------------------------------------------------------------------------ */
2671/* Function:    ipf_firewall                                                */
2672/* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2673/*                           were found, returns NULL.                      */
2674/* Parameters:  fin(I) - pointer to packet information                      */
2675/*              passp(IO) - pointer to current/new filter decision (unused) */
2676/*                                                                          */
2677/* Applies an appropriate set of firewall rules to the packet, to see if    */
2678/* there are any matches.  The first check is to see if a match can be seen */
2679/* in the cache.  If not, then search an appropriate list of rules.  Once a */
2680/* matching rule is found, take any appropriate actions as defined by the   */
2681/* rule - except logging.                                                   */
2682/* ------------------------------------------------------------------------ */
2683static frentry_t *
2684ipf_firewall(fin, passp)
2685	fr_info_t *fin;
2686	u_32_t *passp;
2687{
2688	ipf_main_softc_t *softc = fin->fin_main_soft;
2689	frentry_t *fr;
2690	u_32_t pass;
2691	int out;
2692
2693	out = fin->fin_out;
2694	pass = *passp;
2695
2696	/*
2697	 * This rule cache will only affect packets that are not being
2698	 * statefully filtered.
2699	 */
2700	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2701	if (fin->fin_fr != NULL)
2702		pass = ipf_scanlist(fin, softc->ipf_pass);
2703
2704	if ((pass & FR_NOMATCH)) {
2705		LBUMPD(ipf_stats[out], fr_nom);
2706	}
2707	fr = fin->fin_fr;
2708
2709	/*
2710	 * Apply packets per second rate-limiting to a rule as required.
2711	 */
2712	if ((fr != NULL) && (fr->fr_pps != 0) &&
2713	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2714		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2715		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2716		pass |= FR_BLOCK;
2717		LBUMPD(ipf_stats[out], fr_ppshit);
2718		fin->fin_reason = FRB_PPSRATE;
2719	}
2720
2721	/*
2722	 * If we fail to add a packet to the authorization queue, then we
2723	 * drop the packet later.  However, if it was added then pretend
2724	 * we've dropped it already.
2725	 */
2726	if (FR_ISAUTH(pass)) {
2727		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2728			DT1(frb_authnew, fr_info_t *, fin);
2729			fin->fin_m = *fin->fin_mp = NULL;
2730			fin->fin_reason = FRB_AUTHNEW;
2731			fin->fin_error = 0;
2732		} else {
2733			IPFERROR(1);
2734			fin->fin_error = ENOSPC;
2735		}
2736	}
2737
2738	if ((fr != NULL) && (fr->fr_func != NULL) &&
2739	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2740		(void) (*fr->fr_func)(fin, &pass);
2741
2742	/*
2743	 * If a rule is a pre-auth rule, check again in the list of rules
2744	 * loaded for authenticated use.  It does not particulary matter
2745	 * if this search fails because a "preauth" result, from a rule,
2746	 * is treated as "not a pass", hence the packet is blocked.
2747	 */
2748	if (FR_ISPREAUTH(pass)) {
2749		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2750	}
2751
2752	/*
2753	 * If the rule has "keep frag" and the packet is actually a fragment,
2754	 * then create a fragment state entry.
2755	 */
2756	if (pass & FR_KEEPFRAG) {
2757		if (fin->fin_flx & FI_FRAG) {
2758			if (ipf_frag_new(softc, fin, pass) == -1) {
2759				LBUMP(ipf_stats[out].fr_bnfr);
2760			} else {
2761				LBUMP(ipf_stats[out].fr_nfr);
2762			}
2763		} else {
2764			LBUMP(ipf_stats[out].fr_cfr);
2765		}
2766	}
2767
2768	fr = fin->fin_fr;
2769	*passp = pass;
2770
2771	return fr;
2772}
2773
2774
2775/* ------------------------------------------------------------------------ */
2776/* Function:    ipf_check                                                   */
2777/* Returns:     int -  0 == packet allowed through,                         */
2778/*              User space:                                                 */
2779/*                    -1 == packet blocked                                  */
2780/*                     1 == packet not matched                              */
2781/*                    -2 == requires authentication                         */
2782/*              Kernel:                                                     */
2783/*                   > 0 == filter error # for packet                       */
2784/* Parameters: ctx(I)  - pointer to the instance context                    */
2785/*             ip(I)   - pointer to start of IPv4/6 packet                  */
2786/*             hlen(I) - length of header                                   */
2787/*             ifp(I)  - pointer to interface this packet is on             */
2788/*             out(I)  - 0 == packet going in, 1 == packet going out        */
2789/*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2790/*                       IP packet.                                         */
2791/* Solaris:                                                                 */
2792/*             qpi(I)  - pointer to STREAMS queue information for this      */
2793/*                       interface & direction.                             */
2794/*                                                                          */
2795/* ipf_check() is the master function for all IPFilter packet processing.   */
2796/* It orchestrates: Network Address Translation (NAT), checking for packet  */
2797/* authorisation (or pre-authorisation), presence of related state info.,   */
2798/* generating log entries, IP packet accounting, routing of packets as      */
2799/* directed by firewall rules and of course whether or not to allow the     */
2800/* packet to be further processed by the kernel.                            */
2801/*                                                                          */
2802/* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2803/* freed.  Packets passed may be returned with the pointer pointed to by    */
2804/* by "mp" changed to a new buffer.                                         */
2805/* ------------------------------------------------------------------------ */
2806int
2807ipf_check(ctx, ip, hlen, ifp, out
2808#if defined(_KERNEL) && defined(MENTAT)
2809	, qif, mp)
2810	void *qif;
2811#else
2812	, mp)
2813#endif
2814	mb_t **mp;
2815	ip_t *ip;
2816	int hlen;
2817	struct ifnet *ifp;
2818	int out;
2819	void *ctx;
2820{
2821	/*
2822	 * The above really sucks, but short of writing a diff
2823	 */
2824	ipf_main_softc_t *softc = ctx;
2825	fr_info_t frinfo;
2826	fr_info_t *fin = &frinfo;
2827	u_32_t pass = softc->ipf_pass;
2828	frentry_t *fr = NULL;
2829	int v = IP_V(ip);
2830	mb_t *mc = NULL;
2831	mb_t *m;
2832	/*
2833	 * The first part of ipf_check() deals with making sure that what goes
2834	 * into the filtering engine makes some sense.  Information about the
2835	 * the packet is distilled, collected into a fr_info_t structure and
2836	 * the an attempt to ensure the buffer the packet is in is big enough
2837	 * to hold all the required packet headers.
2838	 */
2839#ifdef	_KERNEL
2840# ifdef MENTAT
2841	qpktinfo_t *qpi = qif;
2842
2843#  ifdef __sparc
2844	if ((u_int)ip & 0x3)
2845		return 2;
2846#  endif
2847# else
2848	SPL_INT(s);
2849# endif
2850
2851	if (softc->ipf_running <= 0) {
2852		return 0;
2853	}
2854
2855	bzero((char *)fin, sizeof(*fin));
2856
2857# ifdef MENTAT
2858	if (qpi->qpi_flags & QF_BROADCAST)
2859		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2860	if (qpi->qpi_flags & QF_MULTICAST)
2861		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2862	m = qpi->qpi_m;
2863	fin->fin_qfm = m;
2864	fin->fin_qpi = qpi;
2865# else /* MENTAT */
2866
2867	m = *mp;
2868
2869#  if defined(M_MCAST)
2870	if ((m->m_flags & M_MCAST) != 0)
2871		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2872#  endif
2873#  if defined(M_MLOOP)
2874	if ((m->m_flags & M_MLOOP) != 0)
2875		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2876#  endif
2877#  if defined(M_BCAST)
2878	if ((m->m_flags & M_BCAST) != 0)
2879		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2880#  endif
2881#  ifdef M_CANFASTFWD
2882	/*
2883	 * XXX For now, IP Filter and fast-forwarding of cached flows
2884	 * XXX are mutually exclusive.  Eventually, IP Filter should
2885	 * XXX get a "can-fast-forward" filter rule.
2886	 */
2887	m->m_flags &= ~M_CANFASTFWD;
2888#  endif /* M_CANFASTFWD */
2889#  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2890	/*
2891	 * disable delayed checksums.
2892	 */
2893	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2894		in_delayed_cksum(m);
2895		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2896	}
2897#  endif /* CSUM_DELAY_DATA */
2898# endif /* MENTAT */
2899#else
2900	bzero((char *)fin, sizeof(*fin));
2901	m = *mp;
2902# if defined(M_MCAST)
2903	if ((m->m_flags & M_MCAST) != 0)
2904		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2905# endif
2906# if defined(M_MLOOP)
2907	if ((m->m_flags & M_MLOOP) != 0)
2908		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2909# endif
2910# if defined(M_BCAST)
2911	if ((m->m_flags & M_BCAST) != 0)
2912		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2913# endif
2914#endif /* _KERNEL */
2915
2916	fin->fin_v = v;
2917	fin->fin_m = m;
2918	fin->fin_ip = ip;
2919	fin->fin_mp = mp;
2920	fin->fin_out = out;
2921	fin->fin_ifp = ifp;
2922	fin->fin_error = ENETUNREACH;
2923	fin->fin_hlen = (u_short)hlen;
2924	fin->fin_dp = (char *)ip + hlen;
2925	fin->fin_main_soft = softc;
2926
2927	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2928
2929	SPL_NET(s);
2930
2931#ifdef	USE_INET6
2932	if (v == 6) {
2933		LBUMP(ipf_stats[out].fr_ipv6);
2934		/*
2935		 * Jumbo grams are quite likely too big for internal buffer
2936		 * structures to handle comfortably, for now, so just drop
2937		 * them.
2938		 */
2939		if (((ip6_t *)ip)->ip6_plen == 0) {
2940			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2941			pass = FR_BLOCK|FR_NOMATCH;
2942			fin->fin_reason = FRB_JUMBO;
2943			goto finished;
2944		}
2945		fin->fin_family = AF_INET6;
2946	} else
2947#endif
2948	{
2949		fin->fin_family = AF_INET;
2950	}
2951
2952	if (ipf_makefrip(hlen, ip, fin) == -1) {
2953		DT1(frb_makefrip, fr_info_t *, fin);
2954		pass = FR_BLOCK|FR_NOMATCH;
2955		fin->fin_reason = FRB_MAKEFRIP;
2956		goto finished;
2957	}
2958
2959	/*
2960	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2961	 * becomes NULL and so we have no packet to free.
2962	 */
2963	if (*fin->fin_mp == NULL)
2964		goto finished;
2965
2966	if (!out) {
2967		if (v == 4) {
2968			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2969				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2970				fin->fin_flx |= FI_BADSRC;
2971			}
2972			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2973				LBUMPD(ipf_stats[0], fr_v4_badttl);
2974				fin->fin_flx |= FI_LOWTTL;
2975			}
2976		}
2977#ifdef USE_INET6
2978		else  if (v == 6) {
2979			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2980				LBUMPD(ipf_stats[0], fr_v6_badttl);
2981				fin->fin_flx |= FI_LOWTTL;
2982			}
2983		}
2984#endif
2985	}
2986
2987	if (fin->fin_flx & FI_SHORT) {
2988		LBUMPD(ipf_stats[out], fr_short);
2989	}
2990
2991	READ_ENTER(&softc->ipf_mutex);
2992
2993	if (!out) {
2994		switch (fin->fin_v)
2995		{
2996		case 4 :
2997			if (ipf_nat_checkin(fin, &pass) == -1) {
2998				goto filterdone;
2999			}
3000			break;
3001#ifdef USE_INET6
3002		case 6 :
3003			if (ipf_nat6_checkin(fin, &pass) == -1) {
3004				goto filterdone;
3005			}
3006			break;
3007#endif
3008		default :
3009			break;
3010		}
3011	}
3012	/*
3013	 * Check auth now.
3014	 * If a packet is found in the auth table, then skip checking
3015	 * the access lists for permission but we do need to consider
3016	 * the result as if it were from the ACL's.  In addition, being
3017	 * found in the auth table means it has been seen before, so do
3018	 * not pass it through accounting (again), lest it be counted twice.
3019	 */
3020	fr = ipf_auth_check(fin, &pass);
3021	if (!out && (fr == NULL))
3022		(void) ipf_acctpkt(fin, NULL);
3023
3024	if (fr == NULL) {
3025		if ((fin->fin_flx & FI_FRAG) != 0)
3026			fr = ipf_frag_known(fin, &pass);
3027
3028		if (fr == NULL)
3029			fr = ipf_state_check(fin, &pass);
3030	}
3031
3032	if ((pass & FR_NOMATCH) || (fr == NULL))
3033		fr = ipf_firewall(fin, &pass);
3034
3035	/*
3036	 * If we've asked to track state for this packet, set it up.
3037	 * Here rather than ipf_firewall because ipf_checkauth may decide
3038	 * to return a packet for "keep state"
3039	 */
3040	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3041	    !(fin->fin_flx & FI_STATE)) {
3042		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3043			LBUMP(ipf_stats[out].fr_ads);
3044		} else {
3045			LBUMP(ipf_stats[out].fr_bads);
3046			if (FR_ISPASS(pass)) {
3047				DT(frb_stateadd);
3048				pass &= ~FR_CMDMASK;
3049				pass |= FR_BLOCK;
3050				fin->fin_reason = FRB_STATEADD;
3051			}
3052		}
3053	}
3054
3055	fin->fin_fr = fr;
3056	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3057		fin->fin_dif = &fr->fr_dif;
3058		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3059	}
3060
3061	/*
3062	 * Only count/translate packets which will be passed on, out the
3063	 * interface.
3064	 */
3065	if (out && FR_ISPASS(pass)) {
3066		(void) ipf_acctpkt(fin, NULL);
3067
3068		switch (fin->fin_v)
3069		{
3070		case 4 :
3071			if (ipf_nat_checkout(fin, &pass) == -1) {
3072				;
3073			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3074				if (ipf_updateipid(fin) == -1) {
3075					DT(frb_updateipid);
3076					LBUMP(ipf_stats[1].fr_ipud);
3077					pass &= ~FR_CMDMASK;
3078					pass |= FR_BLOCK;
3079					fin->fin_reason = FRB_UPDATEIPID;
3080				} else {
3081					LBUMP(ipf_stats[0].fr_ipud);
3082				}
3083			}
3084			break;
3085#ifdef USE_INET6
3086		case 6 :
3087			(void) ipf_nat6_checkout(fin, &pass);
3088			break;
3089#endif
3090		default :
3091			break;
3092		}
3093	}
3094
3095filterdone:
3096#ifdef	IPFILTER_LOG
3097	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3098		(void) ipf_dolog(fin, &pass);
3099	}
3100#endif
3101
3102	/*
3103	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3104	 * will work when called from inside of fr_fastroute.  Although
3105	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3106	 * impact on code execution.
3107	 */
3108	fin->fin_flx &= ~FI_STATE;
3109
3110#if defined(FASTROUTE_RECURSION)
3111	/*
3112	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3113	 * a packet below can sometimes cause a recursive call into IPFilter.
3114	 * On those platforms where that does happen, we need to hang onto
3115	 * the filter rule just in case someone decides to remove or flush it
3116	 * in the meantime.
3117	 */
3118	if (fr != NULL) {
3119		MUTEX_ENTER(&fr->fr_lock);
3120		fr->fr_ref++;
3121		MUTEX_EXIT(&fr->fr_lock);
3122	}
3123
3124	RWLOCK_EXIT(&softc->ipf_mutex);
3125#endif
3126
3127	if ((pass & FR_RETMASK) != 0) {
3128		/*
3129		 * Should we return an ICMP packet to indicate error
3130		 * status passing through the packet filter ?
3131		 * WARNING: ICMP error packets AND TCP RST packets should
3132		 * ONLY be sent in repsonse to incoming packets.  Sending
3133		 * them in response to outbound packets can result in a
3134		 * panic on some operating systems.
3135		 */
3136		if (!out) {
3137			if (pass & FR_RETICMP) {
3138				int dst;
3139
3140				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3141					dst = 1;
3142				else
3143					dst = 0;
3144				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3145							 dst);
3146				LBUMP(ipf_stats[0].fr_ret);
3147			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3148				   !(fin->fin_flx & FI_SHORT)) {
3149				if (((fin->fin_flx & FI_OOW) != 0) ||
3150				    (ipf_send_reset(fin) == 0)) {
3151					LBUMP(ipf_stats[1].fr_ret);
3152				}
3153			}
3154
3155			/*
3156			 * When using return-* with auth rules, the auth code
3157			 * takes over disposing of this packet.
3158			 */
3159			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3160				DT1(frb_authcapture, fr_info_t *, fin);
3161				fin->fin_m = *fin->fin_mp = NULL;
3162				fin->fin_reason = FRB_AUTHCAPTURE;
3163				m = NULL;
3164			}
3165		} else {
3166			if (pass & FR_RETRST) {
3167				fin->fin_error = ECONNRESET;
3168			}
3169		}
3170	}
3171
3172	/*
3173	 * After the above so that ICMP unreachables and TCP RSTs get
3174	 * created properly.
3175	 */
3176	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3177		ipf_nat_uncreate(fin);
3178
3179	/*
3180	 * If we didn't drop off the bottom of the list of rules (and thus
3181	 * the 'current' rule fr is not NULL), then we may have some extra
3182	 * instructions about what to do with a packet.
3183	 * Once we're finished return to our caller, freeing the packet if
3184	 * we are dropping it.
3185	 */
3186	if (fr != NULL) {
3187		frdest_t *fdp;
3188
3189		/*
3190		 * Generate a duplicated packet first because ipf_fastroute
3191		 * can lead to fin_m being free'd... not good.
3192		 */
3193		fdp = fin->fin_dif;
3194		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3195		    (fdp->fd_ptr != (void *)-1)) {
3196			mc = M_COPY(fin->fin_m);
3197			if (mc != NULL)
3198				ipf_fastroute(mc, &mc, fin, fdp);
3199		}
3200
3201		fdp = fin->fin_tif;
3202		if (!out && (pass & FR_FASTROUTE)) {
3203			/*
3204			 * For fastroute rule, no destination interface defined
3205			 * so pass NULL as the frdest_t parameter
3206			 */
3207			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3208			m = *mp = NULL;
3209		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3210			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3211			/* this is for to rules: */
3212			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3213			m = *mp = NULL;
3214		}
3215
3216#if defined(FASTROUTE_RECURSION)
3217		(void) ipf_derefrule(softc, &fr);
3218#endif
3219	}
3220#if !defined(FASTROUTE_RECURSION)
3221	RWLOCK_EXIT(&softc->ipf_mutex);
3222#endif
3223
3224finished:
3225	if (!FR_ISPASS(pass)) {
3226		LBUMP(ipf_stats[out].fr_block);
3227		if (*mp != NULL) {
3228#ifdef _KERNEL
3229			FREE_MB_T(*mp);
3230#endif
3231			m = *mp = NULL;
3232		}
3233	} else {
3234		LBUMP(ipf_stats[out].fr_pass);
3235	}
3236
3237	SPL_X(s);
3238
3239#ifdef _KERNEL
3240	if (FR_ISPASS(pass))
3241		return 0;
3242	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3243	return fin->fin_error;
3244#else /* _KERNEL */
3245	if (*mp != NULL)
3246		(*mp)->mb_ifp = fin->fin_ifp;
3247	blockreason = fin->fin_reason;
3248	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3249	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3250		if ((pass & FR_NOMATCH) != 0)
3251			return 1;
3252
3253	if ((pass & FR_RETMASK) != 0)
3254		switch (pass & FR_RETMASK)
3255		{
3256		case FR_RETRST :
3257			return 3;
3258		case FR_RETICMP :
3259			return 4;
3260		case FR_FAKEICMP :
3261			return 5;
3262		}
3263
3264	switch (pass & FR_CMDMASK)
3265	{
3266	case FR_PASS :
3267		return 0;
3268	case FR_BLOCK :
3269		return -1;
3270	case FR_AUTH :
3271		return -2;
3272	case FR_ACCOUNT :
3273		return -3;
3274	case FR_PREAUTH :
3275		return -4;
3276	}
3277	return 2;
3278#endif /* _KERNEL */
3279}
3280
3281
3282#ifdef	IPFILTER_LOG
3283/* ------------------------------------------------------------------------ */
3284/* Function:    ipf_dolog                                                   */
3285/* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3286/* Parameters:  fin(I) - pointer to packet information                      */
3287/*              passp(IO) - pointer to current/new filter decision (unused) */
3288/*                                                                          */
3289/* Checks flags set to see how a packet should be logged, if it is to be    */
3290/* logged.  Adjust statistics based on its success or not.                  */
3291/* ------------------------------------------------------------------------ */
3292frentry_t *
3293ipf_dolog(fin, passp)
3294	fr_info_t *fin;
3295	u_32_t *passp;
3296{
3297	ipf_main_softc_t *softc = fin->fin_main_soft;
3298	u_32_t pass;
3299	int out;
3300
3301	out = fin->fin_out;
3302	pass = *passp;
3303
3304	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3305		pass |= FF_LOGNOMATCH;
3306		LBUMPD(ipf_stats[out], fr_npkl);
3307		goto logit;
3308
3309	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3310	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3311		if ((pass & FR_LOGMASK) != FR_LOGP)
3312			pass |= FF_LOGPASS;
3313		LBUMPD(ipf_stats[out], fr_ppkl);
3314		goto logit;
3315
3316	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3317		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3318		if ((pass & FR_LOGMASK) != FR_LOGB)
3319			pass |= FF_LOGBLOCK;
3320		LBUMPD(ipf_stats[out], fr_bpkl);
3321
3322logit:
3323		if (ipf_log_pkt(fin, pass) == -1) {
3324			/*
3325			 * If the "or-block" option has been used then
3326			 * block the packet if we failed to log it.
3327			 */
3328			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3329				DT1(frb_logfail2, u_int, pass);
3330				pass &= ~FR_CMDMASK;
3331				pass |= FR_BLOCK;
3332				fin->fin_reason = FRB_LOGFAIL2;
3333			}
3334		}
3335		*passp = pass;
3336	}
3337
3338	return fin->fin_fr;
3339}
3340#endif /* IPFILTER_LOG */
3341
3342
3343/* ------------------------------------------------------------------------ */
3344/* Function:    ipf_cksum                                                   */
3345/* Returns:     u_short - IP header checksum                                */
3346/* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3347/*              len(I)  - length of buffer in bytes                         */
3348/*                                                                          */
3349/* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3350/*                                                                          */
3351/* N.B.: addr should be 16bit aligned.                                      */
3352/* ------------------------------------------------------------------------ */
3353u_short
3354ipf_cksum(addr, len)
3355	u_short *addr;
3356	int len;
3357{
3358	u_32_t sum = 0;
3359
3360	for (sum = 0; len > 1; len -= 2)
3361		sum += *addr++;
3362
3363	/* mop up an odd byte, if necessary */
3364	if (len == 1)
3365		sum += *(u_char *)addr;
3366
3367	/*
3368	 * add back carry outs from top 16 bits to low 16 bits
3369	 */
3370	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3371	sum += (sum >> 16);			/* add carry */
3372	return (u_short)(~sum);
3373}
3374
3375
3376/* ------------------------------------------------------------------------ */
3377/* Function:    fr_cksum                                                    */
3378/* Returns:     u_short - layer 4 checksum                                  */
3379/* Parameters:  fin(I)     - pointer to packet information                  */
3380/*              ip(I)      - pointer to IP header                           */
3381/*              l4proto(I) - protocol to caclulate checksum for             */
3382/*              l4hdr(I)   - pointer to layer 4 header                      */
3383/*                                                                          */
3384/* Calculates the TCP checksum for the packet held in "m", using the data   */
3385/* in the IP header "ip" to seed it.                                        */
3386/*                                                                          */
3387/* NB: This function assumes we've pullup'd enough for all of the IP header */
3388/* and the TCP header.  We also assume that data blocks aren't allocated in */
3389/* odd sizes.                                                               */
3390/*                                                                          */
3391/* Expects ip_len and ip_off to be in network byte order when called.       */
3392/* ------------------------------------------------------------------------ */
3393u_short
3394fr_cksum(fin, ip, l4proto, l4hdr)
3395	fr_info_t *fin;
3396	ip_t *ip;
3397	int l4proto;
3398	void *l4hdr;
3399{
3400	u_short *sp, slen, sumsave, *csump;
3401	u_int sum, sum2;
3402	int hlen;
3403	int off;
3404#ifdef	USE_INET6
3405	ip6_t *ip6;
3406#endif
3407
3408	csump = NULL;
3409	sumsave = 0;
3410	sp = NULL;
3411	slen = 0;
3412	hlen = 0;
3413	sum = 0;
3414
3415	sum = htons((u_short)l4proto);
3416	/*
3417	 * Add up IP Header portion
3418	 */
3419#ifdef	USE_INET6
3420	if (IP_V(ip) == 4) {
3421#endif
3422		hlen = IP_HL(ip) << 2;
3423		off = hlen;
3424		sp = (u_short *)&ip->ip_src;
3425		sum += *sp++;	/* ip_src */
3426		sum += *sp++;
3427		sum += *sp++;	/* ip_dst */
3428		sum += *sp++;
3429		slen = fin->fin_plen - off;
3430		sum += htons(slen);
3431#ifdef	USE_INET6
3432	} else if (IP_V(ip) == 6) {
3433		mb_t *m;
3434
3435		m = fin->fin_m;
3436		ip6 = (ip6_t *)ip;
3437		off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3438		int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3439		return(ipf_pcksum6(m, ip6, off, len));
3440	} else {
3441		return 0xffff;
3442	}
3443#endif
3444
3445	switch (l4proto)
3446	{
3447	case IPPROTO_UDP :
3448		csump = &((udphdr_t *)l4hdr)->uh_sum;
3449		break;
3450
3451	case IPPROTO_TCP :
3452		csump = &((tcphdr_t *)l4hdr)->th_sum;
3453		break;
3454	case IPPROTO_ICMP :
3455		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3456		sum = 0;	/* Pseudo-checksum is not included */
3457		break;
3458#ifdef USE_INET6
3459	case IPPROTO_ICMPV6 :
3460		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3461		break;
3462#endif
3463	default :
3464		break;
3465	}
3466
3467	if (csump != NULL) {
3468		sumsave = *csump;
3469		*csump = 0;
3470	}
3471
3472	sum2 = ipf_pcksum(fin, off, sum);
3473	if (csump != NULL)
3474		*csump = sumsave;
3475	return sum2;
3476}
3477
3478
3479/* ------------------------------------------------------------------------ */
3480/* Function:    ipf_findgroup                                               */
3481/* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3482/* Parameters:  softc(I) - pointer to soft context main structure           */
3483/*              group(I) - group name to search for                         */
3484/*              unit(I)  - device to which this group belongs               */
3485/*              set(I)   - which set of rules (inactive/inactive) this is   */
3486/*              fgpp(O)  - pointer to place to store pointer to the pointer */
3487/*                         to where to add the next (last) group or where   */
3488/*                         to delete group from.                            */
3489/*                                                                          */
3490/* Search amongst the defined groups for a particular group number.         */
3491/* ------------------------------------------------------------------------ */
3492frgroup_t *
3493ipf_findgroup(softc, group, unit, set, fgpp)
3494	ipf_main_softc_t *softc;
3495	char *group;
3496	minor_t unit;
3497	int set;
3498	frgroup_t ***fgpp;
3499{
3500	frgroup_t *fg, **fgp;
3501
3502	/*
3503	 * Which list of groups to search in is dependent on which list of
3504	 * rules are being operated on.
3505	 */
3506	fgp = &softc->ipf_groups[unit][set];
3507
3508	while ((fg = *fgp) != NULL) {
3509		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3510			break;
3511		else
3512			fgp = &fg->fg_next;
3513	}
3514	if (fgpp != NULL)
3515		*fgpp = fgp;
3516	return fg;
3517}
3518
3519
3520/* ------------------------------------------------------------------------ */
3521/* Function:    ipf_group_add                                               */
3522/* Returns:     frgroup_t * - NULL == did not create group,                 */
3523/*                            != NULL == pointer to the group               */
3524/* Parameters:  softc(I) - pointer to soft context main structure           */
3525/*              num(I)   - group number to add                              */
3526/*              head(I)  - rule pointer that is using this as the head      */
3527/*              flags(I) - rule flags which describe the type of rule it is */
3528/*              unit(I)  - device to which this group will belong to        */
3529/*              set(I)   - which set of rules (inactive/inactive) this is   */
3530/* Write Locks: ipf_mutex                                                   */
3531/*                                                                          */
3532/* Add a new group head, or if it already exists, increase the reference    */
3533/* count to it.                                                             */
3534/* ------------------------------------------------------------------------ */
3535frgroup_t *
3536ipf_group_add(softc, group, head, flags, unit, set)
3537	ipf_main_softc_t *softc;
3538	char *group;
3539	void *head;
3540	u_32_t flags;
3541	minor_t unit;
3542	int set;
3543{
3544	frgroup_t *fg, **fgp;
3545	u_32_t gflags;
3546
3547	if (group == NULL)
3548		return NULL;
3549
3550	if (unit == IPL_LOGIPF && *group == '\0')
3551		return NULL;
3552
3553	fgp = NULL;
3554	gflags = flags & FR_INOUT;
3555
3556	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3557	if (fg != NULL) {
3558		if (fg->fg_head == NULL && head != NULL)
3559			fg->fg_head = head;
3560		if (fg->fg_flags == 0)
3561			fg->fg_flags = gflags;
3562		else if (gflags != fg->fg_flags)
3563			return NULL;
3564		fg->fg_ref++;
3565		return fg;
3566	}
3567
3568	KMALLOC(fg, frgroup_t *);
3569	if (fg != NULL) {
3570		fg->fg_head = head;
3571		fg->fg_start = NULL;
3572		fg->fg_next = *fgp;
3573		bcopy(group, fg->fg_name, strlen(group) + 1);
3574		fg->fg_flags = gflags;
3575		fg->fg_ref = 1;
3576		fg->fg_set = &softc->ipf_groups[unit][set];
3577		*fgp = fg;
3578	}
3579	return fg;
3580}
3581
3582
3583/* ------------------------------------------------------------------------ */
3584/* Function:    ipf_group_del                                               */
3585/* Returns:     int      - number of rules deleted                          */
3586/* Parameters:  softc(I) - pointer to soft context main structure           */
3587/*              group(I) - group name to delete                             */
3588/*              fr(I)    - filter rule from which group is referenced       */
3589/* Write Locks: ipf_mutex                                                   */
3590/*                                                                          */
3591/* This function is called whenever a reference to a group is to be dropped */
3592/* and thus its reference count needs to be lowered and the group free'd if */
3593/* the reference count reaches zero. Passing in fr is really for the sole   */
3594/* purpose of knowing when the head rule is being deleted.                  */
3595/* ------------------------------------------------------------------------ */
3596void
3597ipf_group_del(softc, group, fr)
3598	ipf_main_softc_t *softc;
3599	frgroup_t *group;
3600	frentry_t *fr;
3601{
3602
3603	if (group->fg_head == fr)
3604		group->fg_head = NULL;
3605
3606	group->fg_ref--;
3607	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3608		ipf_group_free(group);
3609}
3610
3611
3612/* ------------------------------------------------------------------------ */
3613/* Function:    ipf_group_free                                              */
3614/* Returns:     Nil                                                         */
3615/* Parameters:  group(I) - pointer to filter rule group                     */
3616/*                                                                          */
3617/* Remove the group from the list of groups and free it.                    */
3618/* ------------------------------------------------------------------------ */
3619static void
3620ipf_group_free(group)
3621	frgroup_t *group;
3622{
3623	frgroup_t **gp;
3624
3625	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3626		if (*gp == group) {
3627			*gp = group->fg_next;
3628			break;
3629		}
3630	}
3631	KFREE(group);
3632}
3633
3634
3635/* ------------------------------------------------------------------------ */
3636/* Function:    ipf_group_flush                                             */
3637/* Returns:     int      - number of rules flush from group                 */
3638/* Parameters:  softc(I) - pointer to soft context main structure           */
3639/* Parameters:  group(I) - pointer to filter rule group                     */
3640/*                                                                          */
3641/* Remove all of the rules that currently are listed under the given group. */
3642/* ------------------------------------------------------------------------ */
3643static int
3644ipf_group_flush(softc, group)
3645	ipf_main_softc_t *softc;
3646	frgroup_t *group;
3647{
3648	int gone = 0;
3649
3650	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3651
3652	return gone;
3653}
3654
3655
3656/* ------------------------------------------------------------------------ */
3657/* Function:    ipf_getrulen                                                */
3658/* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3659/* Parameters:  softc(I) - pointer to soft context main structure           */
3660/* Parameters:  unit(I)  - device for which to count the rule's number      */
3661/*              flags(I) - which set of rules to find the rule in           */
3662/*              group(I) - group name                                       */
3663/*              n(I)     - rule number to find                              */
3664/*                                                                          */
3665/* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3666/* group # g doesn't exist or there are less than n rules in the group.     */
3667/* ------------------------------------------------------------------------ */
3668frentry_t *
3669ipf_getrulen(softc, unit, group, n)
3670	ipf_main_softc_t *softc;
3671	int unit;
3672	char *group;
3673	u_32_t n;
3674{
3675	frentry_t *fr;
3676	frgroup_t *fg;
3677
3678	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3679	if (fg == NULL)
3680		return NULL;
3681	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3682		;
3683	if (n != 0)
3684		return NULL;
3685	return fr;
3686}
3687
3688
3689/* ------------------------------------------------------------------------ */
3690/* Function:    ipf_flushlist                                               */
3691/* Returns:     int - >= 0 - number of flushed rules                        */
3692/* Parameters:  softc(I)   - pointer to soft context main structure         */
3693/*              nfreedp(O) - pointer to int where flush count is stored     */
3694/*              listp(I)   - pointer to list to flush pointer               */
3695/* Write Locks: ipf_mutex                                                   */
3696/*                                                                          */
3697/* Recursively flush rules from the list, descending groups as they are     */
3698/* encountered.  if a rule is the head of a group and it has lost all its   */
3699/* group members, then also delete the group reference.  nfreedp is needed  */
3700/* to store the accumulating count of rules removed, whereas the returned   */
3701/* value is just the number removed from the current list.  The latter is   */
3702/* needed to correctly adjust reference counts on rules that define groups. */
3703/*                                                                          */
3704/* NOTE: Rules not loaded from user space cannot be flushed.                */
3705/* ------------------------------------------------------------------------ */
3706static int
3707ipf_flushlist(softc, nfreedp, listp)
3708	ipf_main_softc_t *softc;
3709	int *nfreedp;
3710	frentry_t **listp;
3711{
3712	int freed = 0;
3713	frentry_t *fp;
3714
3715	while ((fp = *listp) != NULL) {
3716		if ((fp->fr_type & FR_T_BUILTIN) ||
3717		    !(fp->fr_flags & FR_COPIED)) {
3718			listp = &fp->fr_next;
3719			continue;
3720		}
3721		*listp = fp->fr_next;
3722		if (fp->fr_next != NULL)
3723			fp->fr_next->fr_pnext = fp->fr_pnext;
3724		fp->fr_pnext = NULL;
3725
3726		if (fp->fr_grphead != NULL) {
3727			freed += ipf_group_flush(softc, fp->fr_grphead);
3728			fp->fr_names[fp->fr_grhead] = '\0';
3729		}
3730
3731		if (fp->fr_icmpgrp != NULL) {
3732			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3733			fp->fr_names[fp->fr_icmphead] = '\0';
3734		}
3735
3736		if (fp->fr_srctrack.ht_max_nodes)
3737			ipf_rb_ht_flush(&fp->fr_srctrack);
3738
3739		fp->fr_next = NULL;
3740
3741		ASSERT(fp->fr_ref > 0);
3742		if (ipf_derefrule(softc, &fp) == 0)
3743			freed++;
3744	}
3745	*nfreedp += freed;
3746	return freed;
3747}
3748
3749
3750/* ------------------------------------------------------------------------ */
3751/* Function:    ipf_flush                                                   */
3752/* Returns:     int - >= 0 - number of flushed rules                        */
3753/* Parameters:  softc(I) - pointer to soft context main structure           */
3754/*              unit(I)  - device for which to flush rules                  */
3755/*              flags(I) - which set of rules to flush                      */
3756/*                                                                          */
3757/* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3758/* and IPv6) as defined by the value of flags.                              */
3759/* ------------------------------------------------------------------------ */
3760int
3761ipf_flush(softc, unit, flags)
3762	ipf_main_softc_t *softc;
3763	minor_t unit;
3764	int flags;
3765{
3766	int flushed = 0, set;
3767
3768	WRITE_ENTER(&softc->ipf_mutex);
3769
3770	set = softc->ipf_active;
3771	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3772		set = 1 - set;
3773
3774	if (flags & FR_OUTQUE) {
3775		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3776		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3777	}
3778	if (flags & FR_INQUE) {
3779		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3780		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3781	}
3782
3783	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3784				    flags & (FR_INQUE|FR_OUTQUE));
3785
3786	RWLOCK_EXIT(&softc->ipf_mutex);
3787
3788	if (unit == IPL_LOGIPF) {
3789		int tmp;
3790
3791		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3792		if (tmp >= 0)
3793			flushed += tmp;
3794	}
3795	return flushed;
3796}
3797
3798
3799/* ------------------------------------------------------------------------ */
3800/* Function:    ipf_flush_groups                                            */
3801/* Returns:     int - >= 0 - number of flushed rules                        */
3802/* Parameters:  softc(I)  - soft context pointerto work with                */
3803/*              grhead(I) - pointer to the start of the group list to flush */
3804/*              flags(I)  - which set of rules to flush                     */
3805/*                                                                          */
3806/* Walk through all of the groups under the given group head and remove all */
3807/* of those that match the flags passed in. The for loop here is bit more   */
3808/* complicated than usual because the removal of a rule with ipf_derefrule  */
3809/* may end up removing not only the structure pointed to by "fg" but also   */
3810/* what is fg_next and fg_next after that. So if a filter rule is actually  */
3811/* removed from the group then it is necessary to start again.              */
3812/* ------------------------------------------------------------------------ */
3813static int
3814ipf_flush_groups(softc, grhead, flags)
3815	ipf_main_softc_t *softc;
3816	frgroup_t **grhead;
3817	int flags;
3818{
3819	frentry_t *fr, **frp;
3820	frgroup_t *fg, **fgp;
3821	int flushed = 0;
3822	int removed = 0;
3823
3824	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3825		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3826			fg = fg->fg_next;
3827		if (fg == NULL)
3828			break;
3829		removed = 0;
3830		frp = &fg->fg_start;
3831		while ((removed == 0) && ((fr = *frp) != NULL)) {
3832			if ((fr->fr_flags & flags) == 0) {
3833				frp = &fr->fr_next;
3834			} else {
3835				if (fr->fr_next != NULL)
3836					fr->fr_next->fr_pnext = fr->fr_pnext;
3837				*frp = fr->fr_next;
3838				fr->fr_pnext = NULL;
3839				fr->fr_next = NULL;
3840				(void) ipf_derefrule(softc, &fr);
3841				flushed++;
3842				removed++;
3843			}
3844		}
3845		if (removed == 0)
3846			fgp = &fg->fg_next;
3847	}
3848	return flushed;
3849}
3850
3851
3852/* ------------------------------------------------------------------------ */
3853/* Function:    memstr                                                      */
3854/* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3855/* Parameters:  src(I)  - pointer to byte sequence to match                 */
3856/*              dst(I)  - pointer to byte sequence to search                */
3857/*              slen(I) - match length                                      */
3858/*              dlen(I) - length available to search in                     */
3859/*                                                                          */
3860/* Search dst for a sequence of bytes matching those at src and extend for  */
3861/* slen bytes.                                                              */
3862/* ------------------------------------------------------------------------ */
3863char *
3864memstr(src, dst, slen, dlen)
3865	const char *src;
3866	char *dst;
3867	size_t slen, dlen;
3868{
3869	char *s = NULL;
3870
3871	while (dlen >= slen) {
3872		if (bcmp(src, dst, slen) == 0) {
3873			s = dst;
3874			break;
3875		}
3876		dst++;
3877		dlen--;
3878	}
3879	return s;
3880}
3881/* ------------------------------------------------------------------------ */
3882/* Function:    ipf_fixskip                                                 */
3883/* Returns:     Nil                                                         */
3884/* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3885/*              rp(I)        - rule added/removed with skip in it.          */
3886/*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3887/*                             depending on whether a rule was just added   */
3888/*                             or removed.                                  */
3889/*                                                                          */
3890/* Adjust all the rules in a list which would have skip'd past the position */
3891/* where we are inserting to skip to the right place given the change.      */
3892/* ------------------------------------------------------------------------ */
3893void
3894ipf_fixskip(listp, rp, addremove)
3895	frentry_t **listp, *rp;
3896	int addremove;
3897{
3898	int rules, rn;
3899	frentry_t *fp;
3900
3901	rules = 0;
3902	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3903		rules++;
3904
3905	if (fp == NULL)
3906		return;
3907
3908	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3909		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3910			fp->fr_arg += addremove;
3911}
3912
3913
3914#ifdef	_KERNEL
3915/* ------------------------------------------------------------------------ */
3916/* Function:    count4bits                                                  */
3917/* Returns:     int - >= 0 - number of consecutive bits in input            */
3918/* Parameters:  ip(I) - 32bit IP address                                    */
3919/*                                                                          */
3920/* IPv4 ONLY                                                                */
3921/* count consecutive 1's in bit mask.  If the mask generated by counting    */
3922/* consecutive 1's is different to that passed, return -1, else return #    */
3923/* of bits.                                                                 */
3924/* ------------------------------------------------------------------------ */
3925int
3926count4bits(ip)
3927	u_32_t	ip;
3928{
3929	u_32_t	ipn;
3930	int	cnt = 0, i, j;
3931
3932	ip = ipn = ntohl(ip);
3933	for (i = 32; i; i--, ipn *= 2)
3934		if (ipn & 0x80000000)
3935			cnt++;
3936		else
3937			break;
3938	ipn = 0;
3939	for (i = 32, j = cnt; i; i--, j--) {
3940		ipn *= 2;
3941		if (j > 0)
3942			ipn++;
3943	}
3944	if (ipn == ip)
3945		return cnt;
3946	return -1;
3947}
3948
3949
3950/* ------------------------------------------------------------------------ */
3951/* Function:    count6bits                                                  */
3952/* Returns:     int - >= 0 - number of consecutive bits in input            */
3953/* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3954/*                                                                          */
3955/* IPv6 ONLY                                                                */
3956/* count consecutive 1's in bit mask.                                       */
3957/* ------------------------------------------------------------------------ */
3958# ifdef USE_INET6
3959int
3960count6bits(msk)
3961	u_32_t *msk;
3962{
3963	int i = 0, k;
3964	u_32_t j;
3965
3966	for (k = 3; k >= 0; k--)
3967		if (msk[k] == 0xffffffff)
3968			i += 32;
3969		else {
3970			for (j = msk[k]; j; j <<= 1)
3971				if (j & 0x80000000)
3972					i++;
3973		}
3974	return i;
3975}
3976# endif
3977#endif /* _KERNEL */
3978
3979
3980/* ------------------------------------------------------------------------ */
3981/* Function:    ipf_synclist                                                */
3982/* Returns:     int    - 0 = no failures, else indication of first failure  */
3983/* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3984/*              ifp(I) - interface pointer for limiting sync lookups        */
3985/* Write Locks: ipf_mutex                                                   */
3986/*                                                                          */
3987/* Walk through a list of filter rules and resolve any interface names into */
3988/* pointers.  Where dynamic addresses are used, also update the IP address  */
3989/* used in the rule.  The interface pointer is used to limit the lookups to */
3990/* a specific set of matching names if it is non-NULL.                      */
3991/* Errors can occur when resolving the destination name of to/dup-to fields */
3992/* when the name points to a pool and that pool doest not exist. If this    */
3993/* does happen then it is necessary to check if there are any lookup refs   */
3994/* that need to be dropped before returning with an error.                  */
3995/* ------------------------------------------------------------------------ */
3996static int
3997ipf_synclist(softc, fr, ifp)
3998	ipf_main_softc_t *softc;
3999	frentry_t *fr;
4000	void *ifp;
4001{
4002	frentry_t *frt, *start = fr;
4003	frdest_t *fdp;
4004	char *name;
4005	int error;
4006	void *ifa;
4007	int v, i;
4008
4009	error = 0;
4010
4011	for (; fr; fr = fr->fr_next) {
4012		if (fr->fr_family == AF_INET)
4013			v = 4;
4014		else if (fr->fr_family == AF_INET6)
4015			v = 6;
4016		else
4017			v = 0;
4018
4019		/*
4020		 * Lookup all the interface names that are part of the rule.
4021		 */
4022		for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
4023			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4024				continue;
4025			if (fr->fr_ifnames[i] == -1)
4026				continue;
4027			name = FR_NAME(fr, fr_ifnames[i]);
4028			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4029		}
4030
4031		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4032			if (fr->fr_satype != FRI_NORMAL &&
4033			    fr->fr_satype != FRI_LOOKUP) {
4034				ifa = ipf_resolvenic(softc, fr->fr_names +
4035						     fr->fr_sifpidx, v);
4036				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4037					    &fr->fr_src6, &fr->fr_smsk6);
4038			}
4039			if (fr->fr_datype != FRI_NORMAL &&
4040			    fr->fr_datype != FRI_LOOKUP) {
4041				ifa = ipf_resolvenic(softc, fr->fr_names +
4042						     fr->fr_sifpidx, v);
4043				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4044					    &fr->fr_dst6, &fr->fr_dmsk6);
4045			}
4046		}
4047
4048		fdp = &fr->fr_tifs[0];
4049		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4050			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4051			if (error != 0)
4052				goto unwind;
4053		}
4054
4055		fdp = &fr->fr_tifs[1];
4056		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4057			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4058			if (error != 0)
4059				goto unwind;
4060		}
4061
4062		fdp = &fr->fr_dif;
4063		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4064			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4065			if (error != 0)
4066				goto unwind;
4067		}
4068
4069		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4070		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4071			fr->fr_srcptr = ipf_lookup_res_num(softc,
4072							   fr->fr_srctype,
4073							   IPL_LOGIPF,
4074							   fr->fr_srcnum,
4075							   &fr->fr_srcfunc);
4076		}
4077		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4078		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4079			fr->fr_dstptr = ipf_lookup_res_num(softc,
4080							   fr->fr_dsttype,
4081							   IPL_LOGIPF,
4082							   fr->fr_dstnum,
4083							   &fr->fr_dstfunc);
4084		}
4085	}
4086	return 0;
4087
4088unwind:
4089	for (frt = start; frt != fr; fr = fr->fr_next) {
4090		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4091		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4092				ipf_lookup_deref(softc, frt->fr_srctype,
4093						 frt->fr_srcptr);
4094		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4095		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4096				ipf_lookup_deref(softc, frt->fr_dsttype,
4097						 frt->fr_dstptr);
4098	}
4099	return error;
4100}
4101
4102
4103/* ------------------------------------------------------------------------ */
4104/* Function:    ipf_sync                                                    */
4105/* Returns:     void                                                        */
4106/* Parameters:  Nil                                                         */
4107/*                                                                          */
4108/* ipf_sync() is called when we suspect that the interface list or          */
4109/* information about interfaces (like IP#) has changed.  Go through all     */
4110/* filter rules, NAT entries and the state table and check if anything      */
4111/* needs to be changed/updated.                                             */
4112/* ------------------------------------------------------------------------ */
4113int
4114ipf_sync(softc, ifp)
4115	ipf_main_softc_t *softc;
4116	void *ifp;
4117{
4118	int i;
4119
4120# if !SOLARIS
4121	ipf_nat_sync(softc, ifp);
4122	ipf_state_sync(softc, ifp);
4123	ipf_lookup_sync(softc, ifp);
4124# endif
4125
4126	WRITE_ENTER(&softc->ipf_mutex);
4127	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4128	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4129	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4130	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4131
4132	for (i = 0; i < IPL_LOGSIZE; i++) {
4133		frgroup_t *g;
4134
4135		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4136			(void) ipf_synclist(softc, g->fg_start, ifp);
4137		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4138			(void) ipf_synclist(softc, g->fg_start, ifp);
4139	}
4140	RWLOCK_EXIT(&softc->ipf_mutex);
4141
4142	return 0;
4143}
4144
4145
4146/*
4147 * In the functions below, bcopy() is called because the pointer being
4148 * copied _from_ in this instance is a pointer to a char buf (which could
4149 * end up being unaligned) and on the kernel's local stack.
4150 */
4151/* ------------------------------------------------------------------------ */
4152/* Function:    copyinptr                                                   */
4153/* Returns:     int - 0 = success, else failure                             */
4154/* Parameters:  src(I)  - pointer to the source address                     */
4155/*              dst(I)  - destination address                               */
4156/*              size(I) - number of bytes to copy                           */
4157/*                                                                          */
4158/* Copy a block of data in from user space, given a pointer to the pointer  */
4159/* to start copying from (src) and a pointer to where to store it (dst).    */
4160/* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4161/* ------------------------------------------------------------------------ */
4162int
4163copyinptr(softc, src, dst, size)
4164	ipf_main_softc_t *softc;
4165	void *src, *dst;
4166	size_t size;
4167{
4168	caddr_t ca;
4169	int error;
4170
4171# if SOLARIS
4172	error = COPYIN(src, &ca, sizeof(ca));
4173	if (error != 0)
4174		return error;
4175# else
4176	bcopy(src, (caddr_t)&ca, sizeof(ca));
4177# endif
4178	error = COPYIN(ca, dst, size);
4179	if (error != 0) {
4180		IPFERROR(3);
4181		error = EFAULT;
4182	}
4183	return error;
4184}
4185
4186
4187/* ------------------------------------------------------------------------ */
4188/* Function:    copyoutptr                                                  */
4189/* Returns:     int - 0 = success, else failure                             */
4190/* Parameters:  src(I)  - pointer to the source address                     */
4191/*              dst(I)  - destination address                               */
4192/*              size(I) - number of bytes to copy                           */
4193/*                                                                          */
4194/* Copy a block of data out to user space, given a pointer to the pointer   */
4195/* to start copying from (src) and a pointer to where to store it (dst).    */
4196/* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4197/* ------------------------------------------------------------------------ */
4198int
4199copyoutptr(softc, src, dst, size)
4200	ipf_main_softc_t *softc;
4201	void *src, *dst;
4202	size_t size;
4203{
4204	caddr_t ca;
4205	int error;
4206
4207	bcopy(dst, (caddr_t)&ca, sizeof(ca));
4208	error = COPYOUT(src, ca, size);
4209	if (error != 0) {
4210		IPFERROR(4);
4211		error = EFAULT;
4212	}
4213	return error;
4214}
4215
4216
4217/* ------------------------------------------------------------------------ */
4218/* Function:    ipf_lock                                                    */
4219/* Returns:     int      - 0 = success, else error                          */
4220/* Parameters:  data(I)  - pointer to lock value to set                     */
4221/*              lockp(O) - pointer to location to store old lock value      */
4222/*                                                                          */
4223/* Get the new value for the lock integer, set it and return the old value  */
4224/* in *lockp.                                                               */
4225/* ------------------------------------------------------------------------ */
4226int
4227ipf_lock(data, lockp)
4228	caddr_t data;
4229	int *lockp;
4230{
4231	int arg, err;
4232
4233	err = BCOPYIN(data, &arg, sizeof(arg));
4234	if (err != 0)
4235		return EFAULT;
4236	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4237	if (err != 0)
4238		return EFAULT;
4239	*lockp = arg;
4240	return 0;
4241}
4242
4243
4244/* ------------------------------------------------------------------------ */
4245/* Function:    ipf_getstat                                                 */
4246/* Returns:     Nil                                                         */
4247/* Parameters:  softc(I) - pointer to soft context main structure           */
4248/*              fiop(I)  - pointer to ipfilter stats structure              */
4249/*              rev(I)   - version claim by program doing ioctl             */
4250/*                                                                          */
4251/* Stores a copy of current pointers, counters, etc, in the friostat        */
4252/* structure.                                                               */
4253/* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4254/* program is looking for. This ensure that validation of the version it    */
4255/* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4256/* allow older binaries to work but kernels without it will not.            */
4257/* ------------------------------------------------------------------------ */
4258/*ARGSUSED*/
4259static void
4260ipf_getstat(softc, fiop, rev)
4261	ipf_main_softc_t *softc;
4262	friostat_t *fiop;
4263	int rev;
4264{
4265	int i;
4266
4267	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4268	      sizeof(ipf_statistics_t) * 2);
4269	fiop->f_locks[IPL_LOGSTATE] = -1;
4270	fiop->f_locks[IPL_LOGNAT] = -1;
4271	fiop->f_locks[IPL_LOGIPF] = -1;
4272	fiop->f_locks[IPL_LOGAUTH] = -1;
4273
4274	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4275	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4276	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4277	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4278	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4279	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4280	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4281	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4282
4283	fiop->f_ticks = softc->ipf_ticks;
4284	fiop->f_active = softc->ipf_active;
4285	fiop->f_froute[0] = softc->ipf_frouteok[0];
4286	fiop->f_froute[1] = softc->ipf_frouteok[1];
4287	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4288	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4289
4290	fiop->f_running = softc->ipf_running;
4291	for (i = 0; i < IPL_LOGSIZE; i++) {
4292		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4293		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4294	}
4295#ifdef  IPFILTER_LOG
4296	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4297	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4298	fiop->f_logging = 1;
4299#else
4300	fiop->f_log_ok = 0;
4301	fiop->f_log_fail = 0;
4302	fiop->f_logging = 0;
4303#endif
4304	fiop->f_defpass = softc->ipf_pass;
4305	fiop->f_features = ipf_features;
4306
4307#ifdef IPFILTER_COMPAT
4308	sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4309		(rev / 1000000) % 100,
4310		(rev / 10000) % 100,
4311		(rev / 100) % 100);
4312#else
4313	rev = rev;
4314	(void) strncpy(fiop->f_version, ipfilter_version,
4315		       sizeof(fiop->f_version));
4316#endif
4317}
4318
4319
4320#ifdef	USE_INET6
4321int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4322	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4323	-1,			/* 1: UNUSED */
4324	-1,			/* 2: UNUSED */
4325	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4326	-1,			/* 4: ICMP_SOURCEQUENCH */
4327	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4328	-1,			/* 6: UNUSED */
4329	-1,			/* 7: UNUSED */
4330	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4331	-1,			/* 9: UNUSED */
4332	-1,			/* 10: UNUSED */
4333	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4334	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4335	-1,			/* 13: ICMP_TSTAMP */
4336	-1,			/* 14: ICMP_TSTAMPREPLY */
4337	-1,			/* 15: ICMP_IREQ */
4338	-1,			/* 16: ICMP_IREQREPLY */
4339	-1,			/* 17: ICMP_MASKREQ */
4340	-1,			/* 18: ICMP_MASKREPLY */
4341};
4342
4343
4344int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4345	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4346	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4347	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4348	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4349	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4350	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4351	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4352	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4353	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4354	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4355	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4356	-1,				/* 11: ICMP_UNREACH_TOSNET */
4357	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4358	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4359};
4360int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4361#endif
4362
4363int	icmpreplytype4[ICMP_MAXTYPE + 1];
4364
4365
4366/* ------------------------------------------------------------------------ */
4367/* Function:    ipf_matchicmpqueryreply                                     */
4368/* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4369/* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4370/*              ic(I)   - ICMP information                                  */
4371/*              icmp(I) - ICMP packet header                                */
4372/*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4373/*                                                                          */
4374/* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4375/* reply to one as described by what's in ic.  If it is a match, return 1,  */
4376/* else return 0 for no match.                                              */
4377/* ------------------------------------------------------------------------ */
4378int
4379ipf_matchicmpqueryreply(v, ic, icmp, rev)
4380	int v;
4381	icmpinfo_t *ic;
4382	icmphdr_t *icmp;
4383	int rev;
4384{
4385	int ictype;
4386
4387	ictype = ic->ici_type;
4388
4389	if (v == 4) {
4390		/*
4391		 * If we matched its type on the way in, then when going out
4392		 * it will still be the same type.
4393		 */
4394		if ((!rev && (icmp->icmp_type == ictype)) ||
4395		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4396			if (icmp->icmp_type != ICMP_ECHOREPLY)
4397				return 1;
4398			if (icmp->icmp_id == ic->ici_id)
4399				return 1;
4400		}
4401	}
4402#ifdef	USE_INET6
4403	else if (v == 6) {
4404		if ((!rev && (icmp->icmp_type == ictype)) ||
4405		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4406			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4407				return 1;
4408			if (icmp->icmp_id == ic->ici_id)
4409				return 1;
4410		}
4411	}
4412#endif
4413	return 0;
4414}
4415
4416
4417/*
4418 * IFNAMES are located in the variable length field starting at
4419 * frentry.fr_names. As pointers within the struct cannot be passed
4420 * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4421 * is unused (invalid). If it is used (valid) it is an offset to the
4422 * character string of an interface name or a comment. The following
4423 * macros will assist those who follow to understand the code.
4424 */
4425#define IPF_IFNAME_VALID(_a)	(_a != -1)
4426#define IPF_IFNAME_INVALID(_a)	(_a == -1)
4427#define IPF_IFNAMES_DIFFERENT(_a)	\
4428	!((IPF_IFNAME_INVALID(fr1->_a) &&	\
4429	IPF_IFNAME_INVALID(fr2->_a)) ||	\
4430	(IPF_IFNAME_VALID(fr1->_a) &&	\
4431	IPF_IFNAME_VALID(fr2->_a) &&	\
4432	!strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4433#define IPF_FRDEST_DIFFERENT(_a)	\
4434	(memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr,	\
4435	offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) ||	\
4436	IPF_IFNAMES_DIFFERENT(_a.fd_name))
4437
4438
4439/* ------------------------------------------------------------------------ */
4440/* Function:    ipf_rule_compare                                            */
4441/* Parameters:  fr1(I) - first rule structure to compare                    */
4442/*              fr2(I) - second rule structure to compare                   */
4443/* Returns:     int    - 0 == rules are the same, else mismatch             */
4444/*                                                                          */
4445/* Compare two rules and return 0 if they match or a number indicating      */
4446/* which of the individual checks failed.                                   */
4447/* ------------------------------------------------------------------------ */
4448static int
4449ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4450{
4451	int i;
4452
4453	if (fr1->fr_cksum != fr2->fr_cksum)
4454		return (1);
4455	if (fr1->fr_size != fr2->fr_size)
4456		return (2);
4457	if (fr1->fr_dsize != fr2->fr_dsize)
4458		return (3);
4459	if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4460	    != 0)
4461		return (4);
4462	/*
4463	 * XXX:	There is still a bug here as different rules with the
4464	 *	the same interfaces but in a different order will compare
4465	 *	differently. But since multiple interfaces in a rule doesn't
4466	 *	work anyway a simple straightforward compare is performed
4467	 *	here. Ultimately frentry_t creation will need to be
4468	 *	revisited in ipf_y.y. While the other issue, recognition
4469	 *	of only the first interface in a list of interfaces will
4470	 *	need to be separately addressed along with why only four.
4471	 */
4472	for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4473		/*
4474		 * XXX:	It's either the same index or uninitialized.
4475		 * 	We assume this because multiple interfaces
4476		 *	referenced by the same rule doesn't work anyway.
4477		 */
4478		if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4479			return(5);
4480	}
4481
4482	if (IPF_FRDEST_DIFFERENT(fr_tif))
4483		return (6);
4484	if (IPF_FRDEST_DIFFERENT(fr_rif))
4485		return (7);
4486	if (IPF_FRDEST_DIFFERENT(fr_dif))
4487		return (8);
4488	if (!fr1->fr_data && !fr2->fr_data)
4489		return (0);	/* move along, nothing to see here */
4490	if (fr1->fr_data && fr2->fr_data) {
4491		if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4492			return (0);	/* same */
4493	}
4494	return (9);
4495}
4496
4497
4498/* ------------------------------------------------------------------------ */
4499/* Function:    frrequest                                                   */
4500/* Returns:     int - 0 == success, > 0 == errno value                      */
4501/* Parameters:  unit(I)     - device for which this is for                  */
4502/*              req(I)      - ioctl command (SIOC*)                         */
4503/*              data(I)     - pointr to ioctl data                          */
4504/*              set(I)      - 1 or 0 (filter set)                           */
4505/*              makecopy(I) - flag indicating whether data points to a rule */
4506/*                            in kernel space & hence doesn't need copying. */
4507/*                                                                          */
4508/* This function handles all the requests which operate on the list of      */
4509/* filter rules.  This includes adding, deleting, insertion.  It is also    */
4510/* responsible for creating groups when a "head" rule is loaded.  Interface */
4511/* names are resolved here and other sanity checks are made on the content  */
4512/* of the rule structure being loaded.  If a rule has user defined timeouts */
4513/* then make sure they are created and initialised before exiting.          */
4514/* ------------------------------------------------------------------------ */
4515int
4516frrequest(softc, unit, req, data, set, makecopy)
4517	ipf_main_softc_t *softc;
4518	int unit;
4519	ioctlcmd_t req;
4520	int set, makecopy;
4521	caddr_t data;
4522{
4523	int error = 0, in, family, need_free = 0;
4524	enum {	OP_ADD,		/* add rule */
4525		OP_REM,		/* remove rule */
4526		OP_ZERO 	/* zero statistics and counters */ }
4527		addrem = OP_ADD;
4528	frentry_t frd, *fp, *f, **fprev, **ftail;
4529	void *ptr, *uptr, *cptr;
4530	u_int *p, *pp;
4531	frgroup_t *fg;
4532	char *group;
4533
4534	ptr = NULL;
4535	cptr = NULL;
4536	fg = NULL;
4537	fp = &frd;
4538	if (makecopy != 0) {
4539		bzero(fp, sizeof(frd));
4540		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4541		if (error) {
4542			return error;
4543		}
4544		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4545			IPFERROR(6);
4546			return EINVAL;
4547		}
4548		KMALLOCS(f, frentry_t *, fp->fr_size);
4549		if (f == NULL) {
4550			IPFERROR(131);
4551			return ENOMEM;
4552		}
4553		bzero(f, fp->fr_size);
4554		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4555				    fp->fr_size);
4556		if (error) {
4557			KFREES(f, fp->fr_size);
4558			return error;
4559		}
4560
4561		fp = f;
4562		f = NULL;
4563		fp->fr_next = NULL;
4564		fp->fr_dnext = NULL;
4565		fp->fr_pnext = NULL;
4566		fp->fr_pdnext = NULL;
4567		fp->fr_grp = NULL;
4568		fp->fr_grphead = NULL;
4569		fp->fr_icmpgrp = NULL;
4570		fp->fr_isc = (void *)-1;
4571		fp->fr_ptr = NULL;
4572		fp->fr_ref = 0;
4573		fp->fr_flags |= FR_COPIED;
4574	} else {
4575		fp = (frentry_t *)data;
4576		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4577			IPFERROR(7);
4578			return EINVAL;
4579		}
4580		fp->fr_flags &= ~FR_COPIED;
4581	}
4582
4583	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4584	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4585		IPFERROR(8);
4586		error = EINVAL;
4587		goto donenolock;
4588	}
4589
4590	family = fp->fr_family;
4591	uptr = fp->fr_data;
4592
4593	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4594	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4595		addrem = OP_ADD;	/* Add rule */
4596	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4597		addrem = OP_REM;		/* Remove rule */
4598	else if (req == (ioctlcmd_t)SIOCZRLST)
4599		addrem = OP_ZERO;	/* Zero statistics and counters */
4600	else {
4601		IPFERROR(9);
4602		error = EINVAL;
4603		goto donenolock;
4604	}
4605
4606	/*
4607	 * Only filter rules for IPv4 or IPv6 are accepted.
4608	 */
4609	if (family == AF_INET) {
4610		/*EMPTY*/;
4611#ifdef	USE_INET6
4612	} else if (family == AF_INET6) {
4613		/*EMPTY*/;
4614#endif
4615	} else if (family != 0) {
4616		IPFERROR(10);
4617		error = EINVAL;
4618		goto donenolock;
4619	}
4620
4621	/*
4622	 * If the rule is being loaded from user space, i.e. we had to copy it
4623	 * into kernel space, then do not trust the function pointer in the
4624	 * rule.
4625	 */
4626	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4627		if (ipf_findfunc(fp->fr_func) == NULL) {
4628			IPFERROR(11);
4629			error = ESRCH;
4630			goto donenolock;
4631		}
4632
4633		if (addrem == OP_ADD) {
4634			error = ipf_funcinit(softc, fp);
4635			if (error != 0)
4636				goto donenolock;
4637		}
4638	}
4639	if ((fp->fr_flags & FR_CALLNOW) &&
4640	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4641		IPFERROR(142);
4642		error = ESRCH;
4643		goto donenolock;
4644	}
4645	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4646	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4647		IPFERROR(143);
4648		error = ESRCH;
4649		goto donenolock;
4650	}
4651
4652	ptr = NULL;
4653	cptr = NULL;
4654
4655	if (FR_ISACCOUNT(fp->fr_flags))
4656		unit = IPL_LOGCOUNT;
4657
4658	/*
4659	 * Check that each group name in the rule has a start index that
4660	 * is valid.
4661	 */
4662	if (fp->fr_icmphead != -1) {
4663		if ((fp->fr_icmphead < 0) ||
4664		    (fp->fr_icmphead >= fp->fr_namelen)) {
4665			IPFERROR(136);
4666			error = EINVAL;
4667			goto donenolock;
4668		}
4669		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4670			fp->fr_names[fp->fr_icmphead] = '\0';
4671	}
4672
4673	if (fp->fr_grhead != -1) {
4674		if ((fp->fr_grhead < 0) ||
4675		    (fp->fr_grhead >= fp->fr_namelen)) {
4676			IPFERROR(137);
4677			error = EINVAL;
4678			goto donenolock;
4679		}
4680		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4681			fp->fr_names[fp->fr_grhead] = '\0';
4682	}
4683
4684	if (fp->fr_group != -1) {
4685		if ((fp->fr_group < 0) ||
4686		    (fp->fr_group >= fp->fr_namelen)) {
4687			IPFERROR(138);
4688			error = EINVAL;
4689			goto donenolock;
4690		}
4691		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4692			/*
4693			 * Allow loading rules that are in groups to cause
4694			 * them to be created if they don't already exit.
4695			 */
4696			group = FR_NAME(fp, fr_group);
4697			if (addrem == OP_ADD) {
4698				fg = ipf_group_add(softc, group, NULL,
4699						   fp->fr_flags, unit, set);
4700				fp->fr_grp = fg;
4701			} else {
4702				fg = ipf_findgroup(softc, group, unit,
4703						   set, NULL);
4704				if (fg == NULL) {
4705					IPFERROR(12);
4706					error = ESRCH;
4707					goto donenolock;
4708				}
4709			}
4710
4711			if (fg->fg_flags == 0) {
4712				fg->fg_flags = fp->fr_flags & FR_INOUT;
4713			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4714				IPFERROR(13);
4715				error = ESRCH;
4716				goto donenolock;
4717			}
4718		}
4719	} else {
4720		/*
4721		 * If a rule is going to be part of a group then it does
4722		 * not matter whether it is an in or out rule, but if it
4723		 * isn't in a group, then it does...
4724		 */
4725		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4726			IPFERROR(14);
4727			error = EINVAL;
4728			goto donenolock;
4729		}
4730	}
4731	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4732
4733	/*
4734	 * Work out which rule list this change is being applied to.
4735	 */
4736	ftail = NULL;
4737	fprev = NULL;
4738	if (unit == IPL_LOGAUTH) {
4739                if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4740		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4741		    (fp->fr_dif.fd_ptr != NULL) ||
4742		    (fp->fr_flags & FR_FASTROUTE)) {
4743			softc->ipf_interror = 145;
4744			error = EINVAL;
4745			goto donenolock;
4746		}
4747		fprev = ipf_auth_rulehead(softc);
4748	} else {
4749		if (FR_ISACCOUNT(fp->fr_flags))
4750			fprev = &softc->ipf_acct[in][set];
4751		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4752			fprev = &softc->ipf_rules[in][set];
4753	}
4754	if (fprev == NULL) {
4755		IPFERROR(15);
4756		error = ESRCH;
4757		goto donenolock;
4758	}
4759
4760	if (fg != NULL)
4761		fprev = &fg->fg_start;
4762
4763	/*
4764	 * Copy in extra data for the rule.
4765	 */
4766	if (fp->fr_dsize != 0) {
4767		if (makecopy != 0) {
4768			KMALLOCS(ptr, void *, fp->fr_dsize);
4769			if (ptr == NULL) {
4770				IPFERROR(16);
4771				error = ENOMEM;
4772				goto donenolock;
4773			}
4774
4775			/*
4776			 * The bcopy case is for when the data is appended
4777			 * to the rule by ipf_in_compat().
4778			 */
4779			if (uptr >= (void *)fp &&
4780			    uptr < (void *)((char *)fp + fp->fr_size)) {
4781				bcopy(uptr, ptr, fp->fr_dsize);
4782				error = 0;
4783			} else {
4784				error = COPYIN(uptr, ptr, fp->fr_dsize);
4785				if (error != 0) {
4786					IPFERROR(17);
4787					error = EFAULT;
4788					goto donenolock;
4789				}
4790			}
4791		} else {
4792			ptr = uptr;
4793		}
4794		fp->fr_data = ptr;
4795	} else {
4796		fp->fr_data = NULL;
4797	}
4798
4799	/*
4800	 * Perform per-rule type sanity checks of their members.
4801	 * All code after this needs to be aware that allocated memory
4802	 * may need to be free'd before exiting.
4803	 */
4804	switch (fp->fr_type & ~FR_T_BUILTIN)
4805	{
4806#if defined(IPFILTER_BPF)
4807	case FR_T_BPFOPC :
4808		if (fp->fr_dsize == 0) {
4809			IPFERROR(19);
4810			error = EINVAL;
4811			break;
4812		}
4813		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4814			IPFERROR(20);
4815			error = EINVAL;
4816			break;
4817		}
4818		break;
4819#endif
4820	case FR_T_IPF :
4821		/*
4822		 * Preparation for error case at the bottom of this function.
4823		 */
4824		if (fp->fr_datype == FRI_LOOKUP)
4825			fp->fr_dstptr = NULL;
4826		if (fp->fr_satype == FRI_LOOKUP)
4827			fp->fr_srcptr = NULL;
4828
4829		if (fp->fr_dsize != sizeof(fripf_t)) {
4830			IPFERROR(21);
4831			error = EINVAL;
4832			break;
4833		}
4834
4835		/*
4836		 * Allowing a rule with both "keep state" and "with oow" is
4837		 * pointless because adding a state entry to the table will
4838		 * fail with the out of window (oow) flag set.
4839		 */
4840		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4841			IPFERROR(22);
4842			error = EINVAL;
4843			break;
4844		}
4845
4846		switch (fp->fr_satype)
4847		{
4848		case FRI_BROADCAST :
4849		case FRI_DYNAMIC :
4850		case FRI_NETWORK :
4851		case FRI_NETMASKED :
4852		case FRI_PEERADDR :
4853			if (fp->fr_sifpidx < 0) {
4854				IPFERROR(23);
4855				error = EINVAL;
4856			}
4857			break;
4858		case FRI_LOOKUP :
4859			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4860						       &fp->fr_src6,
4861						       &fp->fr_smsk6);
4862			if (fp->fr_srcfunc == NULL) {
4863				IPFERROR(132);
4864				error = ESRCH;
4865				break;
4866			}
4867			break;
4868		case FRI_NORMAL :
4869			break;
4870		default :
4871			IPFERROR(133);
4872			error = EINVAL;
4873			break;
4874		}
4875		if (error != 0)
4876			break;
4877
4878		switch (fp->fr_datype)
4879		{
4880		case FRI_BROADCAST :
4881		case FRI_DYNAMIC :
4882		case FRI_NETWORK :
4883		case FRI_NETMASKED :
4884		case FRI_PEERADDR :
4885			if (fp->fr_difpidx < 0) {
4886				IPFERROR(24);
4887				error = EINVAL;
4888			}
4889			break;
4890		case FRI_LOOKUP :
4891			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4892						       &fp->fr_dst6,
4893						       &fp->fr_dmsk6);
4894			if (fp->fr_dstfunc == NULL) {
4895				IPFERROR(134);
4896				error = ESRCH;
4897			}
4898			break;
4899		case FRI_NORMAL :
4900			break;
4901		default :
4902			IPFERROR(135);
4903			error = EINVAL;
4904		}
4905		break;
4906
4907	case FR_T_NONE :
4908	case FR_T_CALLFUNC :
4909	case FR_T_COMPIPF :
4910		break;
4911
4912	case FR_T_IPFEXPR :
4913		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4914			IPFERROR(25);
4915			error = EINVAL;
4916		}
4917		break;
4918
4919	default :
4920		IPFERROR(26);
4921		error = EINVAL;
4922		break;
4923	}
4924	if (error != 0)
4925		goto donenolock;
4926
4927	if (fp->fr_tif.fd_name != -1) {
4928		if ((fp->fr_tif.fd_name < 0) ||
4929		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4930			IPFERROR(139);
4931			error = EINVAL;
4932			goto donenolock;
4933		}
4934	}
4935
4936	if (fp->fr_dif.fd_name != -1) {
4937		if ((fp->fr_dif.fd_name < 0) ||
4938		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4939			IPFERROR(140);
4940			error = EINVAL;
4941			goto donenolock;
4942		}
4943	}
4944
4945	if (fp->fr_rif.fd_name != -1) {
4946		if ((fp->fr_rif.fd_name < 0) ||
4947		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4948			IPFERROR(141);
4949			error = EINVAL;
4950			goto donenolock;
4951		}
4952	}
4953
4954	/*
4955	 * Lookup all the interface names that are part of the rule.
4956	 */
4957	error = ipf_synclist(softc, fp, NULL);
4958	if (error != 0)
4959		goto donenolock;
4960	fp->fr_statecnt = 0;
4961	if (fp->fr_srctrack.ht_max_nodes != 0)
4962		ipf_rb_ht_init(&fp->fr_srctrack);
4963
4964	/*
4965	 * Look for an existing matching filter rule, but don't include the
4966	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4967	 * This elminates rules which are indentical being loaded.  Checksum
4968	 * the constant part of the filter rule to make comparisons quicker
4969	 * (this meaning no pointers are included).
4970	 */
4971	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4972	for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4973		fp->fr_cksum += *p;
4974
4975	WRITE_ENTER(&softc->ipf_mutex);
4976
4977	/*
4978	 * Now that the filter rule lists are locked, we can walk the
4979	 * chain of them without fear.
4980	 */
4981	ftail = fprev;
4982	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4983		if (fp->fr_collect <= f->fr_collect) {
4984			ftail = fprev;
4985			f = NULL;
4986			break;
4987		}
4988		fprev = ftail;
4989	}
4990
4991	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4992		if (ipf_rule_compare(fp, f) == 0)
4993			break;
4994	}
4995
4996	/*
4997	 * If zero'ing statistics, copy current to caller and zero.
4998	 */
4999	if (addrem == OP_ZERO) {
5000		if (f == NULL) {
5001			IPFERROR(27);
5002			error = ESRCH;
5003		} else {
5004			/*
5005			 * Copy and reduce lock because of impending copyout.
5006			 * Well we should, but if we do then the atomicity of
5007			 * this call and the correctness of fr_hits and
5008			 * fr_bytes cannot be guaranteed.  As it is, this code
5009			 * only resets them to 0 if they are successfully
5010			 * copied out into user space.
5011			 */
5012			bcopy((char *)f, (char *)fp, f->fr_size);
5013			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
5014
5015			/*
5016			 * When we copy this rule back out, set the data
5017			 * pointer to be what it was in user space.
5018			 */
5019			fp->fr_data = uptr;
5020			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
5021
5022			if (error == 0) {
5023				if ((f->fr_dsize != 0) && (uptr != NULL)) {
5024					error = COPYOUT(f->fr_data, uptr,
5025							f->fr_dsize);
5026					if (error == 0) {
5027						f->fr_hits = 0;
5028						f->fr_bytes = 0;
5029					} else {
5030						IPFERROR(28);
5031						error = EFAULT;
5032					}
5033				}
5034			}
5035		}
5036
5037		if (makecopy != 0) {
5038			if (ptr != NULL) {
5039				KFREES(ptr, fp->fr_dsize);
5040			}
5041			KFREES(fp, fp->fr_size);
5042		}
5043		RWLOCK_EXIT(&softc->ipf_mutex);
5044		return error;
5045	}
5046
5047	if (f == NULL) {
5048		/*
5049		 * At the end of this, ftail must point to the place where the
5050		 * new rule is to be saved/inserted/added.
5051		 * For SIOCAD*FR, this should be the last rule in the group of
5052		 * rules that have equal fr_collect fields.
5053		 * For SIOCIN*FR, ...
5054		 */
5055		if (req == (ioctlcmd_t)SIOCADAFR ||
5056		    req == (ioctlcmd_t)SIOCADIFR) {
5057
5058			for (ftail = fprev; (f = *ftail) != NULL; ) {
5059				if (f->fr_collect > fp->fr_collect)
5060					break;
5061				ftail = &f->fr_next;
5062				fprev = ftail;
5063			}
5064			ftail = fprev;
5065			f = NULL;
5066			ptr = NULL;
5067		} else if (req == (ioctlcmd_t)SIOCINAFR ||
5068			   req == (ioctlcmd_t)SIOCINIFR) {
5069			while ((f = *fprev) != NULL) {
5070				if (f->fr_collect >= fp->fr_collect)
5071					break;
5072				fprev = &f->fr_next;
5073			}
5074  			ftail = fprev;
5075  			if (fp->fr_hits != 0) {
5076				while (fp->fr_hits && (f = *ftail)) {
5077					if (f->fr_collect != fp->fr_collect)
5078						break;
5079					fprev = ftail;
5080  					ftail = &f->fr_next;
5081					fp->fr_hits--;
5082				}
5083  			}
5084  			f = NULL;
5085  			ptr = NULL;
5086		}
5087	}
5088
5089	/*
5090	 * Request to remove a rule.
5091	 */
5092	if (addrem == OP_REM) {
5093		if (f == NULL) {
5094			IPFERROR(29);
5095			error = ESRCH;
5096		} else {
5097			/*
5098			 * Do not allow activity from user space to interfere
5099			 * with rules not loaded that way.
5100			 */
5101			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5102				IPFERROR(30);
5103				error = EPERM;
5104				goto done;
5105			}
5106
5107			/*
5108			 * Return EBUSY if the rule is being reference by
5109			 * something else (eg state information.)
5110			 */
5111			if (f->fr_ref > 1) {
5112				IPFERROR(31);
5113				error = EBUSY;
5114				goto done;
5115			}
5116#ifdef	IPFILTER_SCAN
5117			if (f->fr_isctag != -1 &&
5118			    (f->fr_isc != (struct ipscan *)-1))
5119				ipf_scan_detachfr(f);
5120#endif
5121
5122			if (unit == IPL_LOGAUTH) {
5123				error = ipf_auth_precmd(softc, req, f, ftail);
5124				goto done;
5125			}
5126
5127			ipf_rule_delete(softc, f, unit, set);
5128
5129			need_free = makecopy;
5130		}
5131	} else {
5132		/*
5133		 * Not removing, so we must be adding/inserting a rule.
5134		 */
5135		if (f != NULL) {
5136			IPFERROR(32);
5137			error = EEXIST;
5138			goto done;
5139		}
5140		if (unit == IPL_LOGAUTH) {
5141			error = ipf_auth_precmd(softc, req, fp, ftail);
5142			goto done;
5143		}
5144
5145		MUTEX_NUKE(&fp->fr_lock);
5146		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5147		if (fp->fr_die != 0)
5148			ipf_rule_expire_insert(softc, fp, set);
5149
5150		fp->fr_hits = 0;
5151		if (makecopy != 0)
5152			fp->fr_ref = 1;
5153		fp->fr_pnext = ftail;
5154		fp->fr_next = *ftail;
5155		if (fp->fr_next != NULL)
5156			fp->fr_next->fr_pnext = &fp->fr_next;
5157		*ftail = fp;
5158		ipf_fixskip(ftail, fp, 1);
5159
5160		fp->fr_icmpgrp = NULL;
5161		if (fp->fr_icmphead != -1) {
5162			group = FR_NAME(fp, fr_icmphead);
5163			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5164			fp->fr_icmpgrp = fg;
5165		}
5166
5167		fp->fr_grphead = NULL;
5168		if (fp->fr_grhead != -1) {
5169			group = FR_NAME(fp, fr_grhead);
5170			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5171					   unit, set);
5172			fp->fr_grphead = fg;
5173		}
5174	}
5175done:
5176	RWLOCK_EXIT(&softc->ipf_mutex);
5177donenolock:
5178	if (need_free || (error != 0)) {
5179		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5180			if ((fp->fr_satype == FRI_LOOKUP) &&
5181			    (fp->fr_srcptr != NULL))
5182				ipf_lookup_deref(softc, fp->fr_srctype,
5183						 fp->fr_srcptr);
5184			if ((fp->fr_datype == FRI_LOOKUP) &&
5185			    (fp->fr_dstptr != NULL))
5186				ipf_lookup_deref(softc, fp->fr_dsttype,
5187						 fp->fr_dstptr);
5188		}
5189		if (fp->fr_grp != NULL) {
5190			WRITE_ENTER(&softc->ipf_mutex);
5191			ipf_group_del(softc, fp->fr_grp, fp);
5192			RWLOCK_EXIT(&softc->ipf_mutex);
5193		}
5194		if ((ptr != NULL) && (makecopy != 0)) {
5195			KFREES(ptr, fp->fr_dsize);
5196		}
5197		KFREES(fp, fp->fr_size);
5198	}
5199	return (error);
5200}
5201
5202
5203/* ------------------------------------------------------------------------ */
5204/* Function:   ipf_rule_delete                                              */
5205/* Returns:    Nil                                                          */
5206/* Parameters: softc(I) - pointer to soft context main structure            */
5207/*             f(I)     - pointer to the rule being deleted                 */
5208/*             ftail(I) - pointer to the pointer to f                       */
5209/*             unit(I)  - device for which this is for                      */
5210/*             set(I)   - 1 or 0 (filter set)                               */
5211/*                                                                          */
5212/* This function attempts to do what it can to delete a filter rule: remove */
5213/* it from any linked lists and remove any groups it is responsible for.    */
5214/* But in the end, removing a rule can only drop the reference count - we   */
5215/* must use that as the guide for whether or not it can be freed.           */
5216/* ------------------------------------------------------------------------ */
5217static void
5218ipf_rule_delete(softc, f, unit, set)
5219	ipf_main_softc_t *softc;
5220	frentry_t *f;
5221	int unit, set;
5222{
5223
5224	/*
5225	 * If fr_pdnext is set, then the rule is on the expire list, so
5226	 * remove it from there.
5227	 */
5228	if (f->fr_pdnext != NULL) {
5229		*f->fr_pdnext = f->fr_dnext;
5230		if (f->fr_dnext != NULL)
5231			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5232		f->fr_pdnext = NULL;
5233		f->fr_dnext = NULL;
5234	}
5235
5236	ipf_fixskip(f->fr_pnext, f, -1);
5237	if (f->fr_pnext != NULL)
5238		*f->fr_pnext = f->fr_next;
5239	if (f->fr_next != NULL)
5240		f->fr_next->fr_pnext = f->fr_pnext;
5241	f->fr_pnext = NULL;
5242	f->fr_next = NULL;
5243
5244	(void) ipf_derefrule(softc, &f);
5245}
5246
5247/* ------------------------------------------------------------------------ */
5248/* Function:   ipf_rule_expire_insert                                       */
5249/* Returns:    Nil                                                          */
5250/* Parameters: softc(I) - pointer to soft context main structure            */
5251/*             f(I)     - pointer to rule to be added to expire list        */
5252/*             set(I)   - 1 or 0 (filter set)                               */
5253/*                                                                          */
5254/* If the new rule has a given expiration time, insert it into the list of  */
5255/* expiring rules with the ones to be removed first added to the front of   */
5256/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5257/* expiration interval checks.                                              */
5258/* ------------------------------------------------------------------------ */
5259static void
5260ipf_rule_expire_insert(softc, f, set)
5261	ipf_main_softc_t *softc;
5262	frentry_t *f;
5263	int set;
5264{
5265	frentry_t *fr;
5266
5267	/*
5268	 */
5269
5270	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5271	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5272	     fr = fr->fr_dnext) {
5273		if (f->fr_die < fr->fr_die)
5274			break;
5275		if (fr->fr_dnext == NULL) {
5276			/*
5277			 * We've got to the last rule and everything
5278			 * wanted to be expired before this new node,
5279			 * so we have to tack it on the end...
5280			 */
5281			fr->fr_dnext = f;
5282			f->fr_pdnext = &fr->fr_dnext;
5283			fr = NULL;
5284			break;
5285		}
5286	}
5287
5288	if (softc->ipf_rule_explist[set] == NULL) {
5289		softc->ipf_rule_explist[set] = f;
5290		f->fr_pdnext = &softc->ipf_rule_explist[set];
5291	} else if (fr != NULL) {
5292		f->fr_dnext = fr;
5293		f->fr_pdnext = fr->fr_pdnext;
5294		fr->fr_pdnext = &f->fr_dnext;
5295	}
5296}
5297
5298
5299/* ------------------------------------------------------------------------ */
5300/* Function:   ipf_findlookup                                               */
5301/* Returns:    NULL = failure, else success                                 */
5302/* Parameters: softc(I) - pointer to soft context main structure            */
5303/*             unit(I)  - ipf device we want to find match for              */
5304/*             fp(I)    - rule for which lookup is for                      */
5305/*             addrp(I) - pointer to lookup information in address struct   */
5306/*             maskp(O) - pointer to lookup information for storage         */
5307/*                                                                          */
5308/* When using pools and hash tables to store addresses for matching in      */
5309/* rules, it is necessary to resolve both the object referred to by the     */
5310/* name or address (and return that pointer) and also provide the means by  */
5311/* which to determine if an address belongs to that object to make the      */
5312/* packet matching quicker.                                                 */
5313/* ------------------------------------------------------------------------ */
5314static void *
5315ipf_findlookup(softc, unit, fr, addrp, maskp)
5316	ipf_main_softc_t *softc;
5317	int unit;
5318	frentry_t *fr;
5319	i6addr_t *addrp, *maskp;
5320{
5321	void *ptr = NULL;
5322
5323	switch (addrp->iplookupsubtype)
5324	{
5325	case 0 :
5326		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5327					 addrp->iplookupnum,
5328					 &maskp->iplookupfunc);
5329		break;
5330	case 1 :
5331		if (addrp->iplookupname < 0)
5332			break;
5333		if (addrp->iplookupname >= fr->fr_namelen)
5334			break;
5335		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5336					  fr->fr_names + addrp->iplookupname,
5337					  &maskp->iplookupfunc);
5338		break;
5339	default :
5340		break;
5341	}
5342
5343	return ptr;
5344}
5345
5346
5347/* ------------------------------------------------------------------------ */
5348/* Function:    ipf_funcinit                                                */
5349/* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5350/* Parameters:  softc(I) - pointer to soft context main structure           */
5351/*              fr(I)    - pointer to filter rule                           */
5352/*                                                                          */
5353/* If a rule is a call rule, then check if the function it points to needs  */
5354/* an init function to be called now the rule has been loaded.              */
5355/* ------------------------------------------------------------------------ */
5356static int
5357ipf_funcinit(softc, fr)
5358	ipf_main_softc_t *softc;
5359	frentry_t *fr;
5360{
5361	ipfunc_resolve_t *ft;
5362	int err;
5363
5364	IPFERROR(34);
5365	err = ESRCH;
5366
5367	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5368		if (ft->ipfu_addr == fr->fr_func) {
5369			err = 0;
5370			if (ft->ipfu_init != NULL)
5371				err = (*ft->ipfu_init)(softc, fr);
5372			break;
5373		}
5374	return err;
5375}
5376
5377
5378/* ------------------------------------------------------------------------ */
5379/* Function:    ipf_funcfini                                                */
5380/* Returns:     Nil                                                         */
5381/* Parameters:  softc(I) - pointer to soft context main structure           */
5382/*              fr(I)    - pointer to filter rule                           */
5383/*                                                                          */
5384/* For a given filter rule, call the matching "fini" function if the rule   */
5385/* is using a known function that would have resulted in the "init" being   */
5386/* called for ealier.                                                       */
5387/* ------------------------------------------------------------------------ */
5388static void
5389ipf_funcfini(softc, fr)
5390	ipf_main_softc_t *softc;
5391	frentry_t *fr;
5392{
5393	ipfunc_resolve_t *ft;
5394
5395	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5396		if (ft->ipfu_addr == fr->fr_func) {
5397			if (ft->ipfu_fini != NULL)
5398				(void) (*ft->ipfu_fini)(softc, fr);
5399			break;
5400		}
5401}
5402
5403
5404/* ------------------------------------------------------------------------ */
5405/* Function:    ipf_findfunc                                                */
5406/* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5407/* Parameters:  funcptr(I) - function pointer to lookup                     */
5408/*                                                                          */
5409/* Look for a function in the table of known functions.                     */
5410/* ------------------------------------------------------------------------ */
5411static ipfunc_t
5412ipf_findfunc(funcptr)
5413	ipfunc_t funcptr;
5414{
5415	ipfunc_resolve_t *ft;
5416
5417	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5418		if (ft->ipfu_addr == funcptr)
5419			return funcptr;
5420	return NULL;
5421}
5422
5423
5424/* ------------------------------------------------------------------------ */
5425/* Function:    ipf_resolvefunc                                             */
5426/* Returns:     int - 0 == success, else error                              */
5427/* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5428/*                                                                          */
5429/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5430/* This will either be the function name (if the pointer is set) or the     */
5431/* function pointer if the name is set.  When found, fill in the other one  */
5432/* so that the entire, complete, structure can be copied back to user space.*/
5433/* ------------------------------------------------------------------------ */
5434int
5435ipf_resolvefunc(softc, data)
5436	ipf_main_softc_t *softc;
5437	void *data;
5438{
5439	ipfunc_resolve_t res, *ft;
5440	int error;
5441
5442	error = BCOPYIN(data, &res, sizeof(res));
5443	if (error != 0) {
5444		IPFERROR(123);
5445		return EFAULT;
5446	}
5447
5448	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5449		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5450			if (strncmp(res.ipfu_name, ft->ipfu_name,
5451				    sizeof(res.ipfu_name)) == 0) {
5452				res.ipfu_addr = ft->ipfu_addr;
5453				res.ipfu_init = ft->ipfu_init;
5454				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5455					IPFERROR(35);
5456					return EFAULT;
5457				}
5458				return 0;
5459			}
5460	}
5461	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5462		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5463			if (ft->ipfu_addr == res.ipfu_addr) {
5464				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5465					       sizeof(res.ipfu_name));
5466				res.ipfu_init = ft->ipfu_init;
5467				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5468					IPFERROR(36);
5469					return EFAULT;
5470				}
5471				return 0;
5472			}
5473	}
5474	IPFERROR(37);
5475	return ESRCH;
5476}
5477
5478
5479#if !defined(_KERNEL) || SOLARIS
5480/*
5481 * From: NetBSD
5482 * ppsratecheck(): packets (or events) per second limitation.
5483 */
5484int
5485ppsratecheck(lasttime, curpps, maxpps)
5486	struct timeval *lasttime;
5487	int *curpps;
5488	int maxpps;	/* maximum pps allowed */
5489{
5490	struct timeval tv, delta;
5491	int rv;
5492
5493	GETKTIME(&tv);
5494
5495	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5496	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5497	if (delta.tv_usec < 0) {
5498		delta.tv_sec--;
5499		delta.tv_usec += 1000000;
5500	}
5501
5502	/*
5503	 * check for 0,0 is so that the message will be seen at least once.
5504	 * if more than one second have passed since the last update of
5505	 * lasttime, reset the counter.
5506	 *
5507	 * we do increment *curpps even in *curpps < maxpps case, as some may
5508	 * try to use *curpps for stat purposes as well.
5509	 */
5510	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5511	    delta.tv_sec >= 1) {
5512		*lasttime = tv;
5513		*curpps = 0;
5514		rv = 1;
5515	} else if (maxpps < 0)
5516		rv = 1;
5517	else if (*curpps < maxpps)
5518		rv = 1;
5519	else
5520		rv = 0;
5521	*curpps = *curpps + 1;
5522
5523	return (rv);
5524}
5525#endif
5526
5527
5528/* ------------------------------------------------------------------------ */
5529/* Function:    ipf_derefrule                                               */
5530/* Returns:     int   - 0 == rule freed up, else rule not freed             */
5531/* Parameters:  fr(I) - pointer to filter rule                              */
5532/*                                                                          */
5533/* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5534/* free it and any associated storage space being used by it.               */
5535/* ------------------------------------------------------------------------ */
5536int
5537ipf_derefrule(softc, frp)
5538	ipf_main_softc_t *softc;
5539	frentry_t **frp;
5540{
5541	frentry_t *fr;
5542	frdest_t *fdp;
5543
5544	fr = *frp;
5545	*frp = NULL;
5546
5547	MUTEX_ENTER(&fr->fr_lock);
5548	fr->fr_ref--;
5549	if (fr->fr_ref == 0) {
5550		MUTEX_EXIT(&fr->fr_lock);
5551		MUTEX_DESTROY(&fr->fr_lock);
5552
5553		ipf_funcfini(softc, fr);
5554
5555		fdp = &fr->fr_tif;
5556		if (fdp->fd_type == FRD_DSTLIST)
5557			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5558
5559		fdp = &fr->fr_rif;
5560		if (fdp->fd_type == FRD_DSTLIST)
5561			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5562
5563		fdp = &fr->fr_dif;
5564		if (fdp->fd_type == FRD_DSTLIST)
5565			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5566
5567		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5568		    fr->fr_satype == FRI_LOOKUP)
5569			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5570		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5571		    fr->fr_datype == FRI_LOOKUP)
5572			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5573
5574		if (fr->fr_grp != NULL)
5575			ipf_group_del(softc, fr->fr_grp, fr);
5576
5577		if (fr->fr_grphead != NULL)
5578			ipf_group_del(softc, fr->fr_grphead, fr);
5579
5580		if (fr->fr_icmpgrp != NULL)
5581			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5582
5583		if ((fr->fr_flags & FR_COPIED) != 0) {
5584			if (fr->fr_dsize) {
5585				KFREES(fr->fr_data, fr->fr_dsize);
5586			}
5587			KFREES(fr, fr->fr_size);
5588			return 0;
5589		}
5590		return 1;
5591	} else {
5592		MUTEX_EXIT(&fr->fr_lock);
5593	}
5594	return -1;
5595}
5596
5597
5598/* ------------------------------------------------------------------------ */
5599/* Function:    ipf_grpmapinit                                              */
5600/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5601/* Parameters:  fr(I) - pointer to rule to find hash table for              */
5602/*                                                                          */
5603/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5604/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5605/* ------------------------------------------------------------------------ */
5606static int
5607ipf_grpmapinit(softc, fr)
5608	ipf_main_softc_t *softc;
5609	frentry_t *fr;
5610{
5611	char name[FR_GROUPLEN];
5612	iphtable_t *iph;
5613
5614#if defined(SNPRINTF) && defined(_KERNEL)
5615	SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5616#else
5617	(void) sprintf(name, "%d", fr->fr_arg);
5618#endif
5619	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5620	if (iph == NULL) {
5621		IPFERROR(38);
5622		return ESRCH;
5623	}
5624	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5625		IPFERROR(39);
5626		return ESRCH;
5627	}
5628	iph->iph_ref++;
5629	fr->fr_ptr = iph;
5630	return 0;
5631}
5632
5633
5634/* ------------------------------------------------------------------------ */
5635/* Function:    ipf_grpmapfini                                              */
5636/* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5637/* Parameters:  softc(I) - pointer to soft context main structure           */
5638/*              fr(I)    - pointer to rule to release hash table for        */
5639/*                                                                          */
5640/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5641/* be called to undo what ipf_grpmapinit caused to be done.                 */
5642/* ------------------------------------------------------------------------ */
5643static int
5644ipf_grpmapfini(softc, fr)
5645	ipf_main_softc_t *softc;
5646	frentry_t *fr;
5647{
5648	iphtable_t *iph;
5649	iph = fr->fr_ptr;
5650	if (iph != NULL)
5651		ipf_lookup_deref(softc, IPLT_HASH, iph);
5652	return 0;
5653}
5654
5655
5656/* ------------------------------------------------------------------------ */
5657/* Function:    ipf_srcgrpmap                                               */
5658/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5659/* Parameters:  fin(I)    - pointer to packet information                   */
5660/*              passp(IO) - pointer to current/new filter decision (unused) */
5661/*                                                                          */
5662/* Look for a rule group head in a hash table, using the source address as  */
5663/* the key, and descend into that group and continue matching rules against */
5664/* the packet.                                                              */
5665/* ------------------------------------------------------------------------ */
5666frentry_t *
5667ipf_srcgrpmap(fin, passp)
5668	fr_info_t *fin;
5669	u_32_t *passp;
5670{
5671	frgroup_t *fg;
5672	void *rval;
5673
5674	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5675				 &fin->fin_src);
5676	if (rval == NULL)
5677		return NULL;
5678
5679	fg = rval;
5680	fin->fin_fr = fg->fg_start;
5681	(void) ipf_scanlist(fin, *passp);
5682	return fin->fin_fr;
5683}
5684
5685
5686/* ------------------------------------------------------------------------ */
5687/* Function:    ipf_dstgrpmap                                               */
5688/* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5689/* Parameters:  fin(I)    - pointer to packet information                   */
5690/*              passp(IO) - pointer to current/new filter decision (unused) */
5691/*                                                                          */
5692/* Look for a rule group head in a hash table, using the destination        */
5693/* address as the key, and descend into that group and continue matching    */
5694/* rules against  the packet.                                               */
5695/* ------------------------------------------------------------------------ */
5696frentry_t *
5697ipf_dstgrpmap(fin, passp)
5698	fr_info_t *fin;
5699	u_32_t *passp;
5700{
5701	frgroup_t *fg;
5702	void *rval;
5703
5704	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5705				 &fin->fin_dst);
5706	if (rval == NULL)
5707		return NULL;
5708
5709	fg = rval;
5710	fin->fin_fr = fg->fg_start;
5711	(void) ipf_scanlist(fin, *passp);
5712	return fin->fin_fr;
5713}
5714
5715/*
5716 * Queue functions
5717 * ===============
5718 * These functions manage objects on queues for efficient timeouts.  There
5719 * are a number of system defined queues as well as user defined timeouts.
5720 * It is expected that a lock is held in the domain in which the queue
5721 * belongs (i.e. either state or NAT) when calling any of these functions
5722 * that prevents ipf_freetimeoutqueue() from being called at the same time
5723 * as any other.
5724 */
5725
5726
5727/* ------------------------------------------------------------------------ */
5728/* Function:    ipf_addtimeoutqueue                                         */
5729/* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5730/*                               timeout queue with given interval.         */
5731/* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5732/*                           of interface queues.                           */
5733/*              seconds(I) - timeout value in seconds for this queue.       */
5734/*                                                                          */
5735/* This routine first looks for a timeout queue that matches the interval   */
5736/* being requested.  If it finds one, increments the reference counter and  */
5737/* returns a pointer to it.  If none are found, it allocates a new one and  */
5738/* inserts it at the top of the list.                                       */
5739/*                                                                          */
5740/* Locking.                                                                 */
5741/* It is assumed that the caller of this function has an appropriate lock   */
5742/* held (exclusively) in the domain that encompases 'parent'.               */
5743/* ------------------------------------------------------------------------ */
5744ipftq_t *
5745ipf_addtimeoutqueue(softc, parent, seconds)
5746	ipf_main_softc_t *softc;
5747	ipftq_t **parent;
5748	u_int seconds;
5749{
5750	ipftq_t *ifq;
5751	u_int period;
5752
5753	period = seconds * IPF_HZ_DIVIDE;
5754
5755	MUTEX_ENTER(&softc->ipf_timeoutlock);
5756	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5757		if (ifq->ifq_ttl == period) {
5758			/*
5759			 * Reset the delete flag, if set, so the structure
5760			 * gets reused rather than freed and reallocated.
5761			 */
5762			MUTEX_ENTER(&ifq->ifq_lock);
5763			ifq->ifq_flags &= ~IFQF_DELETE;
5764			ifq->ifq_ref++;
5765			MUTEX_EXIT(&ifq->ifq_lock);
5766			MUTEX_EXIT(&softc->ipf_timeoutlock);
5767
5768			return ifq;
5769		}
5770	}
5771
5772	KMALLOC(ifq, ipftq_t *);
5773	if (ifq != NULL) {
5774		MUTEX_NUKE(&ifq->ifq_lock);
5775		IPFTQ_INIT(ifq, period, "ipftq mutex");
5776		ifq->ifq_next = *parent;
5777		ifq->ifq_pnext = parent;
5778		ifq->ifq_flags = IFQF_USER;
5779		ifq->ifq_ref++;
5780		*parent = ifq;
5781		softc->ipf_userifqs++;
5782	}
5783	MUTEX_EXIT(&softc->ipf_timeoutlock);
5784	return ifq;
5785}
5786
5787
5788/* ------------------------------------------------------------------------ */
5789/* Function:    ipf_deletetimeoutqueue                                      */
5790/* Returns:     int    - new reference count value of the timeout queue     */
5791/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5792/* Locks:       ifq->ifq_lock                                               */
5793/*                                                                          */
5794/* This routine must be called when we're discarding a pointer to a timeout */
5795/* queue object, taking care of the reference counter.                      */
5796/*                                                                          */
5797/* Now that this just sets a DELETE flag, it requires the expire code to    */
5798/* check the list of user defined timeout queues and call the free function */
5799/* below (currently commented out) to stop memory leaking.  It is done this */
5800/* way because the locking may not be sufficient to safely do a free when   */
5801/* this function is called.                                                 */
5802/* ------------------------------------------------------------------------ */
5803int
5804ipf_deletetimeoutqueue(ifq)
5805	ipftq_t *ifq;
5806{
5807
5808	ifq->ifq_ref--;
5809	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5810		ifq->ifq_flags |= IFQF_DELETE;
5811	}
5812
5813	return ifq->ifq_ref;
5814}
5815
5816
5817/* ------------------------------------------------------------------------ */
5818/* Function:    ipf_freetimeoutqueue                                        */
5819/* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5820/* Returns:     Nil                                                         */
5821/*                                                                          */
5822/* Locking:                                                                 */
5823/* It is assumed that the caller of this function has an appropriate lock   */
5824/* held (exclusively) in the domain that encompases the callers "domain".   */
5825/* The ifq_lock for this structure should not be held.                      */
5826/*                                                                          */
5827/* Remove a user defined timeout queue from the list of queues it is in and */
5828/* tidy up after this is done.                                              */
5829/* ------------------------------------------------------------------------ */
5830void
5831ipf_freetimeoutqueue(softc, ifq)
5832	ipf_main_softc_t *softc;
5833	ipftq_t *ifq;
5834{
5835
5836	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5837	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5838		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5839		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5840		       ifq->ifq_ref);
5841		return;
5842	}
5843
5844	/*
5845	 * Remove from its position in the list.
5846	 */
5847	*ifq->ifq_pnext = ifq->ifq_next;
5848	if (ifq->ifq_next != NULL)
5849		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5850	ifq->ifq_next = NULL;
5851	ifq->ifq_pnext = NULL;
5852
5853	MUTEX_DESTROY(&ifq->ifq_lock);
5854	ATOMIC_DEC(softc->ipf_userifqs);
5855	KFREE(ifq);
5856}
5857
5858
5859/* ------------------------------------------------------------------------ */
5860/* Function:    ipf_deletequeueentry                                        */
5861/* Returns:     Nil                                                         */
5862/* Parameters:  tqe(I) - timeout queue entry to delete                      */
5863/*                                                                          */
5864/* Remove a tail queue entry from its queue and make it an orphan.          */
5865/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5866/* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5867/* the correct lock(s) may not be held that would make it safe to do so.    */
5868/* ------------------------------------------------------------------------ */
5869void
5870ipf_deletequeueentry(tqe)
5871	ipftqent_t *tqe;
5872{
5873	ipftq_t *ifq;
5874
5875	ifq = tqe->tqe_ifq;
5876
5877	MUTEX_ENTER(&ifq->ifq_lock);
5878
5879	if (tqe->tqe_pnext != NULL) {
5880		*tqe->tqe_pnext = tqe->tqe_next;
5881		if (tqe->tqe_next != NULL)
5882			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5883		else    /* we must be the tail anyway */
5884			ifq->ifq_tail = tqe->tqe_pnext;
5885
5886		tqe->tqe_pnext = NULL;
5887		tqe->tqe_ifq = NULL;
5888	}
5889
5890	(void) ipf_deletetimeoutqueue(ifq);
5891	ASSERT(ifq->ifq_ref > 0);
5892
5893	MUTEX_EXIT(&ifq->ifq_lock);
5894}
5895
5896
5897/* ------------------------------------------------------------------------ */
5898/* Function:    ipf_queuefront                                              */
5899/* Returns:     Nil                                                         */
5900/* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5901/*                                                                          */
5902/* Move a queue entry to the front of the queue, if it isn't already there. */
5903/* ------------------------------------------------------------------------ */
5904void
5905ipf_queuefront(tqe)
5906	ipftqent_t *tqe;
5907{
5908	ipftq_t *ifq;
5909
5910	ifq = tqe->tqe_ifq;
5911	if (ifq == NULL)
5912		return;
5913
5914	MUTEX_ENTER(&ifq->ifq_lock);
5915	if (ifq->ifq_head != tqe) {
5916		*tqe->tqe_pnext = tqe->tqe_next;
5917		if (tqe->tqe_next)
5918			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5919		else
5920			ifq->ifq_tail = tqe->tqe_pnext;
5921
5922		tqe->tqe_next = ifq->ifq_head;
5923		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5924		ifq->ifq_head = tqe;
5925		tqe->tqe_pnext = &ifq->ifq_head;
5926	}
5927	MUTEX_EXIT(&ifq->ifq_lock);
5928}
5929
5930
5931/* ------------------------------------------------------------------------ */
5932/* Function:    ipf_queueback                                               */
5933/* Returns:     Nil                                                         */
5934/* Parameters:  ticks(I) - ipf tick time to use with this call              */
5935/*              tqe(I)   - pointer to timeout queue entry                   */
5936/*                                                                          */
5937/* Move a queue entry to the back of the queue, if it isn't already there.  */
5938/* We use use ticks to calculate the expiration and mark for when we last   */
5939/* touched the structure.                                                   */
5940/* ------------------------------------------------------------------------ */
5941void
5942ipf_queueback(ticks, tqe)
5943	u_long ticks;
5944	ipftqent_t *tqe;
5945{
5946	ipftq_t *ifq;
5947
5948	ifq = tqe->tqe_ifq;
5949	if (ifq == NULL)
5950		return;
5951	tqe->tqe_die = ticks + ifq->ifq_ttl;
5952	tqe->tqe_touched = ticks;
5953
5954	MUTEX_ENTER(&ifq->ifq_lock);
5955	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5956		/*
5957		 * Remove from list
5958		 */
5959		*tqe->tqe_pnext = tqe->tqe_next;
5960		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5961
5962		/*
5963		 * Make it the last entry.
5964		 */
5965		tqe->tqe_next = NULL;
5966		tqe->tqe_pnext = ifq->ifq_tail;
5967		*ifq->ifq_tail = tqe;
5968		ifq->ifq_tail = &tqe->tqe_next;
5969	}
5970	MUTEX_EXIT(&ifq->ifq_lock);
5971}
5972
5973
5974/* ------------------------------------------------------------------------ */
5975/* Function:    ipf_queueappend                                             */
5976/* Returns:     Nil                                                         */
5977/* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5978/*              tqe(I)    - pointer to timeout queue entry                  */
5979/*              ifq(I)    - pointer to timeout queue                        */
5980/*              parent(I) - owing object pointer                            */
5981/*                                                                          */
5982/* Add a new item to this queue and put it on the very end.                 */
5983/* We use use ticks to calculate the expiration and mark for when we last   */
5984/* touched the structure.                                                   */
5985/* ------------------------------------------------------------------------ */
5986void
5987ipf_queueappend(ticks, tqe, ifq, parent)
5988	u_long ticks;
5989	ipftqent_t *tqe;
5990	ipftq_t *ifq;
5991	void *parent;
5992{
5993
5994	MUTEX_ENTER(&ifq->ifq_lock);
5995	tqe->tqe_parent = parent;
5996	tqe->tqe_pnext = ifq->ifq_tail;
5997	*ifq->ifq_tail = tqe;
5998	ifq->ifq_tail = &tqe->tqe_next;
5999	tqe->tqe_next = NULL;
6000	tqe->tqe_ifq = ifq;
6001	tqe->tqe_die = ticks + ifq->ifq_ttl;
6002	tqe->tqe_touched = ticks;
6003	ifq->ifq_ref++;
6004	MUTEX_EXIT(&ifq->ifq_lock);
6005}
6006
6007
6008/* ------------------------------------------------------------------------ */
6009/* Function:    ipf_movequeue                                               */
6010/* Returns:     Nil                                                         */
6011/* Parameters:  tq(I)   - pointer to timeout queue information              */
6012/*              oifp(I) - old timeout queue entry was on                    */
6013/*              nifp(I) - new timeout queue to put entry on                 */
6014/*                                                                          */
6015/* Move a queue entry from one timeout queue to another timeout queue.      */
6016/* If it notices that the current entry is already last and does not need   */
6017/* to move queue, the return.                                               */
6018/* ------------------------------------------------------------------------ */
6019void
6020ipf_movequeue(ticks, tqe, oifq, nifq)
6021	u_long ticks;
6022	ipftqent_t *tqe;
6023	ipftq_t *oifq, *nifq;
6024{
6025
6026	/*
6027	 * If the queue hasn't changed and we last touched this entry at the
6028	 * same ipf time, then we're not going to achieve anything by either
6029	 * changing the ttl or moving it on the queue.
6030	 */
6031	if (oifq == nifq && tqe->tqe_touched == ticks)
6032		return;
6033
6034	/*
6035	 * For any of this to be outside the lock, there is a risk that two
6036	 * packets entering simultaneously, with one changing to a different
6037	 * queue and one not, could end up with things in a bizarre state.
6038	 */
6039	MUTEX_ENTER(&oifq->ifq_lock);
6040
6041	tqe->tqe_touched = ticks;
6042	tqe->tqe_die = ticks + nifq->ifq_ttl;
6043	/*
6044	 * Is the operation here going to be a no-op ?
6045	 */
6046	if (oifq == nifq) {
6047		if ((tqe->tqe_next == NULL) ||
6048		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6049			MUTEX_EXIT(&oifq->ifq_lock);
6050			return;
6051		}
6052	}
6053
6054	/*
6055	 * Remove from the old queue
6056	 */
6057	*tqe->tqe_pnext = tqe->tqe_next;
6058	if (tqe->tqe_next)
6059		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6060	else
6061		oifq->ifq_tail = tqe->tqe_pnext;
6062	tqe->tqe_next = NULL;
6063
6064	/*
6065	 * If we're moving from one queue to another, release the
6066	 * lock on the old queue and get a lock on the new queue.
6067	 * For user defined queues, if we're moving off it, call
6068	 * delete in case it can now be freed.
6069	 */
6070	if (oifq != nifq) {
6071		tqe->tqe_ifq = NULL;
6072
6073		(void) ipf_deletetimeoutqueue(oifq);
6074
6075		MUTEX_EXIT(&oifq->ifq_lock);
6076
6077		MUTEX_ENTER(&nifq->ifq_lock);
6078
6079		tqe->tqe_ifq = nifq;
6080		nifq->ifq_ref++;
6081	}
6082
6083	/*
6084	 * Add to the bottom of the new queue
6085	 */
6086	tqe->tqe_pnext = nifq->ifq_tail;
6087	*nifq->ifq_tail = tqe;
6088	nifq->ifq_tail = &tqe->tqe_next;
6089	MUTEX_EXIT(&nifq->ifq_lock);
6090}
6091
6092
6093/* ------------------------------------------------------------------------ */
6094/* Function:    ipf_updateipid                                              */
6095/* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6096/* Parameters:  fin(I) - pointer to packet information                      */
6097/*                                                                          */
6098/* When we are doing NAT, change the IP of every packet to represent a      */
6099/* single sequence of packets coming from the host, hiding any host         */
6100/* specific sequencing that might otherwise be revealed.  If the packet is  */
6101/* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6102/* the fragment cache for non-leading fragments.  If a non-leading fragment */
6103/* has no match in the cache, return an error.                              */
6104/* ------------------------------------------------------------------------ */
6105static int
6106ipf_updateipid(fin)
6107	fr_info_t *fin;
6108{
6109	u_short id, ido, sums;
6110	u_32_t sumd, sum;
6111	ip_t *ip;
6112
6113	ip = fin->fin_ip;
6114	ido = ntohs(ip->ip_id);
6115	if (fin->fin_off != 0) {
6116		sum = ipf_frag_ipidknown(fin);
6117		if (sum == 0xffffffff)
6118			return -1;
6119		sum &= 0xffff;
6120		id = (u_short)sum;
6121		ip->ip_id = htons(id);
6122	} else {
6123		ip_fillid(ip);
6124		id = ntohs(ip->ip_id);
6125		if ((fin->fin_flx & FI_FRAG) != 0)
6126			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
6127	}
6128
6129	if (id == ido)
6130		return 0;
6131	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
6132	sum = (~ntohs(ip->ip_sum)) & 0xffff;
6133	sum += sumd;
6134	sum = (sum >> 16) + (sum & 0xffff);
6135	sum = (sum >> 16) + (sum & 0xffff);
6136	sums = ~(u_short)sum;
6137	ip->ip_sum = htons(sums);
6138	return 0;
6139}
6140
6141
6142#ifdef	NEED_FRGETIFNAME
6143/* ------------------------------------------------------------------------ */
6144/* Function:    ipf_getifname                                               */
6145/* Returns:     char *    - pointer to interface name                       */
6146/* Parameters:  ifp(I)    - pointer to network interface                    */
6147/*              buffer(O) - pointer to where to store interface name        */
6148/*                                                                          */
6149/* Constructs an interface name in the buffer passed.  The buffer passed is */
6150/* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6151/* as a NULL pointer then return a pointer to a static array.               */
6152/* ------------------------------------------------------------------------ */
6153char *
6154ipf_getifname(ifp, buffer)
6155	struct ifnet *ifp;
6156	char *buffer;
6157{
6158	static char namebuf[LIFNAMSIZ];
6159# if defined(MENTAT) || defined(__FreeBSD__)
6160	int unit, space;
6161	char temp[20];
6162	char *s;
6163# endif
6164
6165	if (buffer == NULL)
6166		buffer = namebuf;
6167	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6168	buffer[LIFNAMSIZ - 1] = '\0';
6169# if defined(MENTAT) || defined(__FreeBSD__)
6170	for (s = buffer; *s; s++)
6171		;
6172	unit = ifp->if_unit;
6173	space = LIFNAMSIZ - (s - buffer);
6174	if ((space > 0) && (unit >= 0)) {
6175#  if defined(SNPRINTF) && defined(_KERNEL)
6176		SNPRINTF(temp, sizeof(temp), "%d", unit);
6177#  else
6178		(void) sprintf(temp, "%d", unit);
6179#  endif
6180		(void) strncpy(s, temp, space);
6181	}
6182# endif
6183	return buffer;
6184}
6185#endif
6186
6187
6188/* ------------------------------------------------------------------------ */
6189/* Function:    ipf_ioctlswitch                                             */
6190/* Returns:     int     - -1 continue processing, else ioctl return value   */
6191/* Parameters:  unit(I) - device unit opened                                */
6192/*              data(I) - pointer to ioctl data                             */
6193/*              cmd(I)  - ioctl command                                     */
6194/*              mode(I) - mode value                                        */
6195/*              uid(I)  - uid making the ioctl call                         */
6196/*              ctx(I)  - pointer to context data                           */
6197/*                                                                          */
6198/* Based on the value of unit, call the appropriate ioctl handler or return */
6199/* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6200/* for the device in order to execute the ioctl.  A special case is made    */
6201/* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6202/* The context data pointer is passed through as this is used as the key    */
6203/* for locating a matching token for continued access for walking lists,    */
6204/* etc.                                                                     */
6205/* ------------------------------------------------------------------------ */
6206int
6207ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6208	ipf_main_softc_t *softc;
6209	int unit, mode, uid;
6210	ioctlcmd_t cmd;
6211	void *data, *ctx;
6212{
6213	int error = 0;
6214
6215	switch (cmd)
6216	{
6217	case SIOCIPFINTERROR :
6218		error = BCOPYOUT(&softc->ipf_interror, data,
6219				 sizeof(softc->ipf_interror));
6220		if (error != 0) {
6221			IPFERROR(40);
6222			error = EFAULT;
6223		}
6224		return error;
6225	default :
6226		break;
6227	}
6228
6229	switch (unit)
6230	{
6231	case IPL_LOGIPF :
6232		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6233		break;
6234	case IPL_LOGNAT :
6235		if (softc->ipf_running > 0) {
6236			error = ipf_nat_ioctl(softc, data, cmd, mode,
6237					      uid, ctx);
6238		} else {
6239			IPFERROR(42);
6240			error = EIO;
6241		}
6242		break;
6243	case IPL_LOGSTATE :
6244		if (softc->ipf_running > 0) {
6245			error = ipf_state_ioctl(softc, data, cmd, mode,
6246						uid, ctx);
6247		} else {
6248			IPFERROR(43);
6249			error = EIO;
6250		}
6251		break;
6252	case IPL_LOGAUTH :
6253		if (softc->ipf_running > 0) {
6254			error = ipf_auth_ioctl(softc, data, cmd, mode,
6255					       uid, ctx);
6256		} else {
6257			IPFERROR(44);
6258			error = EIO;
6259		}
6260		break;
6261	case IPL_LOGSYNC :
6262		if (softc->ipf_running > 0) {
6263			error = ipf_sync_ioctl(softc, data, cmd, mode,
6264					       uid, ctx);
6265		} else {
6266			error = EIO;
6267			IPFERROR(45);
6268		}
6269		break;
6270	case IPL_LOGSCAN :
6271#ifdef IPFILTER_SCAN
6272		if (softc->ipf_running > 0)
6273			error = ipf_scan_ioctl(softc, data, cmd, mode,
6274					       uid, ctx);
6275		else
6276#endif
6277		{
6278			error = EIO;
6279			IPFERROR(46);
6280		}
6281		break;
6282	case IPL_LOGLOOKUP :
6283		if (softc->ipf_running > 0) {
6284			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6285						 uid, ctx);
6286		} else {
6287			error = EIO;
6288			IPFERROR(47);
6289		}
6290		break;
6291	default :
6292		IPFERROR(48);
6293		error = EIO;
6294		break;
6295	}
6296
6297	return error;
6298}
6299
6300
6301/*
6302 * This array defines the expected size of objects coming into the kernel
6303 * for the various recognised object types. The first column is flags (see
6304 * below), 2nd column is current size, 3rd column is the version number of
6305 * when the current size became current.
6306 * Flags:
6307 * 1 = minimum size, not absolute size
6308 */
6309static const int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6310	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6311	{ 1,	sizeof(struct friostat),	5010000 },
6312	{ 0,	sizeof(struct fr_info),		5010000 },
6313	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6314	{ 0,	sizeof(struct ipfrstat),	5010000 },
6315	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6316	{ 0,	sizeof(struct natstat),		5010000 },
6317	{ 0,	sizeof(struct ipstate_save),	5010000 },
6318	{ 1,	sizeof(struct nat_save),	5010000 },
6319	{ 0,	sizeof(struct natlookup),	5010000 },
6320	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6321	{ 0,	sizeof(struct ips_stat),	5010000 },
6322	{ 0,	sizeof(struct frauth),		5010000 },
6323	{ 0,	sizeof(struct ipftune),		4010100 },
6324	{ 0,	sizeof(struct nat),		5010000 },
6325	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6326	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6327	{ 0,	sizeof(struct ipftable),	4011400 },
6328	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6329	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6330	{ 1,	0,				0	}, /* IPFEXPR */
6331	{ 0,	0,				0	}, /* PROXYCTL */
6332	{ 0,	sizeof (struct fripf),		5010000	}
6333};
6334
6335
6336/* ------------------------------------------------------------------------ */
6337/* Function:    ipf_inobj                                                   */
6338/* Returns:     int     - 0 = success, else failure                         */
6339/* Parameters:  softc(I) - soft context pointerto work with                 */
6340/*              data(I)  - pointer to ioctl data                            */
6341/*              objp(O)  - where to store ipfobj structure                  */
6342/*              ptr(I)   - pointer to data to copy out                      */
6343/*              type(I)  - type of structure being moved                    */
6344/*                                                                          */
6345/* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6346/* add things to check for version numbers, sizes, etc, to make it backward */
6347/* compatible at the ABI for user land.                                     */
6348/* If objp is not NULL then we assume that the caller wants to see what is  */
6349/* in the ipfobj_t structure being copied in. As an example, this can tell  */
6350/* the caller what version of ipfilter the ioctl program was written to.    */
6351/* ------------------------------------------------------------------------ */
6352int
6353ipf_inobj(softc, data, objp, ptr, type)
6354	ipf_main_softc_t *softc;
6355	void *data;
6356	ipfobj_t *objp;
6357	void *ptr;
6358	int type;
6359{
6360	ipfobj_t obj;
6361	int error;
6362	int size;
6363
6364	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6365		IPFERROR(49);
6366		return EINVAL;
6367	}
6368
6369	if (objp == NULL)
6370		objp = &obj;
6371	error = BCOPYIN(data, objp, sizeof(*objp));
6372	if (error != 0) {
6373		IPFERROR(124);
6374		return EFAULT;
6375	}
6376
6377	if (objp->ipfo_type != type) {
6378		IPFERROR(50);
6379		return EINVAL;
6380	}
6381
6382	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6383		if ((ipf_objbytes[type][0] & 1) != 0) {
6384			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6385				IPFERROR(51);
6386				return EINVAL;
6387			}
6388			size =  ipf_objbytes[type][1];
6389		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6390			size =  objp->ipfo_size;
6391		} else {
6392			IPFERROR(52);
6393			return EINVAL;
6394		}
6395		error = COPYIN(objp->ipfo_ptr, ptr, size);
6396		if (error != 0) {
6397			IPFERROR(55);
6398			error = EFAULT;
6399		}
6400	} else {
6401#ifdef  IPFILTER_COMPAT
6402		error = ipf_in_compat(softc, objp, ptr, 0);
6403#else
6404		IPFERROR(54);
6405		error = EINVAL;
6406#endif
6407	}
6408	return error;
6409}
6410
6411
6412/* ------------------------------------------------------------------------ */
6413/* Function:    ipf_inobjsz                                                 */
6414/* Returns:     int     - 0 = success, else failure                         */
6415/* Parameters:  softc(I) - soft context pointerto work with                 */
6416/*              data(I)  - pointer to ioctl data                            */
6417/*              ptr(I)   - pointer to store real data in                    */
6418/*              type(I)  - type of structure being moved                    */
6419/*              sz(I)    - size of data to copy                             */
6420/*                                                                          */
6421/* As per ipf_inobj, except the size of the object to copy in is passed in  */
6422/* but it must not be smaller than the size defined for the type and the    */
6423/* type must allow for varied sized objects.  The extra requirement here is */
6424/* that sz must match the size of the object being passed in - this is not  */
6425/* not possible nor required in ipf_inobj().                                */
6426/* ------------------------------------------------------------------------ */
6427int
6428ipf_inobjsz(softc, data, ptr, type, sz)
6429	ipf_main_softc_t *softc;
6430	void *data;
6431	void *ptr;
6432	int type, sz;
6433{
6434	ipfobj_t obj;
6435	int error;
6436
6437	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6438		IPFERROR(56);
6439		return EINVAL;
6440	}
6441
6442	error = BCOPYIN(data, &obj, sizeof(obj));
6443	if (error != 0) {
6444		IPFERROR(125);
6445		return EFAULT;
6446	}
6447
6448	if (obj.ipfo_type != type) {
6449		IPFERROR(58);
6450		return EINVAL;
6451	}
6452
6453	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6454		if (((ipf_objbytes[type][0] & 1) == 0) ||
6455		    (sz < ipf_objbytes[type][1])) {
6456			IPFERROR(57);
6457			return EINVAL;
6458		}
6459		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6460		if (error != 0) {
6461			IPFERROR(61);
6462			error = EFAULT;
6463		}
6464	} else {
6465#ifdef	IPFILTER_COMPAT
6466		error = ipf_in_compat(softc, &obj, ptr, sz);
6467#else
6468		IPFERROR(60);
6469		error = EINVAL;
6470#endif
6471	}
6472	return error;
6473}
6474
6475
6476/* ------------------------------------------------------------------------ */
6477/* Function:    ipf_outobjsz                                                */
6478/* Returns:     int     - 0 = success, else failure                         */
6479/* Parameters:  data(I) - pointer to ioctl data                             */
6480/*              ptr(I)  - pointer to store real data in                     */
6481/*              type(I) - type of structure being moved                     */
6482/*              sz(I)   - size of data to copy                              */
6483/*                                                                          */
6484/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6485/* but it must not be smaller than the size defined for the type and the    */
6486/* type must allow for varied sized objects.  The extra requirement here is */
6487/* that sz must match the size of the object being passed in - this is not  */
6488/* not possible nor required in ipf_outobj().                               */
6489/* ------------------------------------------------------------------------ */
6490int
6491ipf_outobjsz(softc, data, ptr, type, sz)
6492	ipf_main_softc_t *softc;
6493	void *data;
6494	void *ptr;
6495	int type, sz;
6496{
6497	ipfobj_t obj;
6498	int error;
6499
6500	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6501		IPFERROR(62);
6502		return EINVAL;
6503	}
6504
6505	error = BCOPYIN(data, &obj, sizeof(obj));
6506	if (error != 0) {
6507		IPFERROR(127);
6508		return EFAULT;
6509	}
6510
6511	if (obj.ipfo_type != type) {
6512		IPFERROR(63);
6513		return EINVAL;
6514	}
6515
6516	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6517		if (((ipf_objbytes[type][0] & 1) == 0) ||
6518		    (sz < ipf_objbytes[type][1])) {
6519			IPFERROR(146);
6520			return EINVAL;
6521		}
6522		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6523		if (error != 0) {
6524			IPFERROR(66);
6525			error = EFAULT;
6526		}
6527	} else {
6528#ifdef	IPFILTER_COMPAT
6529		error = ipf_out_compat(softc, &obj, ptr);
6530#else
6531		IPFERROR(65);
6532		error = EINVAL;
6533#endif
6534	}
6535	return error;
6536}
6537
6538
6539/* ------------------------------------------------------------------------ */
6540/* Function:    ipf_outobj                                                  */
6541/* Returns:     int     - 0 = success, else failure                         */
6542/* Parameters:  data(I) - pointer to ioctl data                             */
6543/*              ptr(I)  - pointer to store real data in                     */
6544/*              type(I) - type of structure being moved                     */
6545/*                                                                          */
6546/* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6547/* future, we add things to check for version numbers, sizes, etc, to make  */
6548/* it backward  compatible at the ABI for user land.                        */
6549/* ------------------------------------------------------------------------ */
6550int
6551ipf_outobj(softc, data, ptr, type)
6552	ipf_main_softc_t *softc;
6553	void *data;
6554	void *ptr;
6555	int type;
6556{
6557	ipfobj_t obj;
6558	int error;
6559
6560	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6561		IPFERROR(67);
6562		return EINVAL;
6563	}
6564
6565	error = BCOPYIN(data, &obj, sizeof(obj));
6566	if (error != 0) {
6567		IPFERROR(126);
6568		return EFAULT;
6569	}
6570
6571	if (obj.ipfo_type != type) {
6572		IPFERROR(68);
6573		return EINVAL;
6574	}
6575
6576	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6577		if ((ipf_objbytes[type][0] & 1) != 0) {
6578			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6579				IPFERROR(69);
6580				return EINVAL;
6581			}
6582		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6583			IPFERROR(70);
6584			return EINVAL;
6585		}
6586
6587		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6588		if (error != 0) {
6589			IPFERROR(73);
6590			error = EFAULT;
6591		}
6592	} else {
6593#ifdef	IPFILTER_COMPAT
6594		error = ipf_out_compat(softc, &obj, ptr);
6595#else
6596		IPFERROR(72);
6597		error = EINVAL;
6598#endif
6599	}
6600	return error;
6601}
6602
6603
6604/* ------------------------------------------------------------------------ */
6605/* Function:    ipf_outobjk                                                 */
6606/* Returns:     int     - 0 = success, else failure                         */
6607/* Parameters:  obj(I)  - pointer to data description structure             */
6608/*              ptr(I)  - pointer to kernel data to copy out                */
6609/*                                                                          */
6610/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6611/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6612/* already populated with information and now we just need to use it.       */
6613/* There is no need for this function to have a "type" parameter as there   */
6614/* is no point in validating information that comes from the kernel with    */
6615/* itself.                                                                  */
6616/* ------------------------------------------------------------------------ */
6617int
6618ipf_outobjk(softc, obj, ptr)
6619	ipf_main_softc_t *softc;
6620	ipfobj_t *obj;
6621	void *ptr;
6622{
6623	int type = obj->ipfo_type;
6624	int error;
6625
6626	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6627		IPFERROR(147);
6628		return EINVAL;
6629	}
6630
6631	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6632		if ((ipf_objbytes[type][0] & 1) != 0) {
6633			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6634				IPFERROR(148);
6635				return EINVAL;
6636			}
6637
6638		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6639			IPFERROR(149);
6640			return EINVAL;
6641		}
6642
6643		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6644		if (error != 0) {
6645			IPFERROR(150);
6646			error = EFAULT;
6647		}
6648	} else {
6649#ifdef  IPFILTER_COMPAT
6650		error = ipf_out_compat(softc, obj, ptr);
6651#else
6652		IPFERROR(151);
6653		error = EINVAL;
6654#endif
6655	}
6656	return error;
6657}
6658
6659
6660/* ------------------------------------------------------------------------ */
6661/* Function:    ipf_checkl4sum                                              */
6662/* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6663/* Parameters:  fin(I) - pointer to packet information                      */
6664/*                                                                          */
6665/* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6666/* not possible, return without indicating a failure or success but in a    */
6667/* way that is ditinguishable. This function should only be called by the   */
6668/* ipf_checkv6sum() for each platform.                                      */
6669/* ------------------------------------------------------------------------ */
6670INLINE int
6671ipf_checkl4sum(fin)
6672	fr_info_t *fin;
6673{
6674	u_short sum, hdrsum, *csump;
6675	udphdr_t *udp;
6676	int dosum;
6677
6678	/*
6679	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6680	 * isn't already considered "bad", then validate the checksum.  If
6681	 * this check fails then considered the packet to be "bad".
6682	 */
6683	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6684		return 1;
6685
6686	DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6687	if (fin->fin_out == 1) {
6688		fin->fin_cksum = FI_CK_SUMOK;
6689		return 0;
6690	}
6691
6692	csump = NULL;
6693	hdrsum = 0;
6694	dosum = 0;
6695	sum = 0;
6696
6697	switch (fin->fin_p)
6698	{
6699	case IPPROTO_TCP :
6700		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6701		dosum = 1;
6702		break;
6703
6704	case IPPROTO_UDP :
6705		udp = fin->fin_dp;
6706		if (udp->uh_sum != 0) {
6707			csump = &udp->uh_sum;
6708			dosum = 1;
6709		}
6710		break;
6711
6712#ifdef USE_INET6
6713	case IPPROTO_ICMPV6 :
6714		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6715		dosum = 1;
6716		break;
6717#endif
6718
6719	case IPPROTO_ICMP :
6720		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6721		dosum = 1;
6722		break;
6723
6724	default :
6725		return 1;
6726		/*NOTREACHED*/
6727	}
6728
6729	if (csump != NULL) {
6730		hdrsum = *csump;
6731		if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6732			hdrsum = 0x0000;
6733	}
6734
6735	if (dosum) {
6736		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6737	}
6738#if !defined(_KERNEL)
6739	if (sum == hdrsum) {
6740		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6741	} else {
6742		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6743	}
6744#endif
6745	DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6746#ifdef USE_INET6
6747	if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6748#else
6749	if (hdrsum == sum) {
6750#endif
6751		fin->fin_cksum = FI_CK_SUMOK;
6752		return 0;
6753	}
6754	fin->fin_cksum = FI_CK_BAD;
6755	return -1;
6756}
6757
6758
6759/* ------------------------------------------------------------------------ */
6760/* Function:    ipf_ifpfillv4addr                                           */
6761/* Returns:     int     - 0 = address update, -1 = address not updated      */
6762/* Parameters:  atype(I)   - type of network address update to perform      */
6763/*              sin(I)     - pointer to source of address information       */
6764/*              mask(I)    - pointer to source of netmask information       */
6765/*              inp(I)     - pointer to destination address store           */
6766/*              inpmask(I) - pointer to destination netmask store           */
6767/*                                                                          */
6768/* Given a type of network address update (atype) to perform, copy          */
6769/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6770/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6771/* which case the operation fails.  For all values of atype other than      */
6772/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6773/* value.                                                                   */
6774/* ------------------------------------------------------------------------ */
6775int
6776ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6777	int atype;
6778	struct sockaddr_in *sin, *mask;
6779	struct in_addr *inp, *inpmask;
6780{
6781	if (inpmask != NULL && atype != FRI_NETMASKED)
6782		inpmask->s_addr = 0xffffffff;
6783
6784	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6785		if (atype == FRI_NETMASKED) {
6786			if (inpmask == NULL)
6787				return -1;
6788			inpmask->s_addr = mask->sin_addr.s_addr;
6789		}
6790		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6791	} else {
6792		inp->s_addr = sin->sin_addr.s_addr;
6793	}
6794	return 0;
6795}
6796
6797
6798#ifdef	USE_INET6
6799/* ------------------------------------------------------------------------ */
6800/* Function:    ipf_ifpfillv6addr                                           */
6801/* Returns:     int     - 0 = address update, -1 = address not updated      */
6802/* Parameters:  atype(I)   - type of network address update to perform      */
6803/*              sin(I)     - pointer to source of address information       */
6804/*              mask(I)    - pointer to source of netmask information       */
6805/*              inp(I)     - pointer to destination address store           */
6806/*              inpmask(I) - pointer to destination netmask store           */
6807/*                                                                          */
6808/* Given a type of network address update (atype) to perform, copy          */
6809/* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6810/* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6811/* which case the operation fails.  For all values of atype other than      */
6812/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6813/* value.                                                                   */
6814/* ------------------------------------------------------------------------ */
6815int
6816ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6817	int atype;
6818	struct sockaddr_in6 *sin, *mask;
6819	i6addr_t *inp, *inpmask;
6820{
6821	i6addr_t *src, *and;
6822
6823	src = (i6addr_t *)&sin->sin6_addr;
6824	and = (i6addr_t *)&mask->sin6_addr;
6825
6826	if (inpmask != NULL && atype != FRI_NETMASKED) {
6827		inpmask->i6[0] = 0xffffffff;
6828		inpmask->i6[1] = 0xffffffff;
6829		inpmask->i6[2] = 0xffffffff;
6830		inpmask->i6[3] = 0xffffffff;
6831	}
6832
6833	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6834		if (atype == FRI_NETMASKED) {
6835			if (inpmask == NULL)
6836				return -1;
6837			inpmask->i6[0] = and->i6[0];
6838			inpmask->i6[1] = and->i6[1];
6839			inpmask->i6[2] = and->i6[2];
6840			inpmask->i6[3] = and->i6[3];
6841		}
6842
6843		inp->i6[0] = src->i6[0] & and->i6[0];
6844		inp->i6[1] = src->i6[1] & and->i6[1];
6845		inp->i6[2] = src->i6[2] & and->i6[2];
6846		inp->i6[3] = src->i6[3] & and->i6[3];
6847	} else {
6848		inp->i6[0] = src->i6[0];
6849		inp->i6[1] = src->i6[1];
6850		inp->i6[2] = src->i6[2];
6851		inp->i6[3] = src->i6[3];
6852	}
6853	return 0;
6854}
6855#endif
6856
6857
6858/* ------------------------------------------------------------------------ */
6859/* Function:    ipf_matchtag                                                */
6860/* Returns:     0 == mismatch, 1 == match.                                  */
6861/* Parameters:  tag1(I) - pointer to first tag to compare                   */
6862/*              tag2(I) - pointer to second tag to compare                  */
6863/*                                                                          */
6864/* Returns true (non-zero) or false(0) if the two tag structures can be     */
6865/* considered to be a match or not match, respectively.  The tag is 16      */
6866/* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6867/* compare the ints instead, for speed. tag1 is the master of the           */
6868/* comparison.  This function should only be called with both tag1 and tag2 */
6869/* as non-NULL pointers.                                                    */
6870/* ------------------------------------------------------------------------ */
6871int
6872ipf_matchtag(tag1, tag2)
6873	ipftag_t *tag1, *tag2;
6874{
6875	if (tag1 == tag2)
6876		return 1;
6877
6878	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6879		return 1;
6880
6881	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6882	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6883	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6884	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6885		return 1;
6886	return 0;
6887}
6888
6889
6890/* ------------------------------------------------------------------------ */
6891/* Function:    ipf_coalesce                                                */
6892/* Returns:     1 == success, -1 == failure, 0 == no change                 */
6893/* Parameters:  fin(I) - pointer to packet information                      */
6894/*                                                                          */
6895/* Attempt to get all of the packet data into a single, contiguous buffer.  */
6896/* If this call returns a failure then the buffers have also been freed.    */
6897/* ------------------------------------------------------------------------ */
6898int
6899ipf_coalesce(fin)
6900	fr_info_t *fin;
6901{
6902
6903	if ((fin->fin_flx & FI_COALESCE) != 0)
6904		return 1;
6905
6906	/*
6907	 * If the mbuf pointers indicate that there is no mbuf to work with,
6908	 * return but do not indicate success or failure.
6909	 */
6910	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6911		return 0;
6912
6913#if defined(_KERNEL)
6914	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6915		ipf_main_softc_t *softc = fin->fin_main_soft;
6916
6917		DT1(frb_coalesce, fr_info_t *, fin);
6918		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6919# ifdef MENTAT
6920		FREE_MB_T(*fin->fin_mp);
6921# endif
6922		fin->fin_reason = FRB_COALESCE;
6923		*fin->fin_mp = NULL;
6924		fin->fin_m = NULL;
6925		return -1;
6926	}
6927#else
6928	fin = fin;	/* LINT */
6929#endif
6930	return 1;
6931}
6932
6933
6934/*
6935 * The following table lists all of the tunable variables that can be
6936 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6937 * in the table below is as follows:
6938 *
6939 * pointer to value, name of value, minimum, maximum, size of the value's
6940 *     container, value attribute flags
6941 *
6942 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6943 * means the value can only be written to when IPFilter is loaded but disabled.
6944 * The obvious implication is if neither of these are set then the value can be
6945 * changed at any time without harm.
6946 */
6947
6948
6949/* ------------------------------------------------------------------------ */
6950/* Function:    ipf_tune_findbycookie                                       */
6951/* Returns:     NULL = search failed, else pointer to tune struct           */
6952/* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6953/*              next(O)   - pointer to place to store the cookie for the    */
6954/*                          "next" tuneable, if it is desired.              */
6955/*                                                                          */
6956/* This function is used to walk through all of the existing tunables with  */
6957/* successive calls.  It searches the known tunables for the one which has  */
6958/* a matching value for "cookie" - ie its address.  When returning a match, */
6959/* the next one to be found may be returned inside next.                    */
6960/* ------------------------------------------------------------------------ */
6961static ipftuneable_t *
6962ipf_tune_findbycookie(ptop, cookie, next)
6963	ipftuneable_t **ptop;
6964	void *cookie, **next;
6965{
6966	ipftuneable_t *ta, **tap;
6967
6968	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6969		if (ta == cookie) {
6970			if (next != NULL) {
6971				/*
6972				 * If the next entry in the array has a name
6973				 * present, then return a pointer to it for
6974				 * where to go next, else return a pointer to
6975				 * the dynaminc list as a key to search there
6976				 * next.  This facilitates a weak linking of
6977				 * the two "lists" together.
6978				 */
6979				if ((ta + 1)->ipft_name != NULL)
6980					*next = ta + 1;
6981				else
6982					*next = ptop;
6983			}
6984			return ta;
6985		}
6986
6987	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6988		if (tap == cookie) {
6989			if (next != NULL)
6990				*next = &ta->ipft_next;
6991			return ta;
6992		}
6993
6994	if (next != NULL)
6995		*next = NULL;
6996	return NULL;
6997}
6998
6999
7000/* ------------------------------------------------------------------------ */
7001/* Function:    ipf_tune_findbyname                                         */
7002/* Returns:     NULL = search failed, else pointer to tune struct           */
7003/* Parameters:  name(I) - name of the tuneable entry to find.               */
7004/*                                                                          */
7005/* Search the static array of tuneables and the list of dynamic tuneables   */
7006/* for an entry with a matching name.  If we can find one, return a pointer */
7007/* to the matching structure.                                               */
7008/* ------------------------------------------------------------------------ */
7009static ipftuneable_t *
7010ipf_tune_findbyname(top, name)
7011	ipftuneable_t *top;
7012	const char *name;
7013{
7014	ipftuneable_t *ta;
7015
7016	for (ta = top; ta != NULL; ta = ta->ipft_next)
7017		if (!strcmp(ta->ipft_name, name)) {
7018			return ta;
7019		}
7020
7021	return NULL;
7022}
7023
7024
7025/* ------------------------------------------------------------------------ */
7026/* Function:    ipf_tune_add_array                                          */
7027/* Returns:     int - 0 == success, else failure                            */
7028/* Parameters:  newtune - pointer to new tune array to add to tuneables     */
7029/*                                                                          */
7030/* Appends tune structures from the array passed in (newtune) to the end of */
7031/* the current list of "dynamic" tuneable parameters.                       */
7032/* If any entry to be added is already present (by name) then the operation */
7033/* is aborted - entries that have been added are removed before returning.  */
7034/* An entry with no name (NULL) is used as the indication that the end of   */
7035/* the array has been reached.                                              */
7036/* ------------------------------------------------------------------------ */
7037int
7038ipf_tune_add_array(softc, newtune)
7039	ipf_main_softc_t *softc;
7040	ipftuneable_t *newtune;
7041{
7042	ipftuneable_t *nt, *dt;
7043	int error = 0;
7044
7045	for (nt = newtune; nt->ipft_name != NULL; nt++) {
7046		error = ipf_tune_add(softc, nt);
7047		if (error != 0) {
7048			for (dt = newtune; dt != nt; dt++) {
7049				(void) ipf_tune_del(softc, dt);
7050			}
7051		}
7052	}
7053
7054	return error;
7055}
7056
7057
7058/* ------------------------------------------------------------------------ */
7059/* Function:    ipf_tune_array_link                                         */
7060/* Returns:     0 == success, -1 == failure                                 */
7061/* Parameters:  softc(I) - soft context pointerto work with                 */
7062/*              array(I) - pointer to an array of tuneables                 */
7063/*                                                                          */
7064/* Given an array of tunables (array), append them to the current list of   */
7065/* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7066/* the array for being appended to the list, initialise all of the next     */
7067/* pointers so we don't need to walk parts of it with ++ and others with    */
7068/* next. The array is expected to have an entry with a NULL name as the     */
7069/* terminator. Trying to add an array with no non-NULL names will return as */
7070/* a failure.                                                               */
7071/* ------------------------------------------------------------------------ */
7072int
7073ipf_tune_array_link(softc, array)
7074	ipf_main_softc_t *softc;
7075	ipftuneable_t *array;
7076{
7077	ipftuneable_t *t, **p;
7078
7079	t = array;
7080	if (t->ipft_name == NULL)
7081		return -1;
7082
7083	for (; t[1].ipft_name != NULL; t++)
7084		t[0].ipft_next = &t[1];
7085	t->ipft_next = NULL;
7086
7087	/*
7088	 * Since a pointer to the last entry isn't kept, we need to find it
7089	 * each time we want to add new variables to the list.
7090	 */
7091	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7092		if (t->ipft_name == NULL)
7093			break;
7094	*p = array;
7095
7096	return 0;
7097}
7098
7099
7100/* ------------------------------------------------------------------------ */
7101/* Function:    ipf_tune_array_unlink                                       */
7102/* Returns:     0 == success, -1 == failure                                 */
7103/* Parameters:  softc(I) - soft context pointerto work with                 */
7104/*              array(I) - pointer to an array of tuneables                 */
7105/*                                                                          */
7106/* ------------------------------------------------------------------------ */
7107int
7108ipf_tune_array_unlink(softc, array)
7109	ipf_main_softc_t *softc;
7110	ipftuneable_t *array;
7111{
7112	ipftuneable_t *t, **p;
7113
7114	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7115		if (t == array)
7116			break;
7117	if (t == NULL)
7118		return -1;
7119
7120	for (; t[1].ipft_name != NULL; t++)
7121		;
7122
7123	*p = t->ipft_next;
7124
7125	return 0;
7126}
7127
7128
7129/* ------------------------------------------------------------------------ */
7130/* Function:   ipf_tune_array_copy                                          */
7131/* Returns:    NULL = failure, else pointer to new array                    */
7132/* Parameters: base(I)     - pointer to structure base                      */
7133/*             size(I)     - size of the array at template                  */
7134/*             template(I) - original array to copy                         */
7135/*                                                                          */
7136/* Allocate memory for a new set of tuneable values and copy everything     */
7137/* from template into the new region of memory.  The new region is full of  */
7138/* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7139/*                                                                          */
7140/* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7141/* In the array template, ipftp_offset is the offset (in bytes) of the      */
7142/* location of the tuneable value inside the structure pointed to by base.  */
7143/* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7144/* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7145/* ipftp_void that points to the stored value.                              */
7146/* ------------------------------------------------------------------------ */
7147ipftuneable_t *
7148ipf_tune_array_copy(base, size, template)
7149	void *base;
7150	size_t size;
7151	ipftuneable_t *template;
7152{
7153	ipftuneable_t *copy;
7154	int i;
7155
7156
7157	KMALLOCS(copy, ipftuneable_t *, size);
7158	if (copy == NULL) {
7159		return NULL;
7160	}
7161	bcopy(template, copy, size);
7162
7163	for (i = 0; copy[i].ipft_name; i++) {
7164		copy[i].ipft_una.ipftp_offset += (u_long)base;
7165		copy[i].ipft_next = copy + i + 1;
7166	}
7167
7168	return copy;
7169}
7170
7171
7172/* ------------------------------------------------------------------------ */
7173/* Function:    ipf_tune_add                                                */
7174/* Returns:     int - 0 == success, else failure                            */
7175/* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7176/*                                                                          */
7177/* Appends tune structures from the array passed in (newtune) to the end of */
7178/* the current list of "dynamic" tuneable parameters.  Once added, the      */
7179/* owner of the object is not expected to ever change "ipft_next".          */
7180/* ------------------------------------------------------------------------ */
7181int
7182ipf_tune_add(softc, newtune)
7183	ipf_main_softc_t *softc;
7184	ipftuneable_t *newtune;
7185{
7186	ipftuneable_t *ta, **tap;
7187
7188	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7189	if (ta != NULL) {
7190		IPFERROR(74);
7191		return EEXIST;
7192	}
7193
7194	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7195		;
7196
7197	newtune->ipft_next = NULL;
7198	*tap = newtune;
7199	return 0;
7200}
7201
7202
7203/* ------------------------------------------------------------------------ */
7204/* Function:    ipf_tune_del                                                */
7205/* Returns:     int - 0 == success, else failure                            */
7206/* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7207/*                        current dynamic tuneables                         */
7208/*                                                                          */
7209/* Search for the tune structure, by pointer, in the list of those that are */
7210/* dynamically added at run time.  If found, adjust the list so that this   */
7211/* structure is no longer part of it.                                       */
7212/* ------------------------------------------------------------------------ */
7213int
7214ipf_tune_del(softc, oldtune)
7215	ipf_main_softc_t *softc;
7216	ipftuneable_t *oldtune;
7217{
7218	ipftuneable_t *ta, **tap;
7219	int error = 0;
7220
7221	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7222	     tap = &ta->ipft_next) {
7223		if (ta == oldtune) {
7224			*tap = oldtune->ipft_next;
7225			oldtune->ipft_next = NULL;
7226			break;
7227		}
7228	}
7229
7230	if (ta == NULL) {
7231		error = ESRCH;
7232		IPFERROR(75);
7233	}
7234	return error;
7235}
7236
7237
7238/* ------------------------------------------------------------------------ */
7239/* Function:    ipf_tune_del_array                                          */
7240/* Returns:     int - 0 == success, else failure                            */
7241/* Parameters:  oldtune - pointer to tuneables array                        */
7242/*                                                                          */
7243/* Remove each tuneable entry in the array from the list of "dynamic"       */
7244/* tunables.  If one entry should fail to be found, an error will be        */
7245/* returned and no further ones removed.                                    */
7246/* An entry with a NULL name is used as the indicator of the last entry in  */
7247/* the array.                                                               */
7248/* ------------------------------------------------------------------------ */
7249int
7250ipf_tune_del_array(softc, oldtune)
7251	ipf_main_softc_t *softc;
7252	ipftuneable_t *oldtune;
7253{
7254	ipftuneable_t *ot;
7255	int error = 0;
7256
7257	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7258		error = ipf_tune_del(softc, ot);
7259		if (error != 0)
7260			break;
7261	}
7262
7263	return error;
7264
7265}
7266
7267
7268/* ------------------------------------------------------------------------ */
7269/* Function:    ipf_tune                                                    */
7270/* Returns:     int - 0 == success, else failure                            */
7271/* Parameters:  cmd(I)  - ioctl command number                              */
7272/*              data(I) - pointer to ioctl data structure                   */
7273/*                                                                          */
7274/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7275/* three ioctls provide the means to access and control global variables    */
7276/* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7277/* changed without rebooting, reloading or recompiling.  The initialisation */
7278/* and 'destruction' routines of the various components of ipfilter are all */
7279/* each responsible for handling their own values being too big.            */
7280/* ------------------------------------------------------------------------ */
7281int
7282ipf_ipftune(softc, cmd, data)
7283	ipf_main_softc_t *softc;
7284	ioctlcmd_t cmd;
7285	void *data;
7286{
7287	ipftuneable_t *ta;
7288	ipftune_t tu;
7289	void *cookie;
7290	int error;
7291
7292	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7293	if (error != 0)
7294		return error;
7295
7296	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7297	cookie = tu.ipft_cookie;
7298	ta = NULL;
7299
7300	switch (cmd)
7301	{
7302	case SIOCIPFGETNEXT :
7303		/*
7304		 * If cookie is non-NULL, assume it to be a pointer to the last
7305		 * entry we looked at, so find it (if possible) and return a
7306		 * pointer to the next one after it.  The last entry in the
7307		 * the table is a NULL entry, so when we get to it, set cookie
7308		 * to NULL and return that, indicating end of list, erstwhile
7309		 * if we come in with cookie set to NULL, we are starting anew
7310		 * at the front of the list.
7311		 */
7312		if (cookie != NULL) {
7313			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7314						   cookie, &tu.ipft_cookie);
7315		} else {
7316			ta = softc->ipf_tuners;
7317			tu.ipft_cookie = ta + 1;
7318		}
7319		if (ta != NULL) {
7320			/*
7321			 * Entry found, but does the data pointed to by that
7322			 * row fit in what we can return?
7323			 */
7324			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7325				IPFERROR(76);
7326				return EINVAL;
7327			}
7328
7329			tu.ipft_vlong = 0;
7330			if (ta->ipft_sz == sizeof(u_long))
7331				tu.ipft_vlong = *ta->ipft_plong;
7332			else if (ta->ipft_sz == sizeof(u_int))
7333				tu.ipft_vint = *ta->ipft_pint;
7334			else if (ta->ipft_sz == sizeof(u_short))
7335				tu.ipft_vshort = *ta->ipft_pshort;
7336			else if (ta->ipft_sz == sizeof(u_char))
7337				tu.ipft_vchar = *ta->ipft_pchar;
7338
7339			tu.ipft_sz = ta->ipft_sz;
7340			tu.ipft_min = ta->ipft_min;
7341			tu.ipft_max = ta->ipft_max;
7342			tu.ipft_flags = ta->ipft_flags;
7343			bcopy(ta->ipft_name, tu.ipft_name,
7344			      MIN(sizeof(tu.ipft_name),
7345				  strlen(ta->ipft_name) + 1));
7346		}
7347		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7348		break;
7349
7350	case SIOCIPFGET :
7351	case SIOCIPFSET :
7352		/*
7353		 * Search by name or by cookie value for a particular entry
7354		 * in the tuning paramter table.
7355		 */
7356		IPFERROR(77);
7357		error = ESRCH;
7358		if (cookie != NULL) {
7359			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7360						   cookie, NULL);
7361			if (ta != NULL)
7362				error = 0;
7363		} else if (tu.ipft_name[0] != '\0') {
7364			ta = ipf_tune_findbyname(softc->ipf_tuners,
7365						 tu.ipft_name);
7366			if (ta != NULL)
7367				error = 0;
7368		}
7369		if (error != 0)
7370			break;
7371
7372		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7373			/*
7374			 * Fetch the tuning parameters for a particular value
7375			 */
7376			tu.ipft_vlong = 0;
7377			if (ta->ipft_sz == sizeof(u_long))
7378				tu.ipft_vlong = *ta->ipft_plong;
7379			else if (ta->ipft_sz == sizeof(u_int))
7380				tu.ipft_vint = *ta->ipft_pint;
7381			else if (ta->ipft_sz == sizeof(u_short))
7382				tu.ipft_vshort = *ta->ipft_pshort;
7383			else if (ta->ipft_sz == sizeof(u_char))
7384				tu.ipft_vchar = *ta->ipft_pchar;
7385			tu.ipft_cookie = ta;
7386			tu.ipft_sz = ta->ipft_sz;
7387			tu.ipft_min = ta->ipft_min;
7388			tu.ipft_max = ta->ipft_max;
7389			tu.ipft_flags = ta->ipft_flags;
7390			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7391
7392		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7393			/*
7394			 * Set an internal parameter.  The hard part here is
7395			 * getting the new value safely and correctly out of
7396			 * the kernel (given we only know its size, not type.)
7397			 */
7398			u_long in;
7399
7400			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7401			    (softc->ipf_running > 0)) {
7402				IPFERROR(78);
7403				error = EBUSY;
7404				break;
7405			}
7406
7407			in = tu.ipft_vlong;
7408			if (in < ta->ipft_min || in > ta->ipft_max) {
7409				IPFERROR(79);
7410				error = EINVAL;
7411				break;
7412			}
7413
7414			if (ta->ipft_func != NULL) {
7415				SPL_INT(s);
7416
7417				SPL_NET(s);
7418				error = (*ta->ipft_func)(softc, ta,
7419							 &tu.ipft_un);
7420				SPL_X(s);
7421
7422			} else if (ta->ipft_sz == sizeof(u_long)) {
7423				tu.ipft_vlong = *ta->ipft_plong;
7424				*ta->ipft_plong = in;
7425
7426			} else if (ta->ipft_sz == sizeof(u_int)) {
7427				tu.ipft_vint = *ta->ipft_pint;
7428				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7429
7430			} else if (ta->ipft_sz == sizeof(u_short)) {
7431				tu.ipft_vshort = *ta->ipft_pshort;
7432				*ta->ipft_pshort = (u_short)(in & 0xffff);
7433
7434			} else if (ta->ipft_sz == sizeof(u_char)) {
7435				tu.ipft_vchar = *ta->ipft_pchar;
7436				*ta->ipft_pchar = (u_char)(in & 0xff);
7437			}
7438			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7439		}
7440		break;
7441
7442	default :
7443		IPFERROR(80);
7444		error = EINVAL;
7445		break;
7446	}
7447
7448	return error;
7449}
7450
7451
7452/* ------------------------------------------------------------------------ */
7453/* Function:    ipf_zerostats                                               */
7454/* Returns:     int - 0 = success, else failure                             */
7455/* Parameters:  data(O) - pointer to pointer for copying data back to       */
7456/*                                                                          */
7457/* Copies the current statistics out to userspace and then zero's the       */
7458/* current ones in the kernel. The lock is only held across the bzero() as  */
7459/* the copyout may result in paging (ie network activity.)                  */
7460/* ------------------------------------------------------------------------ */
7461int
7462ipf_zerostats(softc, data)
7463	ipf_main_softc_t *softc;
7464	caddr_t	data;
7465{
7466	friostat_t fio;
7467	ipfobj_t obj;
7468	int error;
7469
7470	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7471	if (error != 0)
7472		return error;
7473	ipf_getstat(softc, &fio, obj.ipfo_rev);
7474	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7475	if (error != 0)
7476		return error;
7477
7478	WRITE_ENTER(&softc->ipf_mutex);
7479	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7480	RWLOCK_EXIT(&softc->ipf_mutex);
7481
7482	return 0;
7483}
7484
7485
7486/* ------------------------------------------------------------------------ */
7487/* Function:    ipf_resolvedest                                             */
7488/* Returns:     Nil                                                         */
7489/* Parameters:  softc(I) - pointer to soft context main structure           */
7490/*              base(I)  - where strings are stored                         */
7491/*              fdp(IO)  - pointer to destination information to resolve    */
7492/*              v(I)     - IP protocol version to match                     */
7493/*                                                                          */
7494/* Looks up an interface name in the frdest structure pointed to by fdp and */
7495/* if a matching name can be found for the particular IP protocol version   */
7496/* then store the interface pointer in the frdest struct.  If no match is   */
7497/* found, then set the interface pointer to be -1 as NULL is considered to  */
7498/* indicate there is no information at all in the structure.                */
7499/* ------------------------------------------------------------------------ */
7500int
7501ipf_resolvedest(softc, base, fdp, v)
7502	ipf_main_softc_t *softc;
7503	char *base;
7504	frdest_t *fdp;
7505	int v;
7506{
7507	int errval = 0;
7508	void *ifp;
7509
7510	ifp = NULL;
7511
7512	if (fdp->fd_name != -1) {
7513		if (fdp->fd_type == FRD_DSTLIST) {
7514			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7515						  IPLT_DSTLIST,
7516						  base + fdp->fd_name,
7517						  NULL);
7518			if (ifp == NULL) {
7519				IPFERROR(144);
7520				errval = ESRCH;
7521			}
7522		} else {
7523			ifp = GETIFP(base + fdp->fd_name, v);
7524			if (ifp == NULL)
7525				ifp = (void *)-1;
7526		}
7527	}
7528	fdp->fd_ptr = ifp;
7529
7530	return errval;
7531}
7532
7533
7534/* ------------------------------------------------------------------------ */
7535/* Function:    ipf_resolvenic                                              */
7536/* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7537/*                      pointer to interface structure for NIC              */
7538/* Parameters:  softc(I)- pointer to soft context main structure            */
7539/*              name(I) - complete interface name                           */
7540/*              v(I)    - IP protocol version                               */
7541/*                                                                          */
7542/* Look for a network interface structure that firstly has a matching name  */
7543/* to that passed in and that is also being used for that IP protocol       */
7544/* version (necessary on some platforms where there are separate listings   */
7545/* for both IPv4 and IPv6 on the same physical NIC.                         */
7546/* ------------------------------------------------------------------------ */
7547void *
7548ipf_resolvenic(softc, name, v)
7549	ipf_main_softc_t *softc;
7550	char *name;
7551	int v;
7552{
7553	void *nic;
7554
7555	softc = softc;	/* gcc -Wextra */
7556	if (name[0] == '\0')
7557		return NULL;
7558
7559	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7560		return NULL;
7561	}
7562
7563	nic = GETIFP(name, v);
7564	if (nic == NULL)
7565		nic = (void *)-1;
7566	return nic;
7567}
7568
7569
7570/* ------------------------------------------------------------------------ */
7571/* Function:    ipf_token_expire                                            */
7572/* Returns:     None.                                                       */
7573/* Parameters:  softc(I) - pointer to soft context main structure           */
7574/*                                                                          */
7575/* This function is run every ipf tick to see if there are any tokens that  */
7576/* have been held for too long and need to be freed up.                     */
7577/* ------------------------------------------------------------------------ */
7578void
7579ipf_token_expire(softc)
7580	ipf_main_softc_t *softc;
7581{
7582	ipftoken_t *it;
7583
7584	WRITE_ENTER(&softc->ipf_tokens);
7585	while ((it = softc->ipf_token_head) != NULL) {
7586		if (it->ipt_die > softc->ipf_ticks)
7587			break;
7588
7589		ipf_token_deref(softc, it);
7590	}
7591	RWLOCK_EXIT(&softc->ipf_tokens);
7592}
7593
7594
7595/* ------------------------------------------------------------------------ */
7596/* Function:    ipf_token_flush                                             */
7597/* Returns:     None.                                                       */
7598/* Parameters:  softc(I) - pointer to soft context main structure           */
7599/*                                                                          */
7600/* Loop through all of the existing tokens and call deref to see if they    */
7601/* can be freed. Normally a function like this might just loop on           */
7602/* ipf_token_head but there is a chance that a token might have a ref count */
7603/* of greater than one and in that case the the reference would drop twice  */
7604/* by code that is only entitled to drop it once.                           */
7605/* ------------------------------------------------------------------------ */
7606static void
7607ipf_token_flush(softc)
7608	ipf_main_softc_t *softc;
7609{
7610	ipftoken_t *it, *next;
7611
7612	WRITE_ENTER(&softc->ipf_tokens);
7613	for (it = softc->ipf_token_head; it != NULL; it = next) {
7614		next = it->ipt_next;
7615		(void) ipf_token_deref(softc, it);
7616	}
7617	RWLOCK_EXIT(&softc->ipf_tokens);
7618}
7619
7620
7621/* ------------------------------------------------------------------------ */
7622/* Function:    ipf_token_del                                               */
7623/* Returns:     int     - 0 = success, else error                           */
7624/* Parameters:  softc(I)- pointer to soft context main structure            */
7625/*              type(I) - the token type to match                           */
7626/*              uid(I)  - uid owning the token                              */
7627/*              ptr(I)  - context pointer for the token                     */
7628/*                                                                          */
7629/* This function looks for a a token in the current list that matches up    */
7630/* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7631/* call ipf_token_dewref() to remove it from the list. In the event that    */
7632/* the token has a reference held elsewhere, setting ipt_complete to 2      */
7633/* enables debugging to distinguish between the two paths that ultimately   */
7634/* lead to a token to be deleted.                                           */
7635/* ------------------------------------------------------------------------ */
7636int
7637ipf_token_del(softc, type, uid, ptr)
7638	ipf_main_softc_t *softc;
7639	int type, uid;
7640	void *ptr;
7641{
7642	ipftoken_t *it;
7643	int error;
7644
7645	IPFERROR(82);
7646	error = ESRCH;
7647
7648	WRITE_ENTER(&softc->ipf_tokens);
7649	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7650		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7651		    uid == it->ipt_uid) {
7652			it->ipt_complete = 2;
7653			ipf_token_deref(softc, it);
7654			error = 0;
7655			break;
7656		}
7657	}
7658	RWLOCK_EXIT(&softc->ipf_tokens);
7659
7660	return error;
7661}
7662
7663
7664/* ------------------------------------------------------------------------ */
7665/* Function:    ipf_token_mark_complete                                     */
7666/* Returns:     None.                                                       */
7667/* Parameters:  token(I) - pointer to token structure                       */
7668/*                                                                          */
7669/* Mark a token as being ineligable for being found with ipf_token_find.    */
7670/* ------------------------------------------------------------------------ */
7671void
7672ipf_token_mark_complete(token)
7673	ipftoken_t *token;
7674{
7675	if (token->ipt_complete == 0)
7676		token->ipt_complete = 1;
7677}
7678
7679
7680/* ------------------------------------------------------------------------ */
7681/* Function:    ipf_token_find                                               */
7682/* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7683/* Parameters:  softc(I)- pointer to soft context main structure            */
7684/*              type(I) - the token type to match                           */
7685/*              uid(I)  - uid owning the token                              */
7686/*              ptr(I)  - context pointer for the token                     */
7687/*                                                                          */
7688/* This function looks for a live token in the list of current tokens that  */
7689/* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7690/* allocated.  If one is found then it is moved to the top of the list of   */
7691/* currently active tokens.                                                 */
7692/* ------------------------------------------------------------------------ */
7693ipftoken_t *
7694ipf_token_find(softc, type, uid, ptr)
7695	ipf_main_softc_t *softc;
7696	int type, uid;
7697	void *ptr;
7698{
7699	ipftoken_t *it, *new;
7700
7701	KMALLOC(new, ipftoken_t *);
7702	if (new != NULL)
7703		bzero((char *)new, sizeof(*new));
7704
7705	WRITE_ENTER(&softc->ipf_tokens);
7706	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7707		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7708		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7709			break;
7710	}
7711
7712	if (it == NULL) {
7713		it = new;
7714		new = NULL;
7715		if (it == NULL) {
7716			RWLOCK_EXIT(&softc->ipf_tokens);
7717			return NULL;
7718		}
7719		it->ipt_ctx = ptr;
7720		it->ipt_uid = uid;
7721		it->ipt_type = type;
7722		it->ipt_ref = 1;
7723	} else {
7724		if (new != NULL) {
7725			KFREE(new);
7726			new = NULL;
7727		}
7728
7729		if (it->ipt_complete > 0)
7730			it = NULL;
7731		else
7732			ipf_token_unlink(softc, it);
7733	}
7734
7735	if (it != NULL) {
7736		it->ipt_pnext = softc->ipf_token_tail;
7737		*softc->ipf_token_tail = it;
7738		softc->ipf_token_tail = &it->ipt_next;
7739		it->ipt_next = NULL;
7740		it->ipt_ref++;
7741
7742		it->ipt_die = softc->ipf_ticks + 20;
7743	}
7744
7745	RWLOCK_EXIT(&softc->ipf_tokens);
7746
7747	return it;
7748}
7749
7750
7751/* ------------------------------------------------------------------------ */
7752/* Function:    ipf_token_unlink                                            */
7753/* Returns:     None.                                                       */
7754/* Parameters:  softc(I) - pointer to soft context main structure           */
7755/*              token(I) - pointer to token structure                       */
7756/* Write Locks: ipf_tokens                                                  */
7757/*                                                                          */
7758/* This function unlinks a token structure from the linked list of tokens   */
7759/* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7760/* but the tail does due to the linked list implementation.                 */
7761/* ------------------------------------------------------------------------ */
7762static void
7763ipf_token_unlink(softc, token)
7764	ipf_main_softc_t *softc;
7765	ipftoken_t *token;
7766{
7767
7768	if (softc->ipf_token_tail == &token->ipt_next)
7769		softc->ipf_token_tail = token->ipt_pnext;
7770
7771	*token->ipt_pnext = token->ipt_next;
7772	if (token->ipt_next != NULL)
7773		token->ipt_next->ipt_pnext = token->ipt_pnext;
7774	token->ipt_next = NULL;
7775	token->ipt_pnext = NULL;
7776}
7777
7778
7779/* ------------------------------------------------------------------------ */
7780/* Function:    ipf_token_deref                                             */
7781/* Returns:     int      - 0 == token freed, else reference count           */
7782/* Parameters:  softc(I) - pointer to soft context main structure           */
7783/*              token(I) - pointer to token structure                       */
7784/* Write Locks: ipf_tokens                                                  */
7785/*                                                                          */
7786/* Drop the reference count on the token structure and if it drops to zero, */
7787/* call the dereference function for the token type because it is then      */
7788/* possible to free the token data structure.                               */
7789/* ------------------------------------------------------------------------ */
7790int
7791ipf_token_deref(softc, token)
7792	ipf_main_softc_t *softc;
7793	ipftoken_t *token;
7794{
7795	void *data, **datap;
7796
7797	ASSERT(token->ipt_ref > 0);
7798	token->ipt_ref--;
7799	if (token->ipt_ref > 0)
7800		return token->ipt_ref;
7801
7802	data = token->ipt_data;
7803	datap = &data;
7804
7805	if ((data != NULL) && (data != (void *)-1)) {
7806		switch (token->ipt_type)
7807		{
7808		case IPFGENITER_IPF :
7809			(void) ipf_derefrule(softc, (frentry_t **)datap);
7810			break;
7811		case IPFGENITER_IPNAT :
7812			WRITE_ENTER(&softc->ipf_nat);
7813			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7814			RWLOCK_EXIT(&softc->ipf_nat);
7815			break;
7816		case IPFGENITER_NAT :
7817			ipf_nat_deref(softc, (nat_t **)datap);
7818			break;
7819		case IPFGENITER_STATE :
7820			ipf_state_deref(softc, (ipstate_t **)datap);
7821			break;
7822		case IPFGENITER_FRAG :
7823			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7824			break;
7825		case IPFGENITER_NATFRAG :
7826			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7827			break;
7828		case IPFGENITER_HOSTMAP :
7829			WRITE_ENTER(&softc->ipf_nat);
7830			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7831			RWLOCK_EXIT(&softc->ipf_nat);
7832			break;
7833		default :
7834			ipf_lookup_iterderef(softc, token->ipt_type, data);
7835			break;
7836		}
7837	}
7838
7839	ipf_token_unlink(softc, token);
7840	KFREE(token);
7841	return 0;
7842}
7843
7844
7845/* ------------------------------------------------------------------------ */
7846/* Function:    ipf_nextrule                                                */
7847/* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7848/* Parameters:  softc(I)    - pointer to soft context main structure        */
7849/*              fr(I)       - pointer to filter rule                        */
7850/*              out(I)      - 1 == out rules, 0 == input rules              */
7851/*                                                                          */
7852/* Starting with "fr", find the next rule to visit. This includes visiting  */
7853/* the list of rule groups if either fr is NULL (empty list) or it is the   */
7854/* last rule in the list. When walking rule lists, it is either input or    */
7855/* output rules that are returned, never both.                              */
7856/* ------------------------------------------------------------------------ */
7857static frentry_t *
7858ipf_nextrule(softc, active, unit, fr, out)
7859	ipf_main_softc_t *softc;
7860	int active, unit;
7861	frentry_t *fr;
7862	int out;
7863{
7864	frentry_t *next;
7865	frgroup_t *fg;
7866
7867	if (fr != NULL && fr->fr_group != -1) {
7868		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7869				   unit, active, NULL);
7870		if (fg != NULL)
7871			fg = fg->fg_next;
7872	} else {
7873		fg = softc->ipf_groups[unit][active];
7874	}
7875
7876	while (fg != NULL) {
7877		next = fg->fg_start;
7878		while (next != NULL) {
7879			if (out) {
7880				if (next->fr_flags & FR_OUTQUE)
7881					return next;
7882			} else if (next->fr_flags & FR_INQUE) {
7883				return next;
7884			}
7885			next = next->fr_next;
7886		}
7887		if (next == NULL)
7888			fg = fg->fg_next;
7889	}
7890
7891	return NULL;
7892}
7893
7894/* ------------------------------------------------------------------------ */
7895/* Function:    ipf_getnextrule                                             */
7896/* Returns:     int - 0 = success, else error                               */
7897/* Parameters:  softc(I)- pointer to soft context main structure            */
7898/*              t(I)   - pointer to destination information to resolve      */
7899/*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7900/*                                                                          */
7901/* This function's first job is to bring in the ipfruleiter_t structure via */
7902/* the ipfobj_t structure to determine what should be the next rule to      */
7903/* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7904/* find the 'next rule'.  This may include searching rule group lists or    */
7905/* just be as simple as looking at the 'next' field in the rule structure.  */
7906/* When we have found the rule to return, increase its reference count and  */
7907/* if we used an existing rule to get here, decrease its reference count.   */
7908/* ------------------------------------------------------------------------ */
7909int
7910ipf_getnextrule(softc, t, ptr)
7911	ipf_main_softc_t *softc;
7912	ipftoken_t *t;
7913	void *ptr;
7914{
7915	frentry_t *fr, *next, zero;
7916	ipfruleiter_t it;
7917	int error, out;
7918	frgroup_t *fg;
7919	ipfobj_t obj;
7920	int predict;
7921	char *dst;
7922	int unit;
7923
7924	if (t == NULL || ptr == NULL) {
7925		IPFERROR(84);
7926		return EFAULT;
7927	}
7928
7929	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7930	if (error != 0)
7931		return error;
7932
7933	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7934		IPFERROR(85);
7935		return EINVAL;
7936	}
7937	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7938		IPFERROR(86);
7939		return EINVAL;
7940	}
7941	if (it.iri_nrules == 0) {
7942		IPFERROR(87);
7943		return ENOSPC;
7944	}
7945	if (it.iri_rule == NULL) {
7946		IPFERROR(88);
7947		return EFAULT;
7948	}
7949
7950	fg = NULL;
7951	fr = t->ipt_data;
7952	if ((it.iri_inout & F_OUT) != 0)
7953		out = 1;
7954	else
7955		out = 0;
7956	if ((it.iri_inout & F_ACIN) != 0)
7957		unit = IPL_LOGCOUNT;
7958	else
7959		unit = IPL_LOGIPF;
7960
7961	READ_ENTER(&softc->ipf_mutex);
7962	if (fr == NULL) {
7963		if (*it.iri_group == '\0') {
7964			if (unit == IPL_LOGCOUNT) {
7965				next = softc->ipf_acct[out][it.iri_active];
7966			} else {
7967				next = softc->ipf_rules[out][it.iri_active];
7968			}
7969			if (next == NULL)
7970				next = ipf_nextrule(softc, it.iri_active,
7971						    unit, NULL, out);
7972		} else {
7973			fg = ipf_findgroup(softc, it.iri_group, unit,
7974					   it.iri_active, NULL);
7975			if (fg != NULL)
7976				next = fg->fg_start;
7977			else
7978				next = NULL;
7979		}
7980	} else {
7981		next = fr->fr_next;
7982		if (next == NULL)
7983			next = ipf_nextrule(softc, it.iri_active, unit,
7984					    fr, out);
7985	}
7986
7987	if (next != NULL && next->fr_next != NULL)
7988		predict = 1;
7989	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7990		predict = 1;
7991	else
7992		predict = 0;
7993
7994	if (fr != NULL)
7995		(void) ipf_derefrule(softc, &fr);
7996
7997	obj.ipfo_type = IPFOBJ_FRENTRY;
7998	dst = (char *)it.iri_rule;
7999
8000	if (next != NULL) {
8001		obj.ipfo_size = next->fr_size;
8002		MUTEX_ENTER(&next->fr_lock);
8003		next->fr_ref++;
8004		MUTEX_EXIT(&next->fr_lock);
8005		t->ipt_data = next;
8006	} else {
8007		obj.ipfo_size = sizeof(frentry_t);
8008		bzero(&zero, sizeof(zero));
8009		next = &zero;
8010		t->ipt_data = NULL;
8011	}
8012	it.iri_rule = predict ? next : NULL;
8013	if (predict == 0)
8014		ipf_token_mark_complete(t);
8015
8016	RWLOCK_EXIT(&softc->ipf_mutex);
8017
8018	obj.ipfo_ptr = dst;
8019	error = ipf_outobjk(softc, &obj, next);
8020	if (error == 0 && t->ipt_data != NULL) {
8021		dst += obj.ipfo_size;
8022		if (next->fr_data != NULL) {
8023			ipfobj_t dobj;
8024
8025			if (next->fr_type == FR_T_IPFEXPR)
8026				dobj.ipfo_type = IPFOBJ_IPFEXPR;
8027			else
8028				dobj.ipfo_type = IPFOBJ_FRIPF;
8029			dobj.ipfo_size = next->fr_dsize;
8030			dobj.ipfo_rev = obj.ipfo_rev;
8031			dobj.ipfo_ptr = dst;
8032			error = ipf_outobjk(softc, &dobj, next->fr_data);
8033		}
8034	}
8035
8036	if ((fr != NULL) && (next == &zero))
8037		(void) ipf_derefrule(softc, &fr);
8038
8039	return error;
8040}
8041
8042
8043/* ------------------------------------------------------------------------ */
8044/* Function:    ipf_frruleiter                                              */
8045/* Returns:     int - 0 = success, else error                               */
8046/* Parameters:  softc(I)- pointer to soft context main structure            */
8047/*              data(I) - the token type to match                           */
8048/*              uid(I)  - uid owning the token                              */
8049/*              ptr(I)  - context pointer for the token                     */
8050/*                                                                          */
8051/* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8052/* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8053/* the process doing the ioctl and use that to ask for the next rule.       */
8054/* ------------------------------------------------------------------------ */
8055static int
8056ipf_frruleiter(softc, data, uid, ctx)
8057	ipf_main_softc_t *softc;
8058	void *data, *ctx;
8059	int uid;
8060{
8061	ipftoken_t *token;
8062	ipfruleiter_t it;
8063	ipfobj_t obj;
8064	int error;
8065
8066	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8067	if (token != NULL) {
8068		error = ipf_getnextrule(softc, token, data);
8069		WRITE_ENTER(&softc->ipf_tokens);
8070		ipf_token_deref(softc, token);
8071		RWLOCK_EXIT(&softc->ipf_tokens);
8072	} else {
8073		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8074		if (error != 0)
8075			return error;
8076		it.iri_rule = NULL;
8077		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8078	}
8079
8080	return error;
8081}
8082
8083
8084/* ------------------------------------------------------------------------ */
8085/* Function:    ipf_geniter                                                 */
8086/* Returns:     int - 0 = success, else error                               */
8087/* Parameters:  softc(I) - pointer to soft context main structure           */
8088/*              token(I) - pointer to ipftoken_t structure                  */
8089/*              itp(I)   - pointer to iterator data                         */
8090/*                                                                          */
8091/* Decide which iterator function to call using information passed through  */
8092/* the ipfgeniter_t structure at itp.                                       */
8093/* ------------------------------------------------------------------------ */
8094static int
8095ipf_geniter(softc, token, itp)
8096	ipf_main_softc_t *softc;
8097	ipftoken_t *token;
8098	ipfgeniter_t *itp;
8099{
8100	int error;
8101
8102	switch (itp->igi_type)
8103	{
8104	case IPFGENITER_FRAG :
8105		error = ipf_frag_pkt_next(softc, token, itp);
8106		break;
8107	default :
8108		IPFERROR(92);
8109		error = EINVAL;
8110		break;
8111	}
8112
8113	return error;
8114}
8115
8116
8117/* ------------------------------------------------------------------------ */
8118/* Function:    ipf_genericiter                                             */
8119/* Returns:     int - 0 = success, else error                               */
8120/* Parameters:  softc(I)- pointer to soft context main structure            */
8121/*              data(I) - the token type to match                           */
8122/*              uid(I)  - uid owning the token                              */
8123/*              ptr(I)  - context pointer for the token                     */
8124/*                                                                          */
8125/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8126/* ------------------------------------------------------------------------ */
8127int
8128ipf_genericiter(softc, data, uid, ctx)
8129	ipf_main_softc_t *softc;
8130	void *data, *ctx;
8131	int uid;
8132{
8133	ipftoken_t *token;
8134	ipfgeniter_t iter;
8135	int error;
8136
8137	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8138	if (error != 0)
8139		return error;
8140
8141	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8142	if (token != NULL) {
8143		token->ipt_subtype = iter.igi_type;
8144		error = ipf_geniter(softc, token, &iter);
8145		WRITE_ENTER(&softc->ipf_tokens);
8146		ipf_token_deref(softc, token);
8147		RWLOCK_EXIT(&softc->ipf_tokens);
8148	} else {
8149		IPFERROR(93);
8150		error = 0;
8151	}
8152
8153	return error;
8154}
8155
8156
8157/* ------------------------------------------------------------------------ */
8158/* Function:    ipf_ipf_ioctl                                               */
8159/* Returns:     int - 0 = success, else error                               */
8160/* Parameters:  softc(I)- pointer to soft context main structure           */
8161/*              data(I) - the token type to match                           */
8162/*              cmd(I)  - the ioctl command number                          */
8163/*              mode(I) - mode flags for the ioctl                          */
8164/*              uid(I)  - uid owning the token                              */
8165/*              ptr(I)  - context pointer for the token                     */
8166/*                                                                          */
8167/* This function handles all of the ioctl command that are actually isssued */
8168/* to the /dev/ipl device.                                                  */
8169/* ------------------------------------------------------------------------ */
8170int
8171ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8172	ipf_main_softc_t *softc;
8173	caddr_t data;
8174	ioctlcmd_t cmd;
8175	int mode, uid;
8176	void *ctx;
8177{
8178	friostat_t fio;
8179	int error, tmp;
8180	ipfobj_t obj;
8181	SPL_INT(s);
8182
8183	switch (cmd)
8184	{
8185	case SIOCFRENB :
8186		if (!(mode & FWRITE)) {
8187			IPFERROR(94);
8188			error = EPERM;
8189		} else {
8190			error = BCOPYIN(data, &tmp, sizeof(tmp));
8191			if (error != 0) {
8192				IPFERROR(95);
8193				error = EFAULT;
8194				break;
8195			}
8196
8197			WRITE_ENTER(&softc->ipf_global);
8198			if (tmp) {
8199				if (softc->ipf_running > 0)
8200					error = 0;
8201				else
8202					error = ipfattach(softc);
8203				if (error == 0)
8204					softc->ipf_running = 1;
8205				else
8206					(void) ipfdetach(softc);
8207			} else {
8208				if (softc->ipf_running == 1)
8209					error = ipfdetach(softc);
8210				else
8211					error = 0;
8212				if (error == 0)
8213					softc->ipf_running = -1;
8214			}
8215			RWLOCK_EXIT(&softc->ipf_global);
8216		}
8217		break;
8218
8219	case SIOCIPFSET :
8220		if (!(mode & FWRITE)) {
8221			IPFERROR(96);
8222			error = EPERM;
8223			break;
8224		}
8225		/* FALLTHRU */
8226	case SIOCIPFGETNEXT :
8227	case SIOCIPFGET :
8228		error = ipf_ipftune(softc, cmd, (void *)data);
8229		break;
8230
8231	case SIOCSETFF :
8232		if (!(mode & FWRITE)) {
8233			IPFERROR(97);
8234			error = EPERM;
8235		} else {
8236			error = BCOPYIN(data, &softc->ipf_flags,
8237					sizeof(softc->ipf_flags));
8238			if (error != 0) {
8239				IPFERROR(98);
8240				error = EFAULT;
8241			}
8242		}
8243		break;
8244
8245	case SIOCGETFF :
8246		error = BCOPYOUT(&softc->ipf_flags, data,
8247				 sizeof(softc->ipf_flags));
8248		if (error != 0) {
8249			IPFERROR(99);
8250			error = EFAULT;
8251		}
8252		break;
8253
8254	case SIOCFUNCL :
8255		error = ipf_resolvefunc(softc, (void *)data);
8256		break;
8257
8258	case SIOCINAFR :
8259	case SIOCRMAFR :
8260	case SIOCADAFR :
8261	case SIOCZRLST :
8262		if (!(mode & FWRITE)) {
8263			IPFERROR(100);
8264			error = EPERM;
8265		} else {
8266			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8267					  softc->ipf_active, 1);
8268		}
8269		break;
8270
8271	case SIOCINIFR :
8272	case SIOCRMIFR :
8273	case SIOCADIFR :
8274		if (!(mode & FWRITE)) {
8275			IPFERROR(101);
8276			error = EPERM;
8277		} else {
8278			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8279					  1 - softc->ipf_active, 1);
8280		}
8281		break;
8282
8283	case SIOCSWAPA :
8284		if (!(mode & FWRITE)) {
8285			IPFERROR(102);
8286			error = EPERM;
8287		} else {
8288			WRITE_ENTER(&softc->ipf_mutex);
8289			error = BCOPYOUT(&softc->ipf_active, data,
8290					 sizeof(softc->ipf_active));
8291			if (error != 0) {
8292				IPFERROR(103);
8293				error = EFAULT;
8294			} else {
8295				softc->ipf_active = 1 - softc->ipf_active;
8296			}
8297			RWLOCK_EXIT(&softc->ipf_mutex);
8298		}
8299		break;
8300
8301	case SIOCGETFS :
8302		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8303				  IPFOBJ_IPFSTAT);
8304		if (error != 0)
8305			break;
8306		ipf_getstat(softc, &fio, obj.ipfo_rev);
8307		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8308		break;
8309
8310	case SIOCFRZST :
8311		if (!(mode & FWRITE)) {
8312			IPFERROR(104);
8313			error = EPERM;
8314		} else
8315			error = ipf_zerostats(softc, (caddr_t)data);
8316		break;
8317
8318	case SIOCIPFFL :
8319		if (!(mode & FWRITE)) {
8320			IPFERROR(105);
8321			error = EPERM;
8322		} else {
8323			error = BCOPYIN(data, &tmp, sizeof(tmp));
8324			if (!error) {
8325				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8326				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8327				if (error != 0) {
8328					IPFERROR(106);
8329					error = EFAULT;
8330				}
8331			} else {
8332				IPFERROR(107);
8333				error = EFAULT;
8334			}
8335		}
8336		break;
8337
8338#ifdef USE_INET6
8339	case SIOCIPFL6 :
8340		if (!(mode & FWRITE)) {
8341			IPFERROR(108);
8342			error = EPERM;
8343		} else {
8344			error = BCOPYIN(data, &tmp, sizeof(tmp));
8345			if (!error) {
8346				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8347				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8348				if (error != 0) {
8349					IPFERROR(109);
8350					error = EFAULT;
8351				}
8352			} else {
8353				IPFERROR(110);
8354				error = EFAULT;
8355			}
8356		}
8357		break;
8358#endif
8359
8360	case SIOCSTLCK :
8361		if (!(mode & FWRITE)) {
8362			IPFERROR(122);
8363			error = EPERM;
8364		} else {
8365			error = BCOPYIN(data, &tmp, sizeof(tmp));
8366			if (error == 0) {
8367				ipf_state_setlock(softc->ipf_state_soft, tmp);
8368				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8369				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8370				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8371			} else {
8372				IPFERROR(111);
8373				error = EFAULT;
8374			}
8375		}
8376		break;
8377
8378#ifdef	IPFILTER_LOG
8379	case SIOCIPFFB :
8380		if (!(mode & FWRITE)) {
8381			IPFERROR(112);
8382			error = EPERM;
8383		} else {
8384			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8385			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8386			if (error) {
8387				IPFERROR(113);
8388				error = EFAULT;
8389			}
8390		}
8391		break;
8392#endif /* IPFILTER_LOG */
8393
8394	case SIOCFRSYN :
8395		if (!(mode & FWRITE)) {
8396			IPFERROR(114);
8397			error = EPERM;
8398		} else {
8399			WRITE_ENTER(&softc->ipf_global);
8400#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8401			error = ipfsync();
8402#else
8403			ipf_sync(softc, NULL);
8404			error = 0;
8405#endif
8406			RWLOCK_EXIT(&softc->ipf_global);
8407
8408		}
8409		break;
8410
8411	case SIOCGFRST :
8412		error = ipf_outobj(softc, (void *)data,
8413				   ipf_frag_stats(softc->ipf_frag_soft),
8414				   IPFOBJ_FRAGSTAT);
8415		break;
8416
8417#ifdef	IPFILTER_LOG
8418	case FIONREAD :
8419		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8420		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8421		break;
8422#endif
8423
8424	case SIOCIPFITER :
8425		SPL_SCHED(s);
8426		error = ipf_frruleiter(softc, data, uid, ctx);
8427		SPL_X(s);
8428		break;
8429
8430	case SIOCGENITER :
8431		SPL_SCHED(s);
8432		error = ipf_genericiter(softc, data, uid, ctx);
8433		SPL_X(s);
8434		break;
8435
8436	case SIOCIPFDELTOK :
8437		error = BCOPYIN(data, &tmp, sizeof(tmp));
8438		if (error == 0) {
8439			SPL_SCHED(s);
8440			error = ipf_token_del(softc, tmp, uid, ctx);
8441			SPL_X(s);
8442		}
8443		break;
8444
8445	default :
8446		IPFERROR(115);
8447		error = EINVAL;
8448		break;
8449	}
8450
8451	return error;
8452}
8453
8454
8455/* ------------------------------------------------------------------------ */
8456/* Function:    ipf_decaps                                                  */
8457/* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8458/*                           flags indicating packet filtering decision.    */
8459/* Parameters:  fin(I)     - pointer to packet information                  */
8460/*              pass(I)    - IP protocol version to match                   */
8461/*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8462/*                                                                          */
8463/* This function is called for packets that are wrapt up in other packets,  */
8464/* for example, an IP packet that is the entire data segment for another IP */
8465/* packet.  If the basic constraints for this are satisfied, change the     */
8466/* buffer to point to the start of the inner packet and start processing    */
8467/* rules belonging to the head group this rule specifies.                   */
8468/* ------------------------------------------------------------------------ */
8469u_32_t
8470ipf_decaps(fin, pass, l5proto)
8471	fr_info_t *fin;
8472	u_32_t pass;
8473	int l5proto;
8474{
8475	fr_info_t fin2, *fino = NULL;
8476	int elen, hlen, nh;
8477	grehdr_t gre;
8478	ip_t *ip;
8479	mb_t *m;
8480
8481	if ((fin->fin_flx & FI_COALESCE) == 0)
8482		if (ipf_coalesce(fin) == -1)
8483			goto cantdecaps;
8484
8485	m = fin->fin_m;
8486	hlen = fin->fin_hlen;
8487
8488	switch (fin->fin_p)
8489	{
8490	case IPPROTO_UDP :
8491		/*
8492		 * In this case, the specific protocol being decapsulated
8493		 * inside UDP frames comes from the rule.
8494		 */
8495		nh = fin->fin_fr->fr_icode;
8496		break;
8497
8498	case IPPROTO_GRE :	/* 47 */
8499		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8500		hlen += sizeof(grehdr_t);
8501		if (gre.gr_R|gre.gr_s)
8502			goto cantdecaps;
8503		if (gre.gr_C)
8504			hlen += 4;
8505		if (gre.gr_K)
8506			hlen += 4;
8507		if (gre.gr_S)
8508			hlen += 4;
8509
8510		nh = IPPROTO_IP;
8511
8512		/*
8513		 * If the routing options flag is set, validate that it is
8514		 * there and bounce over it.
8515		 */
8516#if 0
8517		/* This is really heavy weight and lots of room for error, */
8518		/* so for now, put it off and get the simple stuff right.  */
8519		if (gre.gr_R) {
8520			u_char off, len, *s;
8521			u_short af;
8522			int end;
8523
8524			end = 0;
8525			s = fin->fin_dp;
8526			s += hlen;
8527			aplen = fin->fin_plen - hlen;
8528			while (aplen > 3) {
8529				af = (s[0] << 8) | s[1];
8530				off = s[2];
8531				len = s[3];
8532				aplen -= 4;
8533				s += 4;
8534				if (af == 0 && len == 0) {
8535					end = 1;
8536					break;
8537				}
8538				if (aplen < len)
8539					break;
8540				s += len;
8541				aplen -= len;
8542			}
8543			if (end != 1)
8544				goto cantdecaps;
8545			hlen = s - (u_char *)fin->fin_dp;
8546		}
8547#endif
8548		break;
8549
8550#ifdef IPPROTO_IPIP
8551	case IPPROTO_IPIP :	/* 4 */
8552#endif
8553		nh = IPPROTO_IP;
8554		break;
8555
8556	default :	/* Includes ESP, AH is special for IPv4 */
8557		goto cantdecaps;
8558	}
8559
8560	switch (nh)
8561	{
8562	case IPPROTO_IP :
8563	case IPPROTO_IPV6 :
8564		break;
8565	default :
8566		goto cantdecaps;
8567	}
8568
8569	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8570	fino = fin;
8571	fin = &fin2;
8572	elen = hlen;
8573#if defined(MENTAT) && defined(_KERNEL)
8574	m->b_rptr += elen;
8575#else
8576	m->m_data += elen;
8577	m->m_len -= elen;
8578#endif
8579	fin->fin_plen -= elen;
8580
8581	ip = (ip_t *)((char *)fin->fin_ip + elen);
8582
8583	/*
8584	 * Make sure we have at least enough data for the network layer
8585	 * header.
8586	 */
8587	if (IP_V(ip) == 4)
8588		hlen = IP_HL(ip) << 2;
8589#ifdef USE_INET6
8590	else if (IP_V(ip) == 6)
8591		hlen = sizeof(ip6_t);
8592#endif
8593	else
8594		goto cantdecaps2;
8595
8596	if (fin->fin_plen < hlen)
8597		goto cantdecaps2;
8598
8599	fin->fin_dp = (char *)ip + hlen;
8600
8601	if (IP_V(ip) == 4) {
8602		/*
8603		 * Perform IPv4 header checksum validation.
8604		 */
8605		if (ipf_cksum((u_short *)ip, hlen))
8606			goto cantdecaps2;
8607	}
8608
8609	if (ipf_makefrip(hlen, ip, fin) == -1) {
8610cantdecaps2:
8611		if (m != NULL) {
8612#if defined(MENTAT) && defined(_KERNEL)
8613			m->b_rptr -= elen;
8614#else
8615			m->m_data -= elen;
8616			m->m_len += elen;
8617#endif
8618		}
8619cantdecaps:
8620		DT1(frb_decapfrip, fr_info_t *, fin);
8621		pass &= ~FR_CMDMASK;
8622		pass |= FR_BLOCK|FR_QUICK;
8623		fin->fin_reason = FRB_DECAPFRIP;
8624		return -1;
8625	}
8626
8627	pass = ipf_scanlist(fin, pass);
8628
8629	/*
8630	 * Copy the packet filter "result" fields out of the fr_info_t struct
8631	 * that is local to the decapsulation processing and back into the
8632	 * one we were called with.
8633	 */
8634	fino->fin_flx = fin->fin_flx;
8635	fino->fin_rev = fin->fin_rev;
8636	fino->fin_icode = fin->fin_icode;
8637	fino->fin_rule = fin->fin_rule;
8638	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8639	fino->fin_fr = fin->fin_fr;
8640	fino->fin_error = fin->fin_error;
8641	fino->fin_mp = fin->fin_mp;
8642	fino->fin_m = fin->fin_m;
8643	m = fin->fin_m;
8644	if (m != NULL) {
8645#if defined(MENTAT) && defined(_KERNEL)
8646		m->b_rptr -= elen;
8647#else
8648		m->m_data -= elen;
8649		m->m_len += elen;
8650#endif
8651	}
8652	return pass;
8653}
8654
8655
8656/* ------------------------------------------------------------------------ */
8657/* Function:    ipf_matcharray_load                                         */
8658/* Returns:     int         - 0 = success, else error                       */
8659/* Parameters:  softc(I)    - pointer to soft context main structure        */
8660/*              data(I)     - pointer to ioctl data                         */
8661/*              objp(I)     - ipfobj_t structure to load data into          */
8662/*              arrayptr(I) - pointer to location to store array pointer    */
8663/*                                                                          */
8664/* This function loads in a mathing array through the ipfobj_t struct that  */
8665/* describes it.  Sanity checking and array size limitations are enforced   */
8666/* in this function to prevent userspace from trying to load in something   */
8667/* that is insanely big.  Once the size of the array is known, the memory   */
8668/* required is malloc'd and returned through changing *arrayptr.  The       */
8669/* contents of the array are verified before returning.  Only in the event  */
8670/* of a successful call is the caller required to free up the malloc area.  */
8671/* ------------------------------------------------------------------------ */
8672int
8673ipf_matcharray_load(softc, data, objp, arrayptr)
8674	ipf_main_softc_t *softc;
8675	caddr_t data;
8676	ipfobj_t *objp;
8677	int **arrayptr;
8678{
8679	int arraysize, *array, error;
8680
8681	*arrayptr = NULL;
8682
8683	error = BCOPYIN(data, objp, sizeof(*objp));
8684	if (error != 0) {
8685		IPFERROR(116);
8686		return EFAULT;
8687	}
8688
8689	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8690		IPFERROR(117);
8691		return EINVAL;
8692	}
8693
8694	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8695	    (objp->ipfo_size > 1024)) {
8696		IPFERROR(118);
8697		return EINVAL;
8698	}
8699
8700	arraysize = objp->ipfo_size * sizeof(*array);
8701	KMALLOCS(array, int *, arraysize);
8702	if (array == NULL) {
8703		IPFERROR(119);
8704		return ENOMEM;
8705	}
8706
8707	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8708	if (error != 0) {
8709		KFREES(array, arraysize);
8710		IPFERROR(120);
8711		return EFAULT;
8712	}
8713
8714	if (ipf_matcharray_verify(array, arraysize) != 0) {
8715		KFREES(array, arraysize);
8716		IPFERROR(121);
8717		return EINVAL;
8718	}
8719
8720	*arrayptr = array;
8721	return 0;
8722}
8723
8724
8725/* ------------------------------------------------------------------------ */
8726/* Function:    ipf_matcharray_verify                                       */
8727/* Returns:     Nil                                                         */
8728/* Parameters:  array(I)     - pointer to matching array                    */
8729/*              arraysize(I) - number of elements in the array              */
8730/*                                                                          */
8731/* Verify the contents of a matching array by stepping through each element */
8732/* in it.  The actual commands in the array are not verified for            */
8733/* correctness, only that all of the sizes are correctly within limits.     */
8734/* ------------------------------------------------------------------------ */
8735int
8736ipf_matcharray_verify(array, arraysize)
8737	int *array, arraysize;
8738{
8739	int i, nelem, maxidx;
8740	ipfexp_t *e;
8741
8742	nelem = arraysize / sizeof(*array);
8743
8744	/*
8745	 * Currently, it makes no sense to have an array less than 6
8746	 * elements long - the initial size at the from, a single operation
8747	 * (minimum 4 in length) and a trailer, for a total of 6.
8748	 */
8749	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8750		return -1;
8751	}
8752
8753	/*
8754	 * Verify the size of data pointed to by array with how long
8755	 * the array claims to be itself.
8756	 */
8757	if (array[0] * sizeof(*array) != arraysize) {
8758		return -1;
8759	}
8760
8761	maxidx = nelem - 1;
8762	/*
8763	 * The last opcode in this array should be an IPF_EXP_END.
8764	 */
8765	if (array[maxidx] != IPF_EXP_END) {
8766		return -1;
8767	}
8768
8769	for (i = 1; i < maxidx; ) {
8770		e = (ipfexp_t *)(array + i);
8771
8772		/*
8773		 * The length of the bits to check must be at least 1
8774		 * (or else there is nothing to comapre with!) and it
8775		 * cannot exceed the length of the data present.
8776		 */
8777		if ((e->ipfe_size < 1 ) ||
8778		    (e->ipfe_size + i > maxidx)) {
8779			return -1;
8780		}
8781		i += e->ipfe_size;
8782	}
8783	return 0;
8784}
8785
8786
8787/* ------------------------------------------------------------------------ */
8788/* Function:    ipf_fr_matcharray                                           */
8789/* Returns:     int      - 0 = match failed, else positive match            */
8790/* Parameters:  fin(I)   - pointer to packet information                    */
8791/*              array(I) - pointer to matching array                        */
8792/*                                                                          */
8793/* This function is used to apply a matching array against a packet and     */
8794/* return an indication of whether or not the packet successfully matches   */
8795/* all of the commands in it.                                               */
8796/* ------------------------------------------------------------------------ */
8797static int
8798ipf_fr_matcharray(fin, array)
8799	fr_info_t *fin;
8800	int *array;
8801{
8802	int i, n, *x, rv, p;
8803	ipfexp_t *e;
8804
8805	rv = 0;
8806	n = array[0];
8807	x = array + 1;
8808
8809	for (; n > 0; x += 3 + x[3], rv = 0) {
8810		e = (ipfexp_t *)x;
8811		if (e->ipfe_cmd == IPF_EXP_END)
8812			break;
8813		n -= e->ipfe_size;
8814
8815		/*
8816		 * The upper 16 bits currently store the protocol value.
8817		 * This is currently used with TCP and UDP port compares and
8818		 * allows "tcp.port = 80" without requiring an explicit
8819		 " "ip.pr = tcp" first.
8820		 */
8821		p = e->ipfe_cmd >> 16;
8822		if ((p != 0) && (p != fin->fin_p))
8823			break;
8824
8825		switch (e->ipfe_cmd)
8826		{
8827		case IPF_EXP_IP_PR :
8828			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8829				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8830			}
8831			break;
8832
8833		case IPF_EXP_IP_SRCADDR :
8834			if (fin->fin_v != 4)
8835				break;
8836			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8837				rv |= ((fin->fin_saddr &
8838					e->ipfe_arg0[i * 2 + 1]) ==
8839				       e->ipfe_arg0[i * 2]);
8840			}
8841			break;
8842
8843		case IPF_EXP_IP_DSTADDR :
8844			if (fin->fin_v != 4)
8845				break;
8846			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8847				rv |= ((fin->fin_daddr &
8848					e->ipfe_arg0[i * 2 + 1]) ==
8849				       e->ipfe_arg0[i * 2]);
8850			}
8851			break;
8852
8853		case IPF_EXP_IP_ADDR :
8854			if (fin->fin_v != 4)
8855				break;
8856			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8857				rv |= ((fin->fin_saddr &
8858					e->ipfe_arg0[i * 2 + 1]) ==
8859				       e->ipfe_arg0[i * 2]) ||
8860				      ((fin->fin_daddr &
8861					e->ipfe_arg0[i * 2 + 1]) ==
8862				       e->ipfe_arg0[i * 2]);
8863			}
8864			break;
8865
8866#ifdef USE_INET6
8867		case IPF_EXP_IP6_SRCADDR :
8868			if (fin->fin_v != 6)
8869				break;
8870			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8871				rv |= IP6_MASKEQ(&fin->fin_src6,
8872						 &e->ipfe_arg0[i * 8 + 4],
8873						 &e->ipfe_arg0[i * 8]);
8874			}
8875			break;
8876
8877		case IPF_EXP_IP6_DSTADDR :
8878			if (fin->fin_v != 6)
8879				break;
8880			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8881				rv |= IP6_MASKEQ(&fin->fin_dst6,
8882						 &e->ipfe_arg0[i * 8 + 4],
8883						 &e->ipfe_arg0[i * 8]);
8884			}
8885			break;
8886
8887		case IPF_EXP_IP6_ADDR :
8888			if (fin->fin_v != 6)
8889				break;
8890			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8891				rv |= IP6_MASKEQ(&fin->fin_src6,
8892						 &e->ipfe_arg0[i * 8 + 4],
8893						 &e->ipfe_arg0[i * 8]) ||
8894				      IP6_MASKEQ(&fin->fin_dst6,
8895						 &e->ipfe_arg0[i * 8 + 4],
8896						 &e->ipfe_arg0[i * 8]);
8897			}
8898			break;
8899#endif
8900
8901		case IPF_EXP_UDP_PORT :
8902		case IPF_EXP_TCP_PORT :
8903			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8904				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8905				      (fin->fin_dport == e->ipfe_arg0[i]);
8906			}
8907			break;
8908
8909		case IPF_EXP_UDP_SPORT :
8910		case IPF_EXP_TCP_SPORT :
8911			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8912				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8913			}
8914			break;
8915
8916		case IPF_EXP_UDP_DPORT :
8917		case IPF_EXP_TCP_DPORT :
8918			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8919				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8920			}
8921			break;
8922
8923		case IPF_EXP_TCP_FLAGS :
8924			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8925				rv |= ((fin->fin_tcpf &
8926					e->ipfe_arg0[i * 2 + 1]) ==
8927				       e->ipfe_arg0[i * 2]);
8928			}
8929			break;
8930		}
8931		rv ^= e->ipfe_not;
8932
8933		if (rv == 0)
8934			break;
8935	}
8936
8937	return rv;
8938}
8939
8940
8941/* ------------------------------------------------------------------------ */
8942/* Function:    ipf_queueflush                                              */
8943/* Returns:     int - number of entries flushed (0 = none)                  */
8944/* Parameters:  softc(I)    - pointer to soft context main structure        */
8945/*              deletefn(I) - function to call to delete entry              */
8946/*              ipfqs(I)    - top of the list of ipf internal queues        */
8947/*              userqs(I)   - top of the list of user defined timeouts      */
8948/*                                                                          */
8949/* This fucntion gets called when the state/NAT hash tables fill up and we  */
8950/* need to try a bit harder to free up some space.  The algorithm used here */
8951/* split into two parts but both halves have the same goal: to reduce the   */
8952/* number of connections considered to be "active" to the low watermark.    */
8953/* There are two steps in doing this:                                       */
8954/* 1) Remove any TCP connections that are already considered to be "closed" */
8955/*    but have not yet been removed from the state table.  The two states   */
8956/*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8957/*    candidates for this style of removal.  If freeing up entries in       */
8958/*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8959/*    we do not go on to step 2.                                            */
8960/*                                                                          */
8961/* 2) Look for the oldest entries on each timeout queue and free them if    */
8962/*    they are within the given window we are considering.  Where the       */
8963/*    window starts and the steps taken to increase its size depend upon    */
8964/*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8965/*    last 30 seconds is not touched.                                       */
8966/*                                              touched                     */
8967/*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8968/*           |          |        |           |     |     |                  */
8969/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8970/*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8971/*                                                                          */
8972/* Points to note:                                                          */
8973/* - tqe_die is the time, in the future, when entries die.                  */
8974/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8975/*   ticks.                                                                 */
8976/* - tqe_touched is when the entry was last used by NAT/state               */
8977/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8978/*   ipf_ticks any given timeout queue and vice versa.                      */
8979/* - both tqe_die and tqe_touched increase over time                        */
8980/* - timeout queues are sorted with the highest value of tqe_die at the     */
8981/*   bottom and therefore the smallest values of each are at the top        */
8982/* - the pointer passed in as ipfqs should point to an array of timeout     */
8983/*   queues representing each of the TCP states                             */
8984/*                                                                          */
8985/* We start by setting up a maximum range to scan for things to move of     */
8986/* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8987/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8988/* we start again with a new value for "iend" and "istart".  This is        */
8989/* continued until we either finish the scan of 30 second intervals or the  */
8990/* low water mark is reached.                                               */
8991/* ------------------------------------------------------------------------ */
8992int
8993ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8994	ipf_main_softc_t *softc;
8995	ipftq_delete_fn_t deletefn;
8996	ipftq_t *ipfqs, *userqs;
8997	u_int *activep;
8998	int size, low;
8999{
9000	u_long interval, istart, iend;
9001	ipftq_t *ifq, *ifqnext;
9002	ipftqent_t *tqe, *tqn;
9003	int removed = 0;
9004
9005	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
9006		tqn = tqe->tqe_next;
9007		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9008			removed++;
9009	}
9010	if ((*activep * 100 / size) > low) {
9011		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
9012		     ((tqe = tqn) != NULL); ) {
9013			tqn = tqe->tqe_next;
9014			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9015				removed++;
9016		}
9017	}
9018
9019	if ((*activep * 100 / size) <= low) {
9020		return removed;
9021	}
9022
9023	/*
9024	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
9025	 *       used then the operations are upgraded to floating point
9026	 *       and kernels don't like floating point...
9027	 */
9028	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
9029		istart = IPF_TTLVAL(86400 * 4);
9030		interval = IPF_TTLVAL(43200);
9031	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9032		istart = IPF_TTLVAL(43200);
9033		interval = IPF_TTLVAL(1800);
9034	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9035		istart = IPF_TTLVAL(1800);
9036		interval = IPF_TTLVAL(30);
9037	} else {
9038		return 0;
9039	}
9040	if (istart > softc->ipf_ticks) {
9041		if (softc->ipf_ticks - interval < interval)
9042			istart = interval;
9043		else
9044			istart = (softc->ipf_ticks / interval) * interval;
9045	}
9046
9047	iend = softc->ipf_ticks - interval;
9048
9049	while ((*activep * 100 / size) > low) {
9050		u_long try;
9051
9052		try = softc->ipf_ticks - istart;
9053
9054		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9055			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9056				if (try < tqe->tqe_touched)
9057					break;
9058				tqn = tqe->tqe_next;
9059				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9060					removed++;
9061			}
9062		}
9063
9064		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9065			ifqnext = ifq->ifq_next;
9066
9067			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9068				if (try < tqe->tqe_touched)
9069					break;
9070				tqn = tqe->tqe_next;
9071				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9072					removed++;
9073			}
9074		}
9075
9076		if (try >= iend) {
9077			if (interval == IPF_TTLVAL(43200)) {
9078				interval = IPF_TTLVAL(1800);
9079			} else if (interval == IPF_TTLVAL(1800)) {
9080				interval = IPF_TTLVAL(30);
9081			} else {
9082				break;
9083			}
9084			if (interval >= softc->ipf_ticks)
9085				break;
9086
9087			iend = softc->ipf_ticks - interval;
9088		}
9089		istart -= interval;
9090	}
9091
9092	return removed;
9093}
9094
9095
9096/* ------------------------------------------------------------------------ */
9097/* Function:    ipf_deliverlocal                                            */
9098/* Returns:     int - 1 = local address, 0 = non-local address              */
9099/* Parameters:  softc(I)     - pointer to soft context main structure       */
9100/*              ipversion(I) - IP protocol version (4 or 6)                 */
9101/*              ifp(I)       - network interface pointer                    */
9102/*              ipaddr(I)    - IPv4/6 destination address                   */
9103/*                                                                          */
9104/* This fucntion is used to determine in the address "ipaddr" belongs to    */
9105/* the network interface represented by ifp.                                */
9106/* ------------------------------------------------------------------------ */
9107int
9108ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9109	ipf_main_softc_t *softc;
9110	int ipversion;
9111	void *ifp;
9112	i6addr_t *ipaddr;
9113{
9114	i6addr_t addr;
9115	int islocal = 0;
9116
9117	if (ipversion == 4) {
9118		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9119			if (addr.in4.s_addr == ipaddr->in4.s_addr)
9120				islocal = 1;
9121		}
9122
9123#ifdef USE_INET6
9124	} else if (ipversion == 6) {
9125		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9126			if (IP6_EQ(&addr, ipaddr))
9127				islocal = 1;
9128		}
9129#endif
9130	}
9131
9132	return islocal;
9133}
9134
9135
9136/* ------------------------------------------------------------------------ */
9137/* Function:    ipf_settimeout                                              */
9138/* Returns:     int - 0 = success, -1 = failure                             */
9139/* Parameters:  softc(I) - pointer to soft context main structure           */
9140/*              t(I)     - pointer to tuneable array entry                  */
9141/*              p(I)     - pointer to values passed in to apply             */
9142/*                                                                          */
9143/* This function is called to set the timeout values for each distinct      */
9144/* queue timeout that is available.  When called, it calls into both the    */
9145/* state and NAT code, telling them to update their timeout queues.         */
9146/* ------------------------------------------------------------------------ */
9147static int
9148ipf_settimeout(softc, t, p)
9149	struct ipf_main_softc_s *softc;
9150	ipftuneable_t *t;
9151	ipftuneval_t *p;
9152{
9153
9154	/*
9155	 * ipf_interror should be set by the functions called here, not
9156	 * by this function - it's just a middle man.
9157	 */
9158	if (ipf_state_settimeout(softc, t, p) == -1)
9159		return -1;
9160	if (ipf_nat_settimeout(softc, t, p) == -1)
9161		return -1;
9162	return 0;
9163}
9164
9165
9166/* ------------------------------------------------------------------------ */
9167/* Function:    ipf_apply_timeout                                           */
9168/* Returns:     int - 0 = success, -1 = failure                             */
9169/* Parameters:  head(I)    - pointer to tuneable array entry                */
9170/*              seconds(I) - pointer to values passed in to apply           */
9171/*                                                                          */
9172/* This function applies a timeout of "seconds" to the timeout queue that   */
9173/* is pointed to by "head".  All entries on this list have an expiration    */
9174/* set to be the current tick value of ipf plus the ttl.  Given that this   */
9175/* function should only be called when the delta is non-zero, the task is   */
9176/* to walk the entire list and apply the change.  The sort order will not   */
9177/* change.  The only catch is that this is O(n) across the list, so if the  */
9178/* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9179/* could take a relatively long time to work through them all.              */
9180/* ------------------------------------------------------------------------ */
9181void
9182ipf_apply_timeout(head, seconds)
9183	ipftq_t *head;
9184	u_int seconds;
9185{
9186	u_int oldtimeout, newtimeout;
9187	ipftqent_t *tqe;
9188	int delta;
9189
9190	MUTEX_ENTER(&head->ifq_lock);
9191	oldtimeout = head->ifq_ttl;
9192	newtimeout = IPF_TTLVAL(seconds);
9193	delta = oldtimeout - newtimeout;
9194
9195	head->ifq_ttl = newtimeout;
9196
9197	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9198		tqe->tqe_die += delta;
9199	}
9200	MUTEX_EXIT(&head->ifq_lock);
9201}
9202
9203
9204/* ------------------------------------------------------------------------ */
9205/* Function:   ipf_settimeout_tcp                                           */
9206/* Returns:    int - 0 = successfully applied, -1 = failed                  */
9207/* Parameters: t(I)   - pointer to tuneable to change                       */
9208/*             p(I)   - pointer to new timeout information                  */
9209/*             tab(I) - pointer to table of TCP queues                      */
9210/*                                                                          */
9211/* This function applies the new timeout (p) to the TCP tunable (t) and     */
9212/* updates all of the entries on the relevant timeout queue by calling      */
9213/* ipf_apply_timeout().                                                     */
9214/* ------------------------------------------------------------------------ */
9215int
9216ipf_settimeout_tcp(t, p, tab)
9217	ipftuneable_t *t;
9218	ipftuneval_t *p;
9219	ipftq_t *tab;
9220{
9221	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9222	    !strcmp(t->ipft_name, "tcp_established")) {
9223		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9224	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9225		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9226	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9227		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9228	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9229		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9230		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9231		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9232	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
9233		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9234	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9235		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9236	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
9237		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9238	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9239		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9240	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9241		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9242	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
9243		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9244	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9245		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9246	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9247		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9248	} else {
9249		/*
9250		 * ipf_interror isn't set here because it should be set
9251		 * by whatever called this function.
9252		 */
9253		return -1;
9254	}
9255	return 0;
9256}
9257
9258
9259/* ------------------------------------------------------------------------ */
9260/* Function:   ipf_main_soft_create                                         */
9261/* Returns:    NULL = failure, else success                                 */
9262/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9263/*                                                                          */
9264/* Create the foundation soft context structure. In circumstances where it  */
9265/* is not required to dynamically allocate the context, a pointer can be    */
9266/* passed in (rather than NULL) to a structure to be initialised.           */
9267/* The main thing of interest is that a number of locks are initialised     */
9268/* here instead of in the where might be expected - in the relevant create  */
9269/* function elsewhere.  This is done because the current locking design has */
9270/* some areas where these locks are used outside of their module.           */
9271/* Possibly the most important exercise that is done here is setting of all */
9272/* the timeout values, allowing them to be changed before init().           */
9273/* ------------------------------------------------------------------------ */
9274void *
9275ipf_main_soft_create(arg)
9276	void *arg;
9277{
9278	ipf_main_softc_t *softc;
9279
9280	if (arg == NULL) {
9281		KMALLOC(softc, ipf_main_softc_t *);
9282		if (softc == NULL)
9283			return NULL;
9284	} else {
9285		softc = arg;
9286	}
9287
9288	bzero((char *)softc, sizeof(*softc));
9289
9290	/*
9291	 * This serves as a flag as to whether or not the softc should be
9292	 * free'd when _destroy is called.
9293	 */
9294	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9295
9296	softc->ipf_tuners = ipf_tune_array_copy(softc,
9297						sizeof(ipf_main_tuneables),
9298						ipf_main_tuneables);
9299	if (softc->ipf_tuners == NULL) {
9300		ipf_main_soft_destroy(softc);
9301		return NULL;
9302	}
9303
9304	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9305	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9306	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9307	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9308	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9309	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9310	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9311	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9312	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9313
9314	softc->ipf_token_head = NULL;
9315	softc->ipf_token_tail = &softc->ipf_token_head;
9316
9317	softc->ipf_tcpidletimeout = FIVE_DAYS;
9318	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9319	softc->ipf_tcplastack = IPF_TTLVAL(30);
9320	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9321	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9322	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9323	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9324	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9325	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9326	softc->ipf_udptimeout = IPF_TTLVAL(120);
9327	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9328	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9329	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9330	softc->ipf_iptimeout = IPF_TTLVAL(60);
9331
9332#if defined(IPFILTER_DEFAULT_BLOCK)
9333	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9334#else
9335	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9336#endif
9337	softc->ipf_minttl = 4;
9338	softc->ipf_icmpminfragmtu = 68;
9339	softc->ipf_flags = IPF_LOGGING;
9340
9341	return softc;
9342}
9343
9344/* ------------------------------------------------------------------------ */
9345/* Function:   ipf_main_soft_init                                           */
9346/* Returns:    0 = success, -1 = failure                                    */
9347/* Parameters: softc(I) - pointer to soft context main structure            */
9348/*                                                                          */
9349/* A null-op function that exists as a placeholder so that the flow in      */
9350/* other functions is obvious.                                              */
9351/* ------------------------------------------------------------------------ */
9352/*ARGSUSED*/
9353int
9354ipf_main_soft_init(softc)
9355	ipf_main_softc_t *softc;
9356{
9357	return 0;
9358}
9359
9360
9361/* ------------------------------------------------------------------------ */
9362/* Function:   ipf_main_soft_destroy                                        */
9363/* Returns:    void                                                         */
9364/* Parameters: softc(I) - pointer to soft context main structure            */
9365/*                                                                          */
9366/* Undo everything that we did in ipf_main_soft_create.                     */
9367/*                                                                          */
9368/* The most important check that needs to be made here is whether or not    */
9369/* the structure was allocated by ipf_main_soft_create() by checking what   */
9370/* value is stored in ipf_dynamic_main.                                     */
9371/* ------------------------------------------------------------------------ */
9372/*ARGSUSED*/
9373void
9374ipf_main_soft_destroy(softc)
9375	ipf_main_softc_t *softc;
9376{
9377
9378	RW_DESTROY(&softc->ipf_frag);
9379	RW_DESTROY(&softc->ipf_poolrw);
9380	RW_DESTROY(&softc->ipf_nat);
9381	RW_DESTROY(&softc->ipf_state);
9382	RW_DESTROY(&softc->ipf_tokens);
9383	RW_DESTROY(&softc->ipf_mutex);
9384	RW_DESTROY(&softc->ipf_global);
9385	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9386	MUTEX_DESTROY(&softc->ipf_rw);
9387
9388	if (softc->ipf_tuners != NULL) {
9389		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9390	}
9391	if (softc->ipf_dynamic_softc == 1) {
9392		KFREE(softc);
9393	}
9394}
9395
9396
9397/* ------------------------------------------------------------------------ */
9398/* Function:   ipf_main_soft_fini                                           */
9399/* Returns:    0 = success, -1 = failure                                    */
9400/* Parameters: softc(I) - pointer to soft context main structure            */
9401/*                                                                          */
9402/* Clean out the rules which have been added since _init was last called,   */
9403/* the only dynamic part of the mainline.                                   */
9404/* ------------------------------------------------------------------------ */
9405int
9406ipf_main_soft_fini(softc)
9407	ipf_main_softc_t *softc;
9408{
9409	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9410	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9411	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9412	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9413
9414	return 0;
9415}
9416
9417
9418/* ------------------------------------------------------------------------ */
9419/* Function:   ipf_main_load                                                */
9420/* Returns:    0 = success, -1 = failure                                    */
9421/* Parameters: none                                                         */
9422/*                                                                          */
9423/* Handle global initialisation that needs to be done for the base part of  */
9424/* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9425/* arrays that get used by the state/NAT code.                              */
9426/* ------------------------------------------------------------------------ */
9427int
9428ipf_main_load()
9429{
9430	int i;
9431
9432	/* fill icmp reply type table */
9433	for (i = 0; i <= ICMP_MAXTYPE; i++)
9434		icmpreplytype4[i] = -1;
9435	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9436	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9437	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9438	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9439
9440#ifdef  USE_INET6
9441	/* fill icmp reply type table */
9442	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9443		icmpreplytype6[i] = -1;
9444	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9445	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9446	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9447	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9448	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9449#endif
9450
9451	return 0;
9452}
9453
9454
9455/* ------------------------------------------------------------------------ */
9456/* Function:   ipf_main_unload                                              */
9457/* Returns:    0 = success, -1 = failure                                    */
9458/* Parameters: none                                                         */
9459/*                                                                          */
9460/* A null-op function that exists as a placeholder so that the flow in      */
9461/* other functions is obvious.                                              */
9462/* ------------------------------------------------------------------------ */
9463int
9464ipf_main_unload()
9465{
9466	return 0;
9467}
9468
9469
9470/* ------------------------------------------------------------------------ */
9471/* Function:   ipf_load_all                                                 */
9472/* Returns:    0 = success, -1 = failure                                    */
9473/* Parameters: none                                                         */
9474/*                                                                          */
9475/* Work through all of the subsystems inside IPFilter and call the load     */
9476/* function for each in an order that won't lead to a crash :)              */
9477/* ------------------------------------------------------------------------ */
9478int
9479ipf_load_all()
9480{
9481	if (ipf_main_load() == -1)
9482		return -1;
9483
9484	if (ipf_state_main_load() == -1)
9485		return -1;
9486
9487	if (ipf_nat_main_load() == -1)
9488		return -1;
9489
9490	if (ipf_frag_main_load() == -1)
9491		return -1;
9492
9493	if (ipf_auth_main_load() == -1)
9494		return -1;
9495
9496	if (ipf_proxy_main_load() == -1)
9497		return -1;
9498
9499	return 0;
9500}
9501
9502
9503/* ------------------------------------------------------------------------ */
9504/* Function:   ipf_unload_all                                               */
9505/* Returns:    0 = success, -1 = failure                                    */
9506/* Parameters: none                                                         */
9507/*                                                                          */
9508/* Work through all of the subsystems inside IPFilter and call the unload   */
9509/* function for each in an order that won't lead to a crash :)              */
9510/* ------------------------------------------------------------------------ */
9511int
9512ipf_unload_all()
9513{
9514	if (ipf_proxy_main_unload() == -1)
9515		return -1;
9516
9517	if (ipf_auth_main_unload() == -1)
9518		return -1;
9519
9520	if (ipf_frag_main_unload() == -1)
9521		return -1;
9522
9523	if (ipf_nat_main_unload() == -1)
9524		return -1;
9525
9526	if (ipf_state_main_unload() == -1)
9527		return -1;
9528
9529	if (ipf_main_unload() == -1)
9530		return -1;
9531
9532	return 0;
9533}
9534
9535
9536/* ------------------------------------------------------------------------ */
9537/* Function:   ipf_create_all                                               */
9538/* Returns:    NULL = failure, else success                                 */
9539/* Parameters: arg(I) - pointer to soft context main structure              */
9540/*                                                                          */
9541/* Work through all of the subsystems inside IPFilter and call the create   */
9542/* function for each in an order that won't lead to a crash :)              */
9543/* ------------------------------------------------------------------------ */
9544ipf_main_softc_t *
9545ipf_create_all(arg)
9546	void *arg;
9547{
9548	ipf_main_softc_t *softc;
9549
9550	softc = ipf_main_soft_create(arg);
9551	if (softc == NULL)
9552		return NULL;
9553
9554#ifdef IPFILTER_LOG
9555	softc->ipf_log_soft = ipf_log_soft_create(softc);
9556	if (softc->ipf_log_soft == NULL) {
9557		ipf_destroy_all(softc);
9558		return NULL;
9559	}
9560#endif
9561
9562	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9563	if (softc->ipf_lookup_soft == NULL) {
9564		ipf_destroy_all(softc);
9565		return NULL;
9566	}
9567
9568	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9569	if (softc->ipf_sync_soft == NULL) {
9570		ipf_destroy_all(softc);
9571		return NULL;
9572	}
9573
9574	softc->ipf_state_soft = ipf_state_soft_create(softc);
9575	if (softc->ipf_state_soft == NULL) {
9576		ipf_destroy_all(softc);
9577		return NULL;
9578	}
9579
9580	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9581	if (softc->ipf_nat_soft == NULL) {
9582		ipf_destroy_all(softc);
9583		return NULL;
9584	}
9585
9586	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9587	if (softc->ipf_frag_soft == NULL) {
9588		ipf_destroy_all(softc);
9589		return NULL;
9590	}
9591
9592	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9593	if (softc->ipf_auth_soft == NULL) {
9594		ipf_destroy_all(softc);
9595		return NULL;
9596	}
9597
9598	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9599	if (softc->ipf_proxy_soft == NULL) {
9600		ipf_destroy_all(softc);
9601		return NULL;
9602	}
9603
9604	return softc;
9605}
9606
9607
9608/* ------------------------------------------------------------------------ */
9609/* Function:   ipf_destroy_all                                              */
9610/* Returns:    void                                                         */
9611/* Parameters: softc(I) - pointer to soft context main structure            */
9612/*                                                                          */
9613/* Work through all of the subsystems inside IPFilter and call the destroy  */
9614/* function for each in an order that won't lead to a crash :)              */
9615/*                                                                          */
9616/* Every one of these functions is expected to succeed, so there is no      */
9617/* checking of return values.                                               */
9618/* ------------------------------------------------------------------------ */
9619void
9620ipf_destroy_all(softc)
9621	ipf_main_softc_t *softc;
9622{
9623
9624	if (softc->ipf_state_soft != NULL) {
9625		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9626		softc->ipf_state_soft = NULL;
9627	}
9628
9629	if (softc->ipf_nat_soft != NULL) {
9630		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9631		softc->ipf_nat_soft = NULL;
9632	}
9633
9634	if (softc->ipf_frag_soft != NULL) {
9635		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9636		softc->ipf_frag_soft = NULL;
9637	}
9638
9639	if (softc->ipf_auth_soft != NULL) {
9640		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9641		softc->ipf_auth_soft = NULL;
9642	}
9643
9644	if (softc->ipf_proxy_soft != NULL) {
9645		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9646		softc->ipf_proxy_soft = NULL;
9647	}
9648
9649	if (softc->ipf_sync_soft != NULL) {
9650		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9651		softc->ipf_sync_soft = NULL;
9652	}
9653
9654	if (softc->ipf_lookup_soft != NULL) {
9655		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9656		softc->ipf_lookup_soft = NULL;
9657	}
9658
9659#ifdef IPFILTER_LOG
9660	if (softc->ipf_log_soft != NULL) {
9661		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9662		softc->ipf_log_soft = NULL;
9663	}
9664#endif
9665
9666	ipf_main_soft_destroy(softc);
9667}
9668
9669
9670/* ------------------------------------------------------------------------ */
9671/* Function:   ipf_init_all                                                 */
9672/* Returns:    0 = success, -1 = failure                                    */
9673/* Parameters: softc(I) - pointer to soft context main structure            */
9674/*                                                                          */
9675/* Work through all of the subsystems inside IPFilter and call the init     */
9676/* function for each in an order that won't lead to a crash :)              */
9677/* ------------------------------------------------------------------------ */
9678int
9679ipf_init_all(softc)
9680	ipf_main_softc_t *softc;
9681{
9682
9683	if (ipf_main_soft_init(softc) == -1)
9684		return -1;
9685
9686#ifdef IPFILTER_LOG
9687	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9688		return -1;
9689#endif
9690
9691	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9692		return -1;
9693
9694	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9695		return -1;
9696
9697	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9698		return -1;
9699
9700	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9701		return -1;
9702
9703	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9704		return -1;
9705
9706	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9707		return -1;
9708
9709	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9710		return -1;
9711
9712	return 0;
9713}
9714
9715
9716/* ------------------------------------------------------------------------ */
9717/* Function:   ipf_fini_all                                                 */
9718/* Returns:    0 = success, -1 = failure                                    */
9719/* Parameters: softc(I) - pointer to soft context main structure            */
9720/*                                                                          */
9721/* Work through all of the subsystems inside IPFilter and call the fini     */
9722/* function for each in an order that won't lead to a crash :)              */
9723/* ------------------------------------------------------------------------ */
9724int
9725ipf_fini_all(softc)
9726	ipf_main_softc_t *softc;
9727{
9728
9729	ipf_token_flush(softc);
9730
9731	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9732		return -1;
9733
9734	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9735		return -1;
9736
9737	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9738		return -1;
9739
9740	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9741		return -1;
9742
9743	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9744		return -1;
9745
9746	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9747		return -1;
9748
9749	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9750		return -1;
9751
9752#ifdef IPFILTER_LOG
9753	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9754		return -1;
9755#endif
9756
9757	if (ipf_main_soft_fini(softc) == -1)
9758		return -1;
9759
9760	return 0;
9761}
9762
9763
9764/* ------------------------------------------------------------------------ */
9765/* Function:    ipf_rule_expire                                             */
9766/* Returns:     Nil                                                         */
9767/* Parameters:  softc(I) - pointer to soft context main structure           */
9768/*                                                                          */
9769/* At present this function exists just to support temporary addition of    */
9770/* firewall rules. Both inactive and active lists are scanned for items to  */
9771/* purge, as by rights, the expiration is computed as soon as the rule is   */
9772/* loaded in.                                                               */
9773/* ------------------------------------------------------------------------ */
9774void
9775ipf_rule_expire(softc)
9776	ipf_main_softc_t *softc;
9777{
9778	frentry_t *fr;
9779
9780	if ((softc->ipf_rule_explist[0] == NULL) &&
9781	    (softc->ipf_rule_explist[1] == NULL))
9782		return;
9783
9784	WRITE_ENTER(&softc->ipf_mutex);
9785
9786	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9787		/*
9788		 * Because the list is kept sorted on insertion, the fist
9789		 * one that dies in the future means no more work to do.
9790		 */
9791		if (fr->fr_die > softc->ipf_ticks)
9792			break;
9793		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9794	}
9795
9796	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9797		/*
9798		 * Because the list is kept sorted on insertion, the fist
9799		 * one that dies in the future means no more work to do.
9800		 */
9801		if (fr->fr_die > softc->ipf_ticks)
9802			break;
9803		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9804	}
9805
9806	RWLOCK_EXIT(&softc->ipf_mutex);
9807}
9808
9809
9810static int ipf_ht_node_cmp(struct host_node_s *, struct host_node_s *);
9811static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9812				      i6addr_t *);
9813
9814host_node_t RBI_ZERO(ipf_rb);
9815RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9816
9817
9818/* ------------------------------------------------------------------------ */
9819/* Function:    ipf_ht_node_cmp                                             */
9820/* Returns:     int   - 0 == nodes are the same, ..                         */
9821/* Parameters:  k1(I) - pointer to first key to compare                     */
9822/*              k2(I) - pointer to second key to compare                    */
9823/*                                                                          */
9824/* The "key" for the node is a combination of two fields: the address       */
9825/* family and the address itself.                                           */
9826/*                                                                          */
9827/* Because we're not actually interpreting the address data, it isn't       */
9828/* necessary to convert them to/from network/host byte order. The mask is   */
9829/* just used to remove bits that aren't significant - it doesn't matter     */
9830/* where they are, as long as they're always in the same place.             */
9831/*                                                                          */
9832/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9833/* this is where individual ones will differ the most - but not true for    */
9834/* for /48's, etc.                                                          */
9835/* ------------------------------------------------------------------------ */
9836static int
9837ipf_ht_node_cmp(k1, k2)
9838	struct host_node_s *k1, *k2;
9839{
9840	int i;
9841
9842	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9843	if (i != 0)
9844		return i;
9845
9846	if (k1->hn_addr.adf_family == AF_INET)
9847		return (k2->hn_addr.adf_addr.in4.s_addr -
9848			k1->hn_addr.adf_addr.in4.s_addr);
9849
9850	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9851	if (i != 0)
9852		return i;
9853	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9854	if (i != 0)
9855		return i;
9856	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9857	if (i != 0)
9858		return i;
9859	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9860	return i;
9861}
9862
9863
9864/* ------------------------------------------------------------------------ */
9865/* Function:    ipf_ht_node_make_key                                        */
9866/* Returns:     Nil                                                         */
9867/* parameters:  htp(I)    - pointer to address tracking structure           */
9868/*              key(I)    - where to store masked address for lookup        */
9869/*              family(I) - protocol family of address                      */
9870/*              addr(I)   - pointer to network address                      */
9871/*                                                                          */
9872/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9873/* copy the address passed in into the key structure whilst masking out the */
9874/* bits that we don't want.                                                 */
9875/*                                                                          */
9876/* Because the parser will set ht_netmask to 128 if there is no protocol    */
9877/* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9878/* have to be wary of that and not allow 32-128 to happen.                  */
9879/* ------------------------------------------------------------------------ */
9880static void
9881ipf_ht_node_make_key(htp, key, family, addr)
9882	host_track_t *htp;
9883	host_node_t *key;
9884	int family;
9885	i6addr_t *addr;
9886{
9887	key->hn_addr.adf_family = family;
9888	if (family == AF_INET) {
9889		u_32_t mask;
9890		int bits;
9891
9892		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9893		bits = htp->ht_netmask;
9894		if (bits >= 32) {
9895			mask = 0xffffffff;
9896		} else {
9897			mask = htonl(0xffffffff << (32 - bits));
9898		}
9899		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9900#ifdef USE_INET6
9901	} else {
9902		int bits = htp->ht_netmask;
9903
9904		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9905		if (bits > 96) {
9906			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9907					     htonl(0xffffffff << (128 - bits));
9908			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9909			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9910			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9911		} else if (bits > 64) {
9912			key->hn_addr.adf_addr.i6[3] = 0;
9913			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9914					     htonl(0xffffffff << (96 - bits));
9915			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9916			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9917		} else if (bits > 32) {
9918			key->hn_addr.adf_addr.i6[3] = 0;
9919			key->hn_addr.adf_addr.i6[2] = 0;
9920			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9921					     htonl(0xffffffff << (64 - bits));
9922			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9923		} else {
9924			key->hn_addr.adf_addr.i6[3] = 0;
9925			key->hn_addr.adf_addr.i6[2] = 0;
9926			key->hn_addr.adf_addr.i6[1] = 0;
9927			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9928					     htonl(0xffffffff << (32 - bits));
9929		}
9930#endif
9931	}
9932}
9933
9934
9935/* ------------------------------------------------------------------------ */
9936/* Function:    ipf_ht_node_add                                             */
9937/* Returns:     int       - 0 == success,  -1 == failure                    */
9938/* Parameters:  softc(I)  - pointer to soft context main structure          */
9939/*              htp(I)    - pointer to address tracking structure           */
9940/*              family(I) - protocol family of address                      */
9941/*              addr(I)   - pointer to network address                      */
9942/*                                                                          */
9943/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9944/*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9945/*                                                                          */
9946/* After preparing the key with the address information to find, look in    */
9947/* the red-black tree to see if the address is known. A successful call to  */
9948/* this function can mean one of two things: a new node was added to the    */
9949/* tree or a matching node exists and we're able to bump up its activity.   */
9950/* ------------------------------------------------------------------------ */
9951int
9952ipf_ht_node_add(softc, htp, family, addr)
9953	ipf_main_softc_t *softc;
9954	host_track_t *htp;
9955	int family;
9956	i6addr_t *addr;
9957{
9958	host_node_t *h;
9959	host_node_t k;
9960
9961	ipf_ht_node_make_key(htp, &k, family, addr);
9962
9963	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9964	if (h == NULL) {
9965		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9966			return -1;
9967		KMALLOC(h, host_node_t *);
9968		if (h == NULL) {
9969			DT(ipf_rb_no_mem);
9970			LBUMP(ipf_rb_no_mem);
9971			return -1;
9972		}
9973
9974		/*
9975		 * If there was a macro to initialise the RB node then that
9976		 * would get used here, but there isn't...
9977		 */
9978		bzero((char *)h, sizeof(*h));
9979		h->hn_addr = k.hn_addr;
9980		h->hn_addr.adf_family = k.hn_addr.adf_family;
9981		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9982		htp->ht_cur_nodes++;
9983	} else {
9984		if ((htp->ht_max_per_node != 0) &&
9985		    (h->hn_active >= htp->ht_max_per_node)) {
9986			DT(ipf_rb_node_max);
9987			LBUMP(ipf_rb_node_max);
9988			return -1;
9989		}
9990	}
9991
9992	h->hn_active++;
9993
9994	return 0;
9995}
9996
9997
9998/* ------------------------------------------------------------------------ */
9999/* Function:    ipf_ht_node_del                                             */
10000/* Returns:     int       - 0 == success,  -1 == failure                    */
10001/* parameters:  htp(I)    - pointer to address tracking structure           */
10002/*              family(I) - protocol family of address                      */
10003/*              addr(I)   - pointer to network address                      */
10004/*                                                                          */
10005/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
10006/*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
10007/*                                                                          */
10008/* Try and find the address passed in amongst the leavese on this tree to   */
10009/* be friend. If found then drop the active account for that node drops by  */
10010/* one. If that count reaches 0, it is time to free it all up.              */
10011/* ------------------------------------------------------------------------ */
10012int
10013ipf_ht_node_del(htp, family, addr)
10014	host_track_t *htp;
10015	int family;
10016	i6addr_t *addr;
10017{
10018	host_node_t *h;
10019	host_node_t k;
10020
10021	ipf_ht_node_make_key(htp, &k, family, addr);
10022
10023	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
10024	if (h == NULL) {
10025		return -1;
10026	} else {
10027		h->hn_active--;
10028		if (h->hn_active == 0) {
10029			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10030			htp->ht_cur_nodes--;
10031			KFREE(h);
10032		}
10033	}
10034
10035	return 0;
10036}
10037
10038
10039/* ------------------------------------------------------------------------ */
10040/* Function:    ipf_rb_ht_init                                              */
10041/* Returns:     Nil                                                         */
10042/* Parameters:  head(I) - pointer to host tracking structure                */
10043/*                                                                          */
10044/* Initialise the host tracking structure to be ready for use above.        */
10045/* ------------------------------------------------------------------------ */
10046void
10047ipf_rb_ht_init(head)
10048	host_track_t *head;
10049{
10050	RBI_INIT(ipf_rb, &head->ht_root);
10051}
10052
10053
10054/* ------------------------------------------------------------------------ */
10055/* Function:    ipf_rb_ht_freenode                                          */
10056/* Returns:     Nil                                                         */
10057/* Parameters:  head(I) - pointer to host tracking structure                */
10058/*              arg(I)  - additional argument from walk caller              */
10059/*                                                                          */
10060/* Free an actual host_node_t structure.                                    */
10061/* ------------------------------------------------------------------------ */
10062void
10063ipf_rb_ht_freenode(node, arg)
10064	host_node_t *node;
10065	void *arg;
10066{
10067	KFREE(node);
10068}
10069
10070
10071/* ------------------------------------------------------------------------ */
10072/* Function:    ipf_rb_ht_flush                                             */
10073/* Returns:     Nil                                                         */
10074/* Parameters:  head(I) - pointer to host tracking structure                */
10075/*                                                                          */
10076/* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10077/* and free'ing each one.                                                   */
10078/* ------------------------------------------------------------------------ */
10079void
10080ipf_rb_ht_flush(head)
10081	host_track_t *head;
10082{
10083	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10084}
10085
10086
10087/* ------------------------------------------------------------------------ */
10088/* Function:    ipf_slowtimer                                               */
10089/* Returns:     Nil                                                         */
10090/* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10091/*                                                                          */
10092/* Slowly expire held state for fragments.  Timeouts are set * in           */
10093/* expectation of this being called twice per second.                       */
10094/* ------------------------------------------------------------------------ */
10095void
10096ipf_slowtimer(softc)
10097	ipf_main_softc_t *softc;
10098{
10099
10100	ipf_token_expire(softc);
10101	ipf_frag_expire(softc);
10102	ipf_state_expire(softc);
10103	ipf_nat_expire(softc);
10104	ipf_auth_expire(softc);
10105	ipf_lookup_expire(softc);
10106	ipf_rule_expire(softc);
10107	ipf_sync_expire(softc);
10108	softc->ipf_ticks++;
10109}
10110
10111
10112/* ------------------------------------------------------------------------ */
10113/* Function:    ipf_inet_mask_add                                           */
10114/* Returns:     Nil                                                         */
10115/* Parameters:  bits(I) - pointer to nat context information                */
10116/*              mtab(I) - pointer to mask hash table structure              */
10117/*                                                                          */
10118/* When called, bits represents the mask of a new NAT rule that has just    */
10119/* been added. This function inserts a bitmask into the array of masks to   */
10120/* search when searching for a matching NAT rule for a packet.              */
10121/* Prevention of duplicate masks is achieved by checking the use count for  */
10122/* a given netmask.                                                         */
10123/* ------------------------------------------------------------------------ */
10124void
10125ipf_inet_mask_add(bits, mtab)
10126	int bits;
10127	ipf_v4_masktab_t *mtab;
10128{
10129	u_32_t mask;
10130	int i, j;
10131
10132	mtab->imt4_masks[bits]++;
10133	if (mtab->imt4_masks[bits] > 1)
10134		return;
10135
10136	if (bits == 0)
10137		mask = 0;
10138	else
10139		mask = 0xffffffff << (32 - bits);
10140
10141	for (i = 0; i < 33; i++) {
10142		if (ntohl(mtab->imt4_active[i]) < mask) {
10143			for (j = 32; j > i; j--)
10144				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10145			mtab->imt4_active[i] = htonl(mask);
10146			break;
10147		}
10148	}
10149	mtab->imt4_max++;
10150}
10151
10152
10153/* ------------------------------------------------------------------------ */
10154/* Function:    ipf_inet_mask_del                                           */
10155/* Returns:     Nil                                                         */
10156/* Parameters:  bits(I) - number of bits set in the netmask                 */
10157/*              mtab(I) - pointer to mask hash table structure              */
10158/*                                                                          */
10159/* Remove the 32bit bitmask represented by "bits" from the collection of    */
10160/* netmasks stored inside of mtab.                                          */
10161/* ------------------------------------------------------------------------ */
10162void
10163ipf_inet_mask_del(bits, mtab)
10164	int bits;
10165	ipf_v4_masktab_t *mtab;
10166{
10167	u_32_t mask;
10168	int i, j;
10169
10170	mtab->imt4_masks[bits]--;
10171	if (mtab->imt4_masks[bits] > 0)
10172		return;
10173
10174	mask = htonl(0xffffffff << (32 - bits));
10175	for (i = 0; i < 33; i++) {
10176		if (mtab->imt4_active[i] == mask) {
10177			for (j = i + 1; j < 33; j++)
10178				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10179			break;
10180		}
10181	}
10182	mtab->imt4_max--;
10183	ASSERT(mtab->imt4_max >= 0);
10184}
10185
10186
10187#ifdef USE_INET6
10188/* ------------------------------------------------------------------------ */
10189/* Function:    ipf_inet6_mask_add                                          */
10190/* Returns:     Nil                                                         */
10191/* Parameters:  bits(I) - number of bits set in mask                        */
10192/*              mask(I) - pointer to mask to add                            */
10193/*              mtab(I) - pointer to mask hash table structure              */
10194/*                                                                          */
10195/* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10196/* has just been added. This function inserts a bitmask into the array of   */
10197/* masks to search when searching for a matching NAT rule for a packet.     */
10198/* Prevention of duplicate masks is achieved by checking the use count for  */
10199/* a given netmask.                                                         */
10200/* ------------------------------------------------------------------------ */
10201void
10202ipf_inet6_mask_add(bits, mask, mtab)
10203	int bits;
10204	i6addr_t *mask;
10205	ipf_v6_masktab_t *mtab;
10206{
10207	i6addr_t zero;
10208	int i, j;
10209
10210	mtab->imt6_masks[bits]++;
10211	if (mtab->imt6_masks[bits] > 1)
10212		return;
10213
10214	if (bits == 0) {
10215		mask = &zero;
10216		zero.i6[0] = 0;
10217		zero.i6[1] = 0;
10218		zero.i6[2] = 0;
10219		zero.i6[3] = 0;
10220	}
10221
10222	for (i = 0; i < 129; i++) {
10223		if (IP6_LT(&mtab->imt6_active[i], mask)) {
10224			for (j = 128; j > i; j--)
10225				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10226			mtab->imt6_active[i] = *mask;
10227			break;
10228		}
10229	}
10230	mtab->imt6_max++;
10231}
10232
10233
10234/* ------------------------------------------------------------------------ */
10235/* Function:    ipf_inet6_mask_del                                          */
10236/* Returns:     Nil                                                         */
10237/* Parameters:  bits(I) - number of bits set in mask                        */
10238/*              mask(I) - pointer to mask to remove                         */
10239/*              mtab(I) - pointer to mask hash table structure              */
10240/*                                                                          */
10241/* Remove the 128bit bitmask represented by "bits" from the collection of   */
10242/* netmasks stored inside of mtab.                                          */
10243/* ------------------------------------------------------------------------ */
10244void
10245ipf_inet6_mask_del(bits, mask, mtab)
10246	int bits;
10247	i6addr_t *mask;
10248	ipf_v6_masktab_t *mtab;
10249{
10250	i6addr_t zero;
10251	int i, j;
10252
10253	mtab->imt6_masks[bits]--;
10254	if (mtab->imt6_masks[bits] > 0)
10255		return;
10256
10257	if (bits == 0)
10258		mask = &zero;
10259	zero.i6[0] = 0;
10260	zero.i6[1] = 0;
10261	zero.i6[2] = 0;
10262	zero.i6[3] = 0;
10263
10264	for (i = 0; i < 129; i++) {
10265		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10266			for (j = i + 1; j < 129; j++) {
10267				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10268				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10269					break;
10270			}
10271			break;
10272		}
10273	}
10274	mtab->imt6_max--;
10275	ASSERT(mtab->imt6_max >= 0);
10276}
10277#endif
10278