xref: /f-stack/freebsd/contrib/ipfilter/netinet/fil.c (revision 22ce4aff)
1 /*	$FreeBSD$	*/
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>
101 extern struct callout ipf_slowtimer_ch;
102 #endif
103 /* END OF INCLUDES */
104 
105 #if !defined(lint)
106 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
107 static const char rcsid[] = "@(#)$FreeBSD$";
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"
114 extern	int	opts;
115 extern	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 
123 static	INLINE int	ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
124 static	u_32_t		ipf_checkcipso __P((fr_info_t *, u_char *, int));
125 static	u_32_t		ipf_checkripso __P((u_char *));
126 static	u_32_t		ipf_decaps __P((fr_info_t *, u_32_t, int));
127 #ifdef IPFILTER_LOG
128 static	frentry_t	*ipf_dolog __P((fr_info_t *, u_32_t *));
129 #endif
130 static	int		ipf_flushlist __P((ipf_main_softc_t *, int *,
131 					   frentry_t **));
132 static	int		ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
133 					      int));
134 static	ipfunc_t	ipf_findfunc __P((ipfunc_t));
135 static	void		*ipf_findlookup __P((ipf_main_softc_t *, int,
136 					     frentry_t *,
137 					     i6addr_t *, i6addr_t *));
138 static	frentry_t	*ipf_firewall __P((fr_info_t *, u_32_t *));
139 static	int		ipf_fr_matcharray __P((fr_info_t *, int *));
140 static	int		ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
141 					    void *));
142 static	void		ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
143 static	int		ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
144 static	int		ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
145 					 ipfgeniter_t *));
146 static	void		ipf_getstat __P((ipf_main_softc_t *,
147 					 struct friostat *, int));
148 static	int		ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
149 static	void		ipf_group_free __P((frgroup_t *));
150 static	int		ipf_grpmapfini __P((struct ipf_main_softc_s *,
151 					    frentry_t *));
152 static	int		ipf_grpmapinit __P((struct ipf_main_softc_s *,
153 					    frentry_t *));
154 static	frentry_t	*ipf_nextrule __P((ipf_main_softc_t *, int, int,
155 					   frentry_t *, int));
156 static	int		ipf_portcheck __P((frpcmp_t *, u_32_t));
157 static	INLINE int	ipf_pr_ah __P((fr_info_t *));
158 static	INLINE void	ipf_pr_esp __P((fr_info_t *));
159 static	INLINE void	ipf_pr_gre __P((fr_info_t *));
160 static	INLINE void	ipf_pr_udp __P((fr_info_t *));
161 static	INLINE void	ipf_pr_tcp __P((fr_info_t *));
162 static	INLINE void	ipf_pr_icmp __P((fr_info_t *));
163 static	INLINE void	ipf_pr_ipv4hdr __P((fr_info_t *));
164 static	INLINE void	ipf_pr_short __P((fr_info_t *, int));
165 static	INLINE int	ipf_pr_tcpcommon __P((fr_info_t *));
166 static	INLINE int	ipf_pr_udpcommon __P((fr_info_t *));
167 static	void		ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
168 					     int, int));
169 static	void		ipf_rule_expire_insert __P((ipf_main_softc_t *,
170 						    frentry_t *, int));
171 static	int		ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
172 					  void *));
173 static	void		ipf_token_flush __P((ipf_main_softc_t *));
174 static	void		ipf_token_unlink __P((ipf_main_softc_t *,
175 					      ipftoken_t *));
176 static	ipftuneable_t	*ipf_tune_findbyname __P((ipftuneable_t *,
177 						  const char *));
178 static	ipftuneable_t	*ipf_tune_findbycookie __P((ipftuneable_t **, void *,
179 						    void **));
180 static	int		ipf_updateipid __P((fr_info_t *));
181 static	int		ipf_settimeout __P((struct ipf_main_softc_s *,
182 					    struct ipftuneable *,
183 					    ipftuneval_t *));
184 #if !defined(_KERNEL) || SOLARIS
185 static	int		ppsratecheck(struct timeval *, int *, int);
186 #endif
187 
188 
189 /*
190  * bit values for identifying presence of individual IP options
191  * All of these tables should be ordered by increasing key value on the left
192  * hand side to allow for binary searching of the array and include a trailer
193  * with a 0 for the bitmask for linear searches to easily find the end with.
194  */
195 static const	struct	optlist	ipopts[] = {
196 	{ IPOPT_NOP,	0x000001 },
197 	{ IPOPT_RR,	0x000002 },
198 	{ IPOPT_ZSU,	0x000004 },
199 	{ IPOPT_MTUP,	0x000008 },
200 	{ IPOPT_MTUR,	0x000010 },
201 	{ IPOPT_ENCODE,	0x000020 },
202 	{ IPOPT_TS,	0x000040 },
203 	{ IPOPT_TR,	0x000080 },
204 	{ IPOPT_SECURITY, 0x000100 },
205 	{ IPOPT_LSRR,	0x000200 },
206 	{ IPOPT_E_SEC,	0x000400 },
207 	{ IPOPT_CIPSO,	0x000800 },
208 	{ IPOPT_SATID,	0x001000 },
209 	{ IPOPT_SSRR,	0x002000 },
210 	{ IPOPT_ADDEXT,	0x004000 },
211 	{ IPOPT_VISA,	0x008000 },
212 	{ IPOPT_IMITD,	0x010000 },
213 	{ IPOPT_EIP,	0x020000 },
214 	{ IPOPT_FINN,	0x040000 },
215 	{ 0,		0x000000 }
216 };
217 
218 #ifdef USE_INET6
219 static const struct optlist ip6exthdr[] = {
220 	{ IPPROTO_HOPOPTS,		0x000001 },
221 	{ IPPROTO_IPV6,			0x000002 },
222 	{ IPPROTO_ROUTING,		0x000004 },
223 	{ IPPROTO_FRAGMENT,		0x000008 },
224 	{ IPPROTO_ESP,			0x000010 },
225 	{ IPPROTO_AH,			0x000020 },
226 	{ IPPROTO_NONE,			0x000040 },
227 	{ IPPROTO_DSTOPTS,		0x000080 },
228 	{ IPPROTO_MOBILITY,		0x000100 },
229 	{ 0,				0 }
230 };
231 #endif
232 
233 /*
234  * bit values for identifying presence of individual IP security options
235  */
236 static const	struct	optlist	secopt[] = {
237 	{ IPSO_CLASS_RES4,	0x01 },
238 	{ IPSO_CLASS_TOPS,	0x02 },
239 	{ IPSO_CLASS_SECR,	0x04 },
240 	{ IPSO_CLASS_RES3,	0x08 },
241 	{ IPSO_CLASS_CONF,	0x10 },
242 	{ IPSO_CLASS_UNCL,	0x20 },
243 	{ IPSO_CLASS_RES2,	0x40 },
244 	{ IPSO_CLASS_RES1,	0x80 }
245 };
246 
247 char	ipfilter_version[] = IPL_VERSION;
248 
249 int	ipf_features = 0
250 #ifdef	IPFILTER_LKM
251 		| IPF_FEAT_LKM
252 #endif
253 #ifdef	IPFILTER_LOG
254 		| IPF_FEAT_LOG
255 #endif
256 		| IPF_FEAT_LOOKUP
257 #ifdef	IPFILTER_BPF
258 		| IPF_FEAT_BPF
259 #endif
260 #ifdef	IPFILTER_COMPILED
261 		| IPF_FEAT_COMPILED
262 #endif
263 #ifdef	IPFILTER_CKSUM
264 		| IPF_FEAT_CKSUM
265 #endif
266 		| IPF_FEAT_SYNC
267 #ifdef	IPFILTER_SCAN
268 		| IPF_FEAT_SCAN
269 #endif
270 #ifdef	USE_INET6
271 		| IPF_FEAT_IPV6
272 #endif
273 	;
274 
275 
276 /*
277  * Table of functions available for use with call rules.
278  */
279 static ipfunc_resolve_t ipf_availfuncs[] = {
280 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
281 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
282 	{ "",	      NULL,	      NULL,	      NULL }
283 };
284 
285 static ipftuneable_t ipf_main_tuneables[] = {
286 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
287 		"ipf_flags",		0,	0xffffffff,
288 		stsizeof(ipf_main_softc_t, ipf_flags),
289 		0,			NULL,	NULL },
290 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
291 		"active",		0,	0,
292 		stsizeof(ipf_main_softc_t, ipf_active),
293 		IPFT_RDONLY,		NULL,	NULL },
294 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
295 		"control_forwarding",	0, 1,
296 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
297 		0,			NULL,	NULL },
298 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
299 		"update_ipid",		0,	1,
300 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
301 		0,			NULL,	NULL },
302 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
303 		"chksrc",		0,	1,
304 		stsizeof(ipf_main_softc_t, ipf_chksrc),
305 		0,			NULL,	NULL },
306 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
307 		"min_ttl",		0,	1,
308 		stsizeof(ipf_main_softc_t, ipf_minttl),
309 		0,			NULL,	NULL },
310 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
311 		"icmp_minfragmtu",	0,	1,
312 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
313 		0,			NULL,	NULL },
314 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
315 		"default_pass",		0,	0xffffffff,
316 		stsizeof(ipf_main_softc_t, ipf_pass),
317 		0,			NULL,	NULL },
318 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
319 		"tcp_idle_timeout",	1,	0x7fffffff,
320 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
321 		0,			NULL,	ipf_settimeout },
322 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
323 		"tcp_close_wait",	1,	0x7fffffff,
324 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
325 		0,			NULL,	ipf_settimeout },
326 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
327 		"tcp_last_ack",		1,	0x7fffffff,
328 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
329 		0,			NULL,	ipf_settimeout },
330 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
331 		"tcp_timeout",		1,	0x7fffffff,
332 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
333 		0,			NULL,	ipf_settimeout },
334 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
335 		"tcp_syn_sent",		1,	0x7fffffff,
336 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
337 		0,			NULL,	ipf_settimeout },
338 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
339 		"tcp_syn_received",	1,	0x7fffffff,
340 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
341 		0,			NULL,	ipf_settimeout },
342 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
343 		"tcp_closed",		1,	0x7fffffff,
344 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
345 		0,			NULL,	ipf_settimeout },
346 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
347 		"tcp_half_closed",	1,	0x7fffffff,
348 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
349 		0,			NULL,	ipf_settimeout },
350 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
351 		"tcp_time_wait",	1,	0x7fffffff,
352 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
353 		0,			NULL,	ipf_settimeout },
354 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
355 		"udp_timeout",		1,	0x7fffffff,
356 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
357 		0,			NULL,	ipf_settimeout },
358 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
359 		"udp_ack_timeout",	1,	0x7fffffff,
360 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
361 		0,			NULL,	ipf_settimeout },
362 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
363 		"icmp_timeout",		1,	0x7fffffff,
364 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
365 		0,			NULL,	ipf_settimeout },
366 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
367 		"icmp_ack_timeout",	1,	0x7fffffff,
368 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
369 		0,			NULL,	ipf_settimeout },
370 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
371 		"ip_timeout",		1,	0x7fffffff,
372 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
373 		0,			NULL,	ipf_settimeout },
374 #if defined(INSTANCES) && defined(_KERNEL)
375 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
376 		"intercept_loopback",	0,	1,
377 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
378 		0,			NULL,	ipf_set_loopback },
379 #endif
380 	{ { 0 },
381 		NULL,			0,	0,
382 		0,
383 		0,			NULL,	NULL }
384 };
385 
386 
387 /*
388  * The next section of code is a collection of small routines that set
389  * fields in the fr_info_t structure passed based on properties of the
390  * current packet.  There are different routines for the same protocol
391  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
392  * will "special" inspection for setup, is now more easily done by adding
393  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
394  * adding more code to a growing switch statement.
395  */
396 #ifdef USE_INET6
397 static	INLINE int	ipf_pr_ah6 __P((fr_info_t *));
398 static	INLINE void	ipf_pr_esp6 __P((fr_info_t *));
399 static	INLINE void	ipf_pr_gre6 __P((fr_info_t *));
400 static	INLINE void	ipf_pr_udp6 __P((fr_info_t *));
401 static	INLINE void	ipf_pr_tcp6 __P((fr_info_t *));
402 static	INLINE void	ipf_pr_icmp6 __P((fr_info_t *));
403 static	INLINE void	ipf_pr_ipv6hdr __P((fr_info_t *));
404 static	INLINE void	ipf_pr_short6 __P((fr_info_t *, int));
405 static	INLINE int	ipf_pr_hopopts6 __P((fr_info_t *));
406 static	INLINE int	ipf_pr_mobility6 __P((fr_info_t *));
407 static	INLINE int	ipf_pr_routing6 __P((fr_info_t *));
408 static	INLINE int	ipf_pr_dstopts6 __P((fr_info_t *));
409 static	INLINE int	ipf_pr_fragment6 __P((fr_info_t *));
410 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
411 
412 
413 /* ------------------------------------------------------------------------ */
414 /* Function:    ipf_pr_short6                                               */
415 /* Returns:     void                                                        */
416 /* Parameters:  fin(I)  - pointer to packet information                     */
417 /*              xmin(I) - minimum header size                               */
418 /*                                                                          */
419 /* IPv6 Only                                                                */
420 /* This is function enforces the 'is a packet too short to be legit' rule   */
421 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
422 /* for ipf_pr_short() for more details.                                     */
423 /* ------------------------------------------------------------------------ */
424 static INLINE void
ipf_pr_short6(fin,xmin)425 ipf_pr_short6(fin, xmin)
426 	fr_info_t *fin;
427 	int xmin;
428 {
429 
430 	if (fin->fin_dlen < xmin)
431 		fin->fin_flx |= FI_SHORT;
432 }
433 
434 
435 /* ------------------------------------------------------------------------ */
436 /* Function:    ipf_pr_ipv6hdr                                              */
437 /* Returns:     void                                                        */
438 /* Parameters:  fin(I) - pointer to packet information                      */
439 /*                                                                          */
440 /* IPv6 Only                                                                */
441 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
442 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
443 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
444 /* of that possibility arising.                                             */
445 /* ------------------------------------------------------------------------ */
446 static INLINE void
ipf_pr_ipv6hdr(fin)447 ipf_pr_ipv6hdr(fin)
448 	fr_info_t *fin;
449 {
450 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
451 	int p, go = 1, i, hdrcount;
452 	fr_ip_t *fi = &fin->fin_fi;
453 
454 	fin->fin_off = 0;
455 
456 	fi->fi_tos = 0;
457 	fi->fi_optmsk = 0;
458 	fi->fi_secmsk = 0;
459 	fi->fi_auth = 0;
460 
461 	p = ip6->ip6_nxt;
462 	fin->fin_crc = p;
463 	fi->fi_ttl = ip6->ip6_hlim;
464 	fi->fi_src.in6 = ip6->ip6_src;
465 	fin->fin_crc += fi->fi_src.i6[0];
466 	fin->fin_crc += fi->fi_src.i6[1];
467 	fin->fin_crc += fi->fi_src.i6[2];
468 	fin->fin_crc += fi->fi_src.i6[3];
469 	fi->fi_dst.in6 = ip6->ip6_dst;
470 	fin->fin_crc += fi->fi_dst.i6[0];
471 	fin->fin_crc += fi->fi_dst.i6[1];
472 	fin->fin_crc += fi->fi_dst.i6[2];
473 	fin->fin_crc += fi->fi_dst.i6[3];
474 	fin->fin_id = 0;
475 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
476 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
477 
478 	hdrcount = 0;
479 	while (go && !(fin->fin_flx & FI_SHORT)) {
480 		switch (p)
481 		{
482 		case IPPROTO_UDP :
483 			ipf_pr_udp6(fin);
484 			go = 0;
485 			break;
486 
487 		case IPPROTO_TCP :
488 			ipf_pr_tcp6(fin);
489 			go = 0;
490 			break;
491 
492 		case IPPROTO_ICMPV6 :
493 			ipf_pr_icmp6(fin);
494 			go = 0;
495 			break;
496 
497 		case IPPROTO_GRE :
498 			ipf_pr_gre6(fin);
499 			go = 0;
500 			break;
501 
502 		case IPPROTO_HOPOPTS :
503 			p = ipf_pr_hopopts6(fin);
504 			break;
505 
506 		case IPPROTO_MOBILITY :
507 			p = ipf_pr_mobility6(fin);
508 			break;
509 
510 		case IPPROTO_DSTOPTS :
511 			p = ipf_pr_dstopts6(fin);
512 			break;
513 
514 		case IPPROTO_ROUTING :
515 			p = ipf_pr_routing6(fin);
516 			break;
517 
518 		case IPPROTO_AH :
519 			p = ipf_pr_ah6(fin);
520 			break;
521 
522 		case IPPROTO_ESP :
523 			ipf_pr_esp6(fin);
524 			go = 0;
525 			break;
526 
527 		case IPPROTO_IPV6 :
528 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
529 				if (ip6exthdr[i].ol_val == p) {
530 					fin->fin_flx |= ip6exthdr[i].ol_bit;
531 					break;
532 				}
533 			go = 0;
534 			break;
535 
536 		case IPPROTO_NONE :
537 			go = 0;
538 			break;
539 
540 		case IPPROTO_FRAGMENT :
541 			p = ipf_pr_fragment6(fin);
542 			/*
543 			 * Given that the only fragments we want to let through
544 			 * (where fin_off != 0) are those where the non-first
545 			 * fragments only have data, we can safely stop looking
546 			 * at headers if this is a non-leading fragment.
547 			 */
548 			if (fin->fin_off != 0)
549 				go = 0;
550 			break;
551 
552 		default :
553 			go = 0;
554 			break;
555 		}
556 		hdrcount++;
557 
558 		/*
559 		 * It is important to note that at this point, for the
560 		 * extension headers (go != 0), the entire header may not have
561 		 * been pulled up when the code gets to this point.  This is
562 		 * only done for "go != 0" because the other header handlers
563 		 * will all pullup their complete header.  The other indicator
564 		 * of an incomplete packet is that this was just an extension
565 		 * header.
566 		 */
567 		if ((go != 0) && (p != IPPROTO_NONE) &&
568 		    (ipf_pr_pullup(fin, 0) == -1)) {
569 			p = IPPROTO_NONE;
570 			break;
571 		}
572 	}
573 
574 	/*
575 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
576 	 * and destroy whatever packet was here.  The caller of this function
577 	 * expects us to return if there is a problem with ipf_pullup.
578 	 */
579 	if (fin->fin_m == NULL) {
580 		ipf_main_softc_t *softc = fin->fin_main_soft;
581 
582 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
583 		return;
584 	}
585 
586 	fi->fi_p = p;
587 
588 	/*
589 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
590 	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
591 	 */
592 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
593 		ipf_main_softc_t *softc = fin->fin_main_soft;
594 
595 		fin->fin_flx |= FI_BAD;
596 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
597 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
598 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
599 	}
600 }
601 
602 
603 /* ------------------------------------------------------------------------ */
604 /* Function:    ipf_pr_ipv6exthdr                                           */
605 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
606 /*                                 or NULL if there is a prolblem.          */
607 /* Parameters:  fin(I)      - pointer to packet information                 */
608 /*              multiple(I) - flag indicating yes/no if multiple occurances */
609 /*                            of this extension header are allowed.         */
610 /*              proto(I)    - protocol number for this extension header     */
611 /*                                                                          */
612 /* IPv6 Only                                                                */
613 /* This function embodies a number of common checks that all IPv6 extension */
614 /* headers must be subjected to.  For example, making sure the packet is    */
615 /* big enough for it to be in, checking if it is repeated and setting a     */
616 /* flag to indicate its presence.                                           */
617 /* ------------------------------------------------------------------------ */
618 static INLINE struct ip6_ext *
ipf_pr_ipv6exthdr(fin,multiple,proto)619 ipf_pr_ipv6exthdr(fin, multiple, proto)
620 	fr_info_t *fin;
621 	int multiple, proto;
622 {
623 	ipf_main_softc_t *softc = fin->fin_main_soft;
624 	struct ip6_ext *hdr;
625 	u_short shift;
626 	int i;
627 
628 	fin->fin_flx |= FI_V6EXTHDR;
629 
630 				/* 8 is default length of extension hdr */
631 	if ((fin->fin_dlen - 8) < 0) {
632 		fin->fin_flx |= FI_SHORT;
633 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
634 		return NULL;
635 	}
636 
637 	if (ipf_pr_pullup(fin, 8) == -1) {
638 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
639 		return NULL;
640 	}
641 
642 	hdr = fin->fin_dp;
643 	switch (proto)
644 	{
645 	case IPPROTO_FRAGMENT :
646 		shift = 8;
647 		break;
648 	default :
649 		shift = 8 + (hdr->ip6e_len << 3);
650 		break;
651 	}
652 
653 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
654 		fin->fin_flx |= FI_BAD;
655 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
656 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
657 		return NULL;
658 	}
659 
660 	fin->fin_dp = (char *)fin->fin_dp + shift;
661 	fin->fin_dlen -= shift;
662 
663 	/*
664 	 * If we have seen a fragment header, do not set any flags to indicate
665 	 * the presence of this extension header as it has no impact on the
666 	 * end result until after it has been defragmented.
667 	 */
668 	if (fin->fin_flx & FI_FRAG)
669 		return hdr;
670 
671 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
672 		if (ip6exthdr[i].ol_val == proto) {
673 			/*
674 			 * Most IPv6 extension headers are only allowed once.
675 			 */
676 			if ((multiple == 0) &&
677 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
678 				fin->fin_flx |= FI_BAD;
679 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
680 			} else
681 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
682 			break;
683 		}
684 
685 	return hdr;
686 }
687 
688 
689 /* ------------------------------------------------------------------------ */
690 /* Function:    ipf_pr_hopopts6                                             */
691 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
692 /* Parameters:  fin(I) - pointer to packet information                      */
693 /*                                                                          */
694 /* IPv6 Only                                                                */
695 /* This is function checks pending hop by hop options extension header      */
696 /* ------------------------------------------------------------------------ */
697 static INLINE int
ipf_pr_hopopts6(fin)698 ipf_pr_hopopts6(fin)
699 	fr_info_t *fin;
700 {
701 	struct ip6_ext *hdr;
702 
703 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
704 	if (hdr == NULL)
705 		return IPPROTO_NONE;
706 	return hdr->ip6e_nxt;
707 }
708 
709 
710 /* ------------------------------------------------------------------------ */
711 /* Function:    ipf_pr_mobility6                                            */
712 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
713 /* Parameters:  fin(I) - pointer to packet information                      */
714 /*                                                                          */
715 /* IPv6 Only                                                                */
716 /* This is function checks the IPv6 mobility extension header               */
717 /* ------------------------------------------------------------------------ */
718 static INLINE int
ipf_pr_mobility6(fin)719 ipf_pr_mobility6(fin)
720 	fr_info_t *fin;
721 {
722 	struct ip6_ext *hdr;
723 
724 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
725 	if (hdr == NULL)
726 		return IPPROTO_NONE;
727 	return hdr->ip6e_nxt;
728 }
729 
730 
731 /* ------------------------------------------------------------------------ */
732 /* Function:    ipf_pr_routing6                                             */
733 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
734 /* Parameters:  fin(I) - pointer to packet information                      */
735 /*                                                                          */
736 /* IPv6 Only                                                                */
737 /* This is function checks pending routing extension header                 */
738 /* ------------------------------------------------------------------------ */
739 static INLINE int
ipf_pr_routing6(fin)740 ipf_pr_routing6(fin)
741 	fr_info_t *fin;
742 {
743 	struct ip6_routing *hdr;
744 
745 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
746 	if (hdr == NULL)
747 		return IPPROTO_NONE;
748 
749 	switch (hdr->ip6r_type)
750 	{
751 	case 0 :
752 		/*
753 		 * Nasty extension header length?
754 		 */
755 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
756 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
757 			ipf_main_softc_t *softc = fin->fin_main_soft;
758 
759 			fin->fin_flx |= FI_BAD;
760 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
761 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
762 			return IPPROTO_NONE;
763 		}
764 		break;
765 
766 	default :
767 		break;
768 	}
769 
770 	return hdr->ip6r_nxt;
771 }
772 
773 
774 /* ------------------------------------------------------------------------ */
775 /* Function:    ipf_pr_fragment6                                            */
776 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
777 /* Parameters:  fin(I) - pointer to packet information                      */
778 /*                                                                          */
779 /* IPv6 Only                                                                */
780 /* Examine the IPv6 fragment header and extract fragment offset information.*/
781 /*                                                                          */
782 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
783 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
784 /* packets with a fragment header can fit into.  They are as follows:       */
785 /*                                                                          */
786 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
787 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
788 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
789 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
790 /* 5.  [IPV6][0-n EH][FH][data]                                             */
791 /*                                                                          */
792 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
793 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
794 /*                                                                          */
795 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
796 /* scenario in which they happen is in extreme circumstances that are most  */
797 /* likely to be an indication of an attack rather than normal traffic.      */
798 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
799 /* are two rules that can be used to guard against type 3 packets: L4       */
800 /* headers must always be in a packet that has the offset field set to 0    */
801 /* and no packet is allowed to overlay that where offset = 0.               */
802 /* ------------------------------------------------------------------------ */
803 static INLINE int
ipf_pr_fragment6(fin)804 ipf_pr_fragment6(fin)
805 	fr_info_t *fin;
806 {
807 	ipf_main_softc_t *softc = fin->fin_main_soft;
808 	struct ip6_frag *frag;
809 
810 	fin->fin_flx |= FI_FRAG;
811 
812 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
813 	if (frag == NULL) {
814 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
815 		return IPPROTO_NONE;
816 	}
817 
818 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
819 		/*
820 		 * Any fragment that isn't the last fragment must have its
821 		 * length as a multiple of 8.
822 		 */
823 		if ((fin->fin_plen & 7) != 0) {
824 			fin->fin_flx |= FI_BAD;
825 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
826 		}
827 	}
828 
829 	fin->fin_fraghdr = frag;
830 	fin->fin_id = frag->ip6f_ident;
831 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
832 	if (fin->fin_off != 0)
833 		fin->fin_flx |= FI_FRAGBODY;
834 
835 	/*
836 	 * Jumbograms aren't handled, so the max. length is 64k
837 	 */
838 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
839 		  fin->fin_flx |= FI_BAD;
840 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
841 	}
842 
843 	/*
844 	 * We don't know where the transport layer header (or whatever is next
845 	 * is), as it could be behind destination options (amongst others) so
846 	 * return the fragment header as the type of packet this is.  Note that
847 	 * this effectively disables the fragment cache for > 1 protocol at a
848 	 * time.
849 	 */
850 	return frag->ip6f_nxt;
851 }
852 
853 
854 /* ------------------------------------------------------------------------ */
855 /* Function:    ipf_pr_dstopts6                                             */
856 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
857 /* Parameters:  fin(I) - pointer to packet information                      */
858 /*                                                                          */
859 /* IPv6 Only                                                                */
860 /* This is function checks pending destination options extension header     */
861 /* ------------------------------------------------------------------------ */
862 static INLINE int
ipf_pr_dstopts6(fin)863 ipf_pr_dstopts6(fin)
864 	fr_info_t *fin;
865 {
866 	ipf_main_softc_t *softc = fin->fin_main_soft;
867 	struct ip6_ext *hdr;
868 
869 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
870 	if (hdr == NULL) {
871 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
872 		return IPPROTO_NONE;
873 	}
874 	return hdr->ip6e_nxt;
875 }
876 
877 
878 /* ------------------------------------------------------------------------ */
879 /* Function:    ipf_pr_icmp6                                                */
880 /* Returns:     void                                                        */
881 /* Parameters:  fin(I) - pointer to packet information                      */
882 /*                                                                          */
883 /* IPv6 Only                                                                */
884 /* This routine is mainly concerned with determining the minimum valid size */
885 /* for an ICMPv6 packet.                                                    */
886 /* ------------------------------------------------------------------------ */
887 static INLINE void
ipf_pr_icmp6(fin)888 ipf_pr_icmp6(fin)
889 	fr_info_t *fin;
890 {
891 	int minicmpsz = sizeof(struct icmp6_hdr);
892 	struct icmp6_hdr *icmp6;
893 
894 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
895 		ipf_main_softc_t *softc = fin->fin_main_soft;
896 
897 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
898 		return;
899 	}
900 
901 	if (fin->fin_dlen > 1) {
902 		ip6_t *ip6;
903 
904 		icmp6 = fin->fin_dp;
905 
906 		fin->fin_data[0] = *(u_short *)icmp6;
907 
908 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
909 			fin->fin_flx |= FI_ICMPQUERY;
910 
911 		switch (icmp6->icmp6_type)
912 		{
913 		case ICMP6_ECHO_REPLY :
914 		case ICMP6_ECHO_REQUEST :
915 			if (fin->fin_dlen >= 6)
916 				fin->fin_data[1] = icmp6->icmp6_id;
917 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
918 			break;
919 
920 		case ICMP6_DST_UNREACH :
921 		case ICMP6_PACKET_TOO_BIG :
922 		case ICMP6_TIME_EXCEEDED :
923 		case ICMP6_PARAM_PROB :
924 			fin->fin_flx |= FI_ICMPERR;
925 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
926 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
927 				break;
928 
929 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
930 				if (ipf_coalesce(fin) != 1)
931 					return;
932 			}
933 
934 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
935 				return;
936 
937 			/*
938 			 * If the destination of this packet doesn't match the
939 			 * source of the original packet then this packet is
940 			 * not correct.
941 			 */
942 			icmp6 = fin->fin_dp;
943 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
944 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
945 				    (i6addr_t *)&ip6->ip6_src)) {
946 				fin->fin_flx |= FI_BAD;
947 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
948 			}
949 			break;
950 		default :
951 			break;
952 		}
953 	}
954 
955 	ipf_pr_short6(fin, minicmpsz);
956 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
957 		u_char p = fin->fin_p;
958 
959 		fin->fin_p = IPPROTO_ICMPV6;
960 		ipf_checkv6sum(fin);
961 		fin->fin_p = p;
962 	}
963 }
964 
965 
966 /* ------------------------------------------------------------------------ */
967 /* Function:    ipf_pr_udp6                                                 */
968 /* Returns:     void                                                        */
969 /* Parameters:  fin(I) - pointer to packet information                      */
970 /*                                                                          */
971 /* IPv6 Only                                                                */
972 /* Analyse the packet for IPv6/UDP properties.                              */
973 /* Is not expected to be called for fragmented packets.                     */
974 /* ------------------------------------------------------------------------ */
975 static INLINE void
ipf_pr_udp6(fin)976 ipf_pr_udp6(fin)
977 	fr_info_t *fin;
978 {
979 
980 	if (ipf_pr_udpcommon(fin) == 0) {
981 		u_char p = fin->fin_p;
982 
983 		fin->fin_p = IPPROTO_UDP;
984 		ipf_checkv6sum(fin);
985 		fin->fin_p = p;
986 	}
987 }
988 
989 
990 /* ------------------------------------------------------------------------ */
991 /* Function:    ipf_pr_tcp6                                                 */
992 /* Returns:     void                                                        */
993 /* Parameters:  fin(I) - pointer to packet information                      */
994 /*                                                                          */
995 /* IPv6 Only                                                                */
996 /* Analyse the packet for IPv6/TCP properties.                              */
997 /* Is not expected to be called for fragmented packets.                     */
998 /* ------------------------------------------------------------------------ */
999 static INLINE void
ipf_pr_tcp6(fin)1000 ipf_pr_tcp6(fin)
1001 	fr_info_t *fin;
1002 {
1003 
1004 	if (ipf_pr_tcpcommon(fin) == 0) {
1005 		u_char p = fin->fin_p;
1006 
1007 		fin->fin_p = IPPROTO_TCP;
1008 		ipf_checkv6sum(fin);
1009 		fin->fin_p = p;
1010 	}
1011 }
1012 
1013 
1014 /* ------------------------------------------------------------------------ */
1015 /* Function:    ipf_pr_esp6                                                 */
1016 /* Returns:     void                                                        */
1017 /* Parameters:  fin(I) - pointer to packet information                      */
1018 /*                                                                          */
1019 /* IPv6 Only                                                                */
1020 /* Analyse the packet for ESP properties.                                   */
1021 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1022 /* even though the newer ESP packets must also have a sequence number that  */
1023 /* is 32bits as well, it is not possible(?) to determine the version from a */
1024 /* simple packet header.                                                    */
1025 /* ------------------------------------------------------------------------ */
1026 static INLINE void
ipf_pr_esp6(fin)1027 ipf_pr_esp6(fin)
1028 	fr_info_t *fin;
1029 {
1030 
1031 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1032 		ipf_main_softc_t *softc = fin->fin_main_soft;
1033 
1034 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1035 		return;
1036 	}
1037 }
1038 
1039 
1040 /* ------------------------------------------------------------------------ */
1041 /* Function:    ipf_pr_ah6                                                  */
1042 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1043 /* Parameters:  fin(I) - pointer to packet information                      */
1044 /*                                                                          */
1045 /* IPv6 Only                                                                */
1046 /* Analyse the packet for AH properties.                                    */
1047 /* The minimum length is taken to be the combination of all fields in the   */
1048 /* header being present and no authentication data (null algorithm used.)   */
1049 /* ------------------------------------------------------------------------ */
1050 static INLINE int
ipf_pr_ah6(fin)1051 ipf_pr_ah6(fin)
1052 	fr_info_t *fin;
1053 {
1054 	authhdr_t *ah;
1055 
1056 	fin->fin_flx |= FI_AH;
1057 
1058 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1059 	if (ah == NULL) {
1060 		ipf_main_softc_t *softc = fin->fin_main_soft;
1061 
1062 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1063 		return IPPROTO_NONE;
1064 	}
1065 
1066 	ipf_pr_short6(fin, sizeof(*ah));
1067 
1068 	/*
1069 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1070 	 * enough data to satisfy ah_next (the very first one.)
1071 	 */
1072 	return ah->ah_next;
1073 }
1074 
1075 
1076 /* ------------------------------------------------------------------------ */
1077 /* Function:    ipf_pr_gre6                                                 */
1078 /* Returns:     void                                                        */
1079 /* Parameters:  fin(I) - pointer to packet information                      */
1080 /*                                                                          */
1081 /* Analyse the packet for GRE properties.                                   */
1082 /* ------------------------------------------------------------------------ */
1083 static INLINE void
ipf_pr_gre6(fin)1084 ipf_pr_gre6(fin)
1085 	fr_info_t *fin;
1086 {
1087 	grehdr_t *gre;
1088 
1089 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1090 		ipf_main_softc_t *softc = fin->fin_main_soft;
1091 
1092 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1093 		return;
1094 	}
1095 
1096 	gre = fin->fin_dp;
1097 	if (GRE_REV(gre->gr_flags) == 1)
1098 		fin->fin_data[0] = gre->gr_call;
1099 }
1100 #endif	/* USE_INET6 */
1101 
1102 
1103 /* ------------------------------------------------------------------------ */
1104 /* Function:    ipf_pr_pullup                                               */
1105 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1106 /* Parameters:  fin(I)  - pointer to packet information                     */
1107 /*              plen(I) - length (excluding L3 header) to pullup            */
1108 /*                                                                          */
1109 /* Short inline function to cut down on code duplication to perform a call  */
1110 /* to ipf_pullup to ensure there is the required amount of data,            */
1111 /* consecutively in the packet buffer.                                      */
1112 /*                                                                          */
1113 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1114 /* points to the first byte after the complete layer 3 header, which will   */
1115 /* include all of the known extension headers for IPv6 or options for IPv4. */
1116 /*                                                                          */
1117 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1118 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1119 /* - fin_ip) to what is passed through.                                     */
1120 /* ------------------------------------------------------------------------ */
1121 int
ipf_pr_pullup(fin,plen)1122 ipf_pr_pullup(fin, plen)
1123 	fr_info_t *fin;
1124 	int plen;
1125 {
1126 	ipf_main_softc_t *softc = fin->fin_main_soft;
1127 
1128 	if (fin->fin_m != NULL) {
1129 		if (fin->fin_dp != NULL)
1130 			plen += (char *)fin->fin_dp -
1131 				((char *)fin->fin_ip + fin->fin_hlen);
1132 		plen += fin->fin_hlen;
1133 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1134 #if defined(_KERNEL)
1135 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1136 				DT(ipf_pullup_fail);
1137 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1138 				return -1;
1139 			}
1140 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1141 #else
1142 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1143 			/*
1144 			 * Fake ipf_pullup failing
1145 			 */
1146 			fin->fin_reason = FRB_PULLUP;
1147 			*fin->fin_mp = NULL;
1148 			fin->fin_m = NULL;
1149 			fin->fin_ip = NULL;
1150 			return -1;
1151 #endif
1152 		}
1153 	}
1154 	return 0;
1155 }
1156 
1157 
1158 /* ------------------------------------------------------------------------ */
1159 /* Function:    ipf_pr_short                                                */
1160 /* Returns:     void                                                        */
1161 /* Parameters:  fin(I)  - pointer to packet information                     */
1162 /*              xmin(I) - minimum header size                               */
1163 /*                                                                          */
1164 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1165 /* applying here is that the packet must not be fragmented within the layer */
1166 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1167 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1168 /* entire layer 4 header must be present (min).                             */
1169 /* ------------------------------------------------------------------------ */
1170 static INLINE void
ipf_pr_short(fin,xmin)1171 ipf_pr_short(fin, xmin)
1172 	fr_info_t *fin;
1173 	int xmin;
1174 {
1175 
1176 	if (fin->fin_off == 0) {
1177 		if (fin->fin_dlen < xmin)
1178 			fin->fin_flx |= FI_SHORT;
1179 	} else if (fin->fin_off < xmin) {
1180 		fin->fin_flx |= FI_SHORT;
1181 	}
1182 }
1183 
1184 
1185 /* ------------------------------------------------------------------------ */
1186 /* Function:    ipf_pr_icmp                                                 */
1187 /* Returns:     void                                                        */
1188 /* Parameters:  fin(I) - pointer to packet information                      */
1189 /*                                                                          */
1190 /* IPv4 Only                                                                */
1191 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1192 /* except extrememly bad packets, both type and code will be present.       */
1193 /* The expected minimum size of an ICMP packet is very much dependent on    */
1194 /* the type of it.                                                          */
1195 /*                                                                          */
1196 /* XXX - other ICMP sanity checks?                                          */
1197 /* ------------------------------------------------------------------------ */
1198 static INLINE void
ipf_pr_icmp(fin)1199 ipf_pr_icmp(fin)
1200 	fr_info_t *fin;
1201 {
1202 	ipf_main_softc_t *softc = fin->fin_main_soft;
1203 	int minicmpsz = sizeof(struct icmp);
1204 	icmphdr_t *icmp;
1205 	ip_t *oip;
1206 
1207 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1208 
1209 	if (fin->fin_off != 0) {
1210 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1211 		return;
1212 	}
1213 
1214 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1215 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1216 		return;
1217 	}
1218 
1219 	icmp = fin->fin_dp;
1220 
1221 	fin->fin_data[0] = *(u_short *)icmp;
1222 	fin->fin_data[1] = icmp->icmp_id;
1223 
1224 	switch (icmp->icmp_type)
1225 	{
1226 	case ICMP_ECHOREPLY :
1227 	case ICMP_ECHO :
1228 	/* Router discovery messaes - RFC 1256 */
1229 	case ICMP_ROUTERADVERT :
1230 	case ICMP_ROUTERSOLICIT :
1231 		fin->fin_flx |= FI_ICMPQUERY;
1232 		minicmpsz = ICMP_MINLEN;
1233 		break;
1234 	/*
1235 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1236 	 * 3 * timestamp(3 * 4)
1237 	 */
1238 	case ICMP_TSTAMP :
1239 	case ICMP_TSTAMPREPLY :
1240 		fin->fin_flx |= FI_ICMPQUERY;
1241 		minicmpsz = 20;
1242 		break;
1243 	/*
1244 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1245 	 * mask(4)
1246 	 */
1247 	case ICMP_IREQ :
1248 	case ICMP_IREQREPLY :
1249 	case ICMP_MASKREQ :
1250 	case ICMP_MASKREPLY :
1251 		fin->fin_flx |= FI_ICMPQUERY;
1252 		minicmpsz = 12;
1253 		break;
1254 	/*
1255 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1256 	 */
1257 	case ICMP_UNREACH :
1258 #ifdef icmp_nextmtu
1259 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1260 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1261 				fin->fin_flx |= FI_BAD;
1262 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1263 			}
1264 		}
1265 #endif
1266 		/* FALLTHROUGH */
1267 	case ICMP_SOURCEQUENCH :
1268 	case ICMP_REDIRECT :
1269 	case ICMP_TIMXCEED :
1270 	case ICMP_PARAMPROB :
1271 		fin->fin_flx |= FI_ICMPERR;
1272 		if (ipf_coalesce(fin) != 1) {
1273 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1274 			return;
1275 		}
1276 
1277 		/*
1278 		 * ICMP error packets should not be generated for IP
1279 		 * packets that are a fragment that isn't the first
1280 		 * fragment.
1281 		 */
1282 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1283 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1284 			fin->fin_flx |= FI_BAD;
1285 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1286 		}
1287 
1288 		/*
1289 		 * If the destination of this packet doesn't match the
1290 		 * source of the original packet then this packet is
1291 		 * not correct.
1292 		 */
1293 		if (oip->ip_src.s_addr != fin->fin_daddr) {
1294 			fin->fin_flx |= FI_BAD;
1295 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1296 		}
1297 		break;
1298 	default :
1299 		break;
1300 	}
1301 
1302 	ipf_pr_short(fin, minicmpsz);
1303 
1304 	ipf_checkv4sum(fin);
1305 }
1306 
1307 
1308 /* ------------------------------------------------------------------------ */
1309 /* Function:    ipf_pr_tcpcommon                                            */
1310 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1311 /* Parameters:  fin(I) - pointer to packet information                      */
1312 /*                                                                          */
1313 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1314 /* and make some checks with how they interact with other fields.           */
1315 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1316 /* valid and mark the packet as bad if not.                                 */
1317 /* ------------------------------------------------------------------------ */
1318 static INLINE int
ipf_pr_tcpcommon(fin)1319 ipf_pr_tcpcommon(fin)
1320 	fr_info_t *fin;
1321 {
1322 	ipf_main_softc_t *softc = fin->fin_main_soft;
1323 	int flags, tlen;
1324 	tcphdr_t *tcp;
1325 
1326 	fin->fin_flx |= FI_TCPUDP;
1327 	if (fin->fin_off != 0) {
1328 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1329 		return 0;
1330 	}
1331 
1332 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1333 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1334 		return -1;
1335 	}
1336 
1337 	tcp = fin->fin_dp;
1338 	if (fin->fin_dlen > 3) {
1339 		fin->fin_sport = ntohs(tcp->th_sport);
1340 		fin->fin_dport = ntohs(tcp->th_dport);
1341 	}
1342 
1343 	if ((fin->fin_flx & FI_SHORT) != 0) {
1344 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1345 		return 1;
1346 	}
1347 
1348 	/*
1349 	 * Use of the TCP data offset *must* result in a value that is at
1350 	 * least the same size as the TCP header.
1351 	 */
1352 	tlen = TCP_OFF(tcp) << 2;
1353 	if (tlen < sizeof(tcphdr_t)) {
1354 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1355 		fin->fin_flx |= FI_BAD;
1356 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1357 		return 1;
1358 	}
1359 
1360 	flags = tcp->th_flags;
1361 	fin->fin_tcpf = tcp->th_flags;
1362 
1363 	/*
1364 	 * If the urgent flag is set, then the urgent pointer must
1365 	 * also be set and vice versa.  Good TCP packets do not have
1366 	 * just one of these set.
1367 	 */
1368 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1369 		fin->fin_flx |= FI_BAD;
1370 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1371 #if 0
1372 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1373 		/*
1374 		 * Ignore this case (#if 0) as it shows up in "real"
1375 		 * traffic with bogus values in the urgent pointer field.
1376 		 */
1377 		fin->fin_flx |= FI_BAD;
1378 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1379 #endif
1380 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1381 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1382 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1383 		fin->fin_flx |= FI_BAD;
1384 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1385 #if 1
1386 	} else if (((flags & TH_SYN) != 0) &&
1387 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1388 		/*
1389 		 * SYN with URG and PUSH set is not for normal TCP but it is
1390 		 * possible(?) with T/TCP...but who uses T/TCP?
1391 		 */
1392 		fin->fin_flx |= FI_BAD;
1393 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1394 #endif
1395 	} else if (!(flags & TH_ACK)) {
1396 		/*
1397 		 * If the ack bit isn't set, then either the SYN or
1398 		 * RST bit must be set.  If the SYN bit is set, then
1399 		 * we expect the ACK field to be 0.  If the ACK is
1400 		 * not set and if URG, PSH or FIN are set, consdier
1401 		 * that to indicate a bad TCP packet.
1402 		 */
1403 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1404 			/*
1405 			 * Cisco PIX sets the ACK field to a random value.
1406 			 * In light of this, do not set FI_BAD until a patch
1407 			 * is available from Cisco to ensure that
1408 			 * interoperability between existing systems is
1409 			 * achieved.
1410 			 */
1411 			/*fin->fin_flx |= FI_BAD*/;
1412 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1413 		} else if (!(flags & (TH_RST|TH_SYN))) {
1414 			fin->fin_flx |= FI_BAD;
1415 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1416 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1417 			fin->fin_flx |= FI_BAD;
1418 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1419 		}
1420 	}
1421 	if (fin->fin_flx & FI_BAD) {
1422 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1423 		return 1;
1424 	}
1425 
1426 	/*
1427 	 * At this point, it's not exactly clear what is to be gained by
1428 	 * marking up which TCP options are and are not present.  The one we
1429 	 * are most interested in is the TCP window scale.  This is only in
1430 	 * a SYN packet [RFC1323] so we don't need this here...?
1431 	 * Now if we were to analyse the header for passive fingerprinting,
1432 	 * then that might add some weight to adding this...
1433 	 */
1434 	if (tlen == sizeof(tcphdr_t)) {
1435 		return 0;
1436 	}
1437 
1438 	if (ipf_pr_pullup(fin, tlen) == -1) {
1439 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1440 		return -1;
1441 	}
1442 
1443 #if 0
1444 	tcp = fin->fin_dp;
1445 	ip = fin->fin_ip;
1446 	s = (u_char *)(tcp + 1);
1447 	off = IP_HL(ip) << 2;
1448 # ifdef _KERNEL
1449 	if (fin->fin_mp != NULL) {
1450 		mb_t *m = *fin->fin_mp;
1451 
1452 		if (off + tlen > M_LEN(m))
1453 			return;
1454 	}
1455 # endif
1456 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1457 		opt = *s;
1458 		if (opt == '\0')
1459 			break;
1460 		else if (opt == TCPOPT_NOP)
1461 			ol = 1;
1462 		else {
1463 			if (tlen < 2)
1464 				break;
1465 			ol = (int)*(s + 1);
1466 			if (ol < 2 || ol > tlen)
1467 				break;
1468 		}
1469 
1470 		for (i = 9, mv = 4; mv >= 0; ) {
1471 			op = ipopts + i;
1472 			if (opt == (u_char)op->ol_val) {
1473 				optmsk |= op->ol_bit;
1474 				break;
1475 			}
1476 		}
1477 		tlen -= ol;
1478 		s += ol;
1479 	}
1480 #endif /* 0 */
1481 
1482 	return 0;
1483 }
1484 
1485 
1486 
1487 /* ------------------------------------------------------------------------ */
1488 /* Function:    ipf_pr_udpcommon                                            */
1489 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1490 /* Parameters:  fin(I) - pointer to packet information                      */
1491 /*                                                                          */
1492 /* Extract the UDP source and destination ports, if present.  If compiled   */
1493 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1494 /* ------------------------------------------------------------------------ */
1495 static INLINE int
ipf_pr_udpcommon(fin)1496 ipf_pr_udpcommon(fin)
1497 	fr_info_t *fin;
1498 {
1499 	udphdr_t *udp;
1500 
1501 	fin->fin_flx |= FI_TCPUDP;
1502 
1503 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1504 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1505 			ipf_main_softc_t *softc = fin->fin_main_soft;
1506 
1507 			fin->fin_flx |= FI_SHORT;
1508 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1509 			return 1;
1510 		}
1511 
1512 		udp = fin->fin_dp;
1513 
1514 		fin->fin_sport = ntohs(udp->uh_sport);
1515 		fin->fin_dport = ntohs(udp->uh_dport);
1516 	}
1517 
1518 	return 0;
1519 }
1520 
1521 
1522 /* ------------------------------------------------------------------------ */
1523 /* Function:    ipf_pr_tcp                                                  */
1524 /* Returns:     void                                                        */
1525 /* Parameters:  fin(I) - pointer to packet information                      */
1526 /*                                                                          */
1527 /* IPv4 Only                                                                */
1528 /* Analyse the packet for IPv4/TCP properties.                              */
1529 /* ------------------------------------------------------------------------ */
1530 static INLINE void
ipf_pr_tcp(fin)1531 ipf_pr_tcp(fin)
1532 	fr_info_t *fin;
1533 {
1534 
1535 	ipf_pr_short(fin, sizeof(tcphdr_t));
1536 
1537 	if (ipf_pr_tcpcommon(fin) == 0)
1538 		ipf_checkv4sum(fin);
1539 }
1540 
1541 
1542 /* ------------------------------------------------------------------------ */
1543 /* Function:    ipf_pr_udp                                                  */
1544 /* Returns:     void                                                        */
1545 /* Parameters:  fin(I) - pointer to packet information                      */
1546 /*                                                                          */
1547 /* IPv4 Only                                                                */
1548 /* Analyse the packet for IPv4/UDP properties.                              */
1549 /* ------------------------------------------------------------------------ */
1550 static INLINE void
ipf_pr_udp(fin)1551 ipf_pr_udp(fin)
1552 	fr_info_t *fin;
1553 {
1554 
1555 	ipf_pr_short(fin, sizeof(udphdr_t));
1556 
1557 	if (ipf_pr_udpcommon(fin) == 0)
1558 		ipf_checkv4sum(fin);
1559 }
1560 
1561 
1562 /* ------------------------------------------------------------------------ */
1563 /* Function:    ipf_pr_esp                                                  */
1564 /* Returns:     void                                                        */
1565 /* Parameters:  fin(I) - pointer to packet information                      */
1566 /*                                                                          */
1567 /* Analyse the packet for ESP properties.                                   */
1568 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1569 /* even though the newer ESP packets must also have a sequence number that  */
1570 /* is 32bits as well, it is not possible(?) to determine the version from a */
1571 /* simple packet header.                                                    */
1572 /* ------------------------------------------------------------------------ */
1573 static INLINE void
ipf_pr_esp(fin)1574 ipf_pr_esp(fin)
1575 	fr_info_t *fin;
1576 {
1577 
1578 	if (fin->fin_off == 0) {
1579 		ipf_pr_short(fin, 8);
1580 		if (ipf_pr_pullup(fin, 8) == -1) {
1581 			ipf_main_softc_t *softc = fin->fin_main_soft;
1582 
1583 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1584 		}
1585 	}
1586 }
1587 
1588 
1589 /* ------------------------------------------------------------------------ */
1590 /* Function:    ipf_pr_ah                                                   */
1591 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1592 /* Parameters:  fin(I) - pointer to packet information                      */
1593 /*                                                                          */
1594 /* Analyse the packet for AH properties.                                    */
1595 /* The minimum length is taken to be the combination of all fields in the   */
1596 /* header being present and no authentication data (null algorithm used.)   */
1597 /* ------------------------------------------------------------------------ */
1598 static INLINE int
ipf_pr_ah(fin)1599 ipf_pr_ah(fin)
1600 	fr_info_t *fin;
1601 {
1602 	ipf_main_softc_t *softc = fin->fin_main_soft;
1603 	authhdr_t *ah;
1604 	int len;
1605 
1606 	fin->fin_flx |= FI_AH;
1607 	ipf_pr_short(fin, sizeof(*ah));
1608 
1609 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1610 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1611 		return IPPROTO_NONE;
1612 	}
1613 
1614 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1615 		DT(fr_v4_ah_pullup_1);
1616 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1617 		return IPPROTO_NONE;
1618 	}
1619 
1620 	ah = (authhdr_t *)fin->fin_dp;
1621 
1622 	len = (ah->ah_plen + 2) << 2;
1623 	ipf_pr_short(fin, len);
1624 	if (ipf_pr_pullup(fin, len) == -1) {
1625 		DT(fr_v4_ah_pullup_2);
1626 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1627 		return IPPROTO_NONE;
1628 	}
1629 
1630 	/*
1631 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1632 	 * header.
1633 	 */
1634 	fin->fin_dp = (char *)fin->fin_dp + len;
1635 	fin->fin_dlen -= len;
1636 	return ah->ah_next;
1637 }
1638 
1639 
1640 /* ------------------------------------------------------------------------ */
1641 /* Function:    ipf_pr_gre                                                  */
1642 /* Returns:     void                                                        */
1643 /* Parameters:  fin(I) - pointer to packet information                      */
1644 /*                                                                          */
1645 /* Analyse the packet for GRE properties.                                   */
1646 /* ------------------------------------------------------------------------ */
1647 static INLINE void
ipf_pr_gre(fin)1648 ipf_pr_gre(fin)
1649 	fr_info_t *fin;
1650 {
1651 	ipf_main_softc_t *softc = fin->fin_main_soft;
1652 	grehdr_t *gre;
1653 
1654 	ipf_pr_short(fin, sizeof(grehdr_t));
1655 
1656 	if (fin->fin_off != 0) {
1657 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1658 		return;
1659 	}
1660 
1661 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1662 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1663 		return;
1664 	}
1665 
1666 	gre = fin->fin_dp;
1667 	if (GRE_REV(gre->gr_flags) == 1)
1668 		fin->fin_data[0] = gre->gr_call;
1669 }
1670 
1671 
1672 /* ------------------------------------------------------------------------ */
1673 /* Function:    ipf_pr_ipv4hdr                                              */
1674 /* Returns:     void                                                        */
1675 /* Parameters:  fin(I) - pointer to packet information                      */
1676 /*                                                                          */
1677 /* IPv4 Only                                                                */
1678 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1679 /* Check all options present and flag their presence if any exist.          */
1680 /* ------------------------------------------------------------------------ */
1681 static INLINE void
ipf_pr_ipv4hdr(fin)1682 ipf_pr_ipv4hdr(fin)
1683 	fr_info_t *fin;
1684 {
1685 	u_short optmsk = 0, secmsk = 0, auth = 0;
1686 	int hlen, ol, mv, p, i;
1687 	const struct optlist *op;
1688 	u_char *s, opt;
1689 	u_short off;
1690 	fr_ip_t *fi;
1691 	ip_t *ip;
1692 
1693 	fi = &fin->fin_fi;
1694 	hlen = fin->fin_hlen;
1695 
1696 	ip = fin->fin_ip;
1697 	p = ip->ip_p;
1698 	fi->fi_p = p;
1699 	fin->fin_crc = p;
1700 	fi->fi_tos = ip->ip_tos;
1701 	fin->fin_id = ntohs(ip->ip_id);
1702 	off = ntohs(ip->ip_off);
1703 
1704 	/* Get both TTL and protocol */
1705 	fi->fi_p = ip->ip_p;
1706 	fi->fi_ttl = ip->ip_ttl;
1707 
1708 	/* Zero out bits not used in IPv6 address */
1709 	fi->fi_src.i6[1] = 0;
1710 	fi->fi_src.i6[2] = 0;
1711 	fi->fi_src.i6[3] = 0;
1712 	fi->fi_dst.i6[1] = 0;
1713 	fi->fi_dst.i6[2] = 0;
1714 	fi->fi_dst.i6[3] = 0;
1715 
1716 	fi->fi_saddr = ip->ip_src.s_addr;
1717 	fin->fin_crc += fi->fi_saddr;
1718 	fi->fi_daddr = ip->ip_dst.s_addr;
1719 	fin->fin_crc += fi->fi_daddr;
1720 	if (IN_CLASSD(ntohl(fi->fi_daddr)))
1721 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1722 
1723 	/*
1724 	 * set packet attribute flags based on the offset and
1725 	 * calculate the byte offset that it represents.
1726 	 */
1727 	off &= IP_MF|IP_OFFMASK;
1728 	if (off != 0) {
1729 		int morefrag = off & IP_MF;
1730 
1731 		fi->fi_flx |= FI_FRAG;
1732 		off &= IP_OFFMASK;
1733 		if (off == 1 && p == IPPROTO_TCP) {
1734 			fin->fin_flx |= FI_SHORT;	/* RFC 3128 */
1735 			DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1736 		}
1737 		if (off != 0) {
1738 			fin->fin_flx |= FI_FRAGBODY;
1739 			off <<= 3;
1740 			if ((off + fin->fin_dlen > 65535) ||
1741 			    (fin->fin_dlen == 0) ||
1742 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1743 				/*
1744 				 * The length of the packet, starting at its
1745 				 * offset cannot exceed 65535 (0xffff) as the
1746 				 * length of an IP packet is only 16 bits.
1747 				 *
1748 				 * Any fragment that isn't the last fragment
1749 				 * must have a length greater than 0 and it
1750 				 * must be an even multiple of 8.
1751 				 */
1752 				fi->fi_flx |= FI_BAD;
1753 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1754 			}
1755 		}
1756 	}
1757 	fin->fin_off = off;
1758 
1759 	/*
1760 	 * Call per-protocol setup and checking
1761 	 */
1762 	if (p == IPPROTO_AH) {
1763 		/*
1764 		 * Treat AH differently because we expect there to be another
1765 		 * layer 4 header after it.
1766 		 */
1767 		p = ipf_pr_ah(fin);
1768 	}
1769 
1770 	switch (p)
1771 	{
1772 	case IPPROTO_UDP :
1773 		ipf_pr_udp(fin);
1774 		break;
1775 	case IPPROTO_TCP :
1776 		ipf_pr_tcp(fin);
1777 		break;
1778 	case IPPROTO_ICMP :
1779 		ipf_pr_icmp(fin);
1780 		break;
1781 	case IPPROTO_ESP :
1782 		ipf_pr_esp(fin);
1783 		break;
1784 	case IPPROTO_GRE :
1785 		ipf_pr_gre(fin);
1786 		break;
1787 	}
1788 
1789 	ip = fin->fin_ip;
1790 	if (ip == NULL)
1791 		return;
1792 
1793 	/*
1794 	 * If it is a standard IP header (no options), set the flag fields
1795 	 * which relate to options to 0.
1796 	 */
1797 	if (hlen == sizeof(*ip)) {
1798 		fi->fi_optmsk = 0;
1799 		fi->fi_secmsk = 0;
1800 		fi->fi_auth = 0;
1801 		return;
1802 	}
1803 
1804 	/*
1805 	 * So the IP header has some IP options attached.  Walk the entire
1806 	 * list of options present with this packet and set flags to indicate
1807 	 * which ones are here and which ones are not.  For the somewhat out
1808 	 * of date and obscure security classification options, set a flag to
1809 	 * represent which classification is present.
1810 	 */
1811 	fi->fi_flx |= FI_OPTIONS;
1812 
1813 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1814 		opt = *s;
1815 		if (opt == '\0')
1816 			break;
1817 		else if (opt == IPOPT_NOP)
1818 			ol = 1;
1819 		else {
1820 			if (hlen < 2)
1821 				break;
1822 			ol = (int)*(s + 1);
1823 			if (ol < 2 || ol > hlen)
1824 				break;
1825 		}
1826 		for (i = 9, mv = 4; mv >= 0; ) {
1827 			op = ipopts + i;
1828 
1829 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1830 				u_32_t doi;
1831 
1832 				switch (opt)
1833 				{
1834 				case IPOPT_SECURITY :
1835 					if (optmsk & op->ol_bit) {
1836 						fin->fin_flx |= FI_BAD;
1837 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1838 					} else {
1839 						doi = ipf_checkripso(s);
1840 						secmsk = doi >> 16;
1841 						auth = doi & 0xffff;
1842 					}
1843 					break;
1844 
1845 				case IPOPT_CIPSO :
1846 
1847 					if (optmsk & op->ol_bit) {
1848 						fin->fin_flx |= FI_BAD;
1849 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1850 					} else {
1851 						doi = ipf_checkcipso(fin,
1852 								     s, ol);
1853 						secmsk = doi >> 16;
1854 						auth = doi & 0xffff;
1855 					}
1856 					break;
1857 				}
1858 				optmsk |= op->ol_bit;
1859 			}
1860 
1861 			if (opt < op->ol_val)
1862 				i -= mv;
1863 			else
1864 				i += mv;
1865 			mv--;
1866 		}
1867 		hlen -= ol;
1868 		s += ol;
1869 	}
1870 
1871 	/*
1872 	 *
1873 	 */
1874 	if (auth && !(auth & 0x0100))
1875 		auth &= 0xff00;
1876 	fi->fi_optmsk = optmsk;
1877 	fi->fi_secmsk = secmsk;
1878 	fi->fi_auth = auth;
1879 }
1880 
1881 
1882 /* ------------------------------------------------------------------------ */
1883 /* Function:    ipf_checkripso                                              */
1884 /* Returns:     void                                                        */
1885 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1886 /*                                                                          */
1887 /* ------------------------------------------------------------------------ */
1888 static u_32_t
ipf_checkripso(s)1889 ipf_checkripso(s)
1890 	u_char *s;
1891 {
1892 	const struct optlist *sp;
1893 	u_short secmsk = 0, auth = 0;
1894 	u_char sec;
1895 	int j, m;
1896 
1897 	sec = *(s + 2);	/* classification */
1898 	for (j = 3, m = 2; m >= 0; ) {
1899 		sp = secopt + j;
1900 		if (sec == sp->ol_val) {
1901 			secmsk |= sp->ol_bit;
1902 			auth = *(s + 3);
1903 			auth *= 256;
1904 			auth += *(s + 4);
1905 			break;
1906 		}
1907 		if (sec < sp->ol_val)
1908 			j -= m;
1909 		else
1910 			j += m;
1911 		m--;
1912 	}
1913 
1914 	return (secmsk << 16) | auth;
1915 }
1916 
1917 
1918 /* ------------------------------------------------------------------------ */
1919 /* Function:    ipf_checkcipso                                              */
1920 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1921 /* Parameters:  fin(IO) - pointer to packet information                     */
1922 /*              s(I)    - pointer to start of CIPSO option                  */
1923 /*              ol(I)   - length of CIPSO option field                      */
1924 /*                                                                          */
1925 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1926 /* header and returns that whilst also storing the highest sensitivity      */
1927 /* value found in the fr_info_t structure.                                  */
1928 /*                                                                          */
1929 /* No attempt is made to extract the category bitmaps as these are defined  */
1930 /* by the user (rather than the protocol) and can be rather numerous on the */
1931 /* end nodes.                                                               */
1932 /* ------------------------------------------------------------------------ */
1933 static u_32_t
ipf_checkcipso(fin,s,ol)1934 ipf_checkcipso(fin, s, ol)
1935 	fr_info_t *fin;
1936 	u_char *s;
1937 	int ol;
1938 {
1939 	ipf_main_softc_t *softc = fin->fin_main_soft;
1940 	fr_ip_t *fi;
1941 	u_32_t doi;
1942 	u_char *t, tag, tlen, sensitivity;
1943 	int len;
1944 
1945 	if (ol < 6 || ol > 40) {
1946 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1947 		fin->fin_flx |= FI_BAD;
1948 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1949 		return 0;
1950 	}
1951 
1952 	fi = &fin->fin_fi;
1953 	fi->fi_sensitivity = 0;
1954 	/*
1955 	 * The DOI field MUST be there.
1956 	 */
1957 	bcopy(s + 2, &doi, sizeof(doi));
1958 
1959 	t = (u_char *)s + 6;
1960 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1961 		tag = *t;
1962 		tlen = *(t + 1);
1963 		if (tlen > len || tlen < 4 || tlen > 34) {
1964 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1965 			fin->fin_flx |= FI_BAD;
1966 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1967 			return 0;
1968 		}
1969 
1970 		sensitivity = 0;
1971 		/*
1972 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1973 		 * draft (16 July 1992) that has expired.
1974 		 */
1975 		if (tag == 0) {
1976 			fin->fin_flx |= FI_BAD;
1977 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1978 			continue;
1979 		} else if (tag == 1) {
1980 			if (*(t + 2) != 0) {
1981 				fin->fin_flx |= FI_BAD;
1982 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1983 				continue;
1984 			}
1985 			sensitivity = *(t + 3);
1986 			/* Category bitmap for categories 0-239 */
1987 
1988 		} else if (tag == 4) {
1989 			if (*(t + 2) != 0) {
1990 				fin->fin_flx |= FI_BAD;
1991 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1992 				continue;
1993 			}
1994 			sensitivity = *(t + 3);
1995 			/* Enumerated categories, 16bits each, upto 15 */
1996 
1997 		} else if (tag == 5) {
1998 			if (*(t + 2) != 0) {
1999 				fin->fin_flx |= FI_BAD;
2000 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
2001 				continue;
2002 			}
2003 			sensitivity = *(t + 3);
2004 			/* Range of categories (2*16bits), up to 7 pairs */
2005 
2006 		} else if (tag > 127) {
2007 			/* Custom defined DOI */
2008 			;
2009 		} else {
2010 			fin->fin_flx |= FI_BAD;
2011 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2012 			continue;
2013 		}
2014 
2015 		if (sensitivity > fi->fi_sensitivity)
2016 			fi->fi_sensitivity = sensitivity;
2017 	}
2018 
2019 	return doi;
2020 }
2021 
2022 
2023 /* ------------------------------------------------------------------------ */
2024 /* Function:    ipf_makefrip                                                */
2025 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2026 /* Parameters:  hlen(I) - length of IP packet header                        */
2027 /*              ip(I)   - pointer to the IP header                          */
2028 /*              fin(IO) - pointer to packet information                     */
2029 /*                                                                          */
2030 /* Compact the IP header into a structure which contains just the info.     */
2031 /* which is useful for comparing IP headers with and store this information */
2032 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2033 /* this function will be called with either an IPv4 or IPv6 packet.         */
2034 /* ------------------------------------------------------------------------ */
2035 int
ipf_makefrip(hlen,ip,fin)2036 ipf_makefrip(hlen, ip, fin)
2037 	int hlen;
2038 	ip_t *ip;
2039 	fr_info_t *fin;
2040 {
2041 	ipf_main_softc_t *softc = fin->fin_main_soft;
2042 	int v;
2043 
2044 	fin->fin_depth = 0;
2045 	fin->fin_hlen = (u_short)hlen;
2046 	fin->fin_ip = ip;
2047 	fin->fin_rule = 0xffffffff;
2048 	fin->fin_group[0] = -1;
2049 	fin->fin_group[1] = '\0';
2050 	fin->fin_dp = (char *)ip + hlen;
2051 
2052 	v = fin->fin_v;
2053 	if (v == 4) {
2054 		fin->fin_plen = ntohs(ip->ip_len);
2055 		fin->fin_dlen = fin->fin_plen - hlen;
2056 		ipf_pr_ipv4hdr(fin);
2057 #ifdef	USE_INET6
2058 	} else if (v == 6) {
2059 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2060 		fin->fin_dlen = fin->fin_plen;
2061 		fin->fin_plen += hlen;
2062 
2063 		ipf_pr_ipv6hdr(fin);
2064 #endif
2065 	}
2066 	if (fin->fin_ip == NULL) {
2067 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2068 		return -1;
2069 	}
2070 	return 0;
2071 }
2072 
2073 
2074 /* ------------------------------------------------------------------------ */
2075 /* Function:    ipf_portcheck                                               */
2076 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2077 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2078 /*              pop(I) - port number to evaluate                            */
2079 /*                                                                          */
2080 /* Perform a comparison of a port number against some other(s), using a     */
2081 /* structure with compare information stored in it.                         */
2082 /* ------------------------------------------------------------------------ */
2083 static INLINE int
ipf_portcheck(frp,pop)2084 ipf_portcheck(frp, pop)
2085 	frpcmp_t *frp;
2086 	u_32_t pop;
2087 {
2088 	int err = 1;
2089 	u_32_t po;
2090 
2091 	po = frp->frp_port;
2092 
2093 	/*
2094 	 * Do opposite test to that required and continue if that succeeds.
2095 	 */
2096 	switch (frp->frp_cmp)
2097 	{
2098 	case FR_EQUAL :
2099 		if (pop != po) /* EQUAL */
2100 			err = 0;
2101 		break;
2102 	case FR_NEQUAL :
2103 		if (pop == po) /* NOTEQUAL */
2104 			err = 0;
2105 		break;
2106 	case FR_LESST :
2107 		if (pop >= po) /* LESSTHAN */
2108 			err = 0;
2109 		break;
2110 	case FR_GREATERT :
2111 		if (pop <= po) /* GREATERTHAN */
2112 			err = 0;
2113 		break;
2114 	case FR_LESSTE :
2115 		if (pop > po) /* LT or EQ */
2116 			err = 0;
2117 		break;
2118 	case FR_GREATERTE :
2119 		if (pop < po) /* GT or EQ */
2120 			err = 0;
2121 		break;
2122 	case FR_OUTRANGE :
2123 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2124 			err = 0;
2125 		break;
2126 	case FR_INRANGE :
2127 		if (pop <= po || pop >= frp->frp_top) /* In range */
2128 			err = 0;
2129 		break;
2130 	case FR_INCRANGE :
2131 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2132 			err = 0;
2133 		break;
2134 	default :
2135 		break;
2136 	}
2137 	return err;
2138 }
2139 
2140 
2141 /* ------------------------------------------------------------------------ */
2142 /* Function:    ipf_tcpudpchk                                               */
2143 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2144 /* Parameters:  fda(I) - pointer to packet information                      */
2145 /*              ft(I)  - pointer to structure with comparison data          */
2146 /*                                                                          */
2147 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2148 /* structure containing information that we want to match against.          */
2149 /* ------------------------------------------------------------------------ */
2150 int
ipf_tcpudpchk(fi,ft)2151 ipf_tcpudpchk(fi, ft)
2152 	fr_ip_t *fi;
2153 	frtuc_t *ft;
2154 {
2155 	int err = 1;
2156 
2157 	/*
2158 	 * Both ports should *always* be in the first fragment.
2159 	 * So far, I cannot find any cases where they can not be.
2160 	 *
2161 	 * compare destination ports
2162 	 */
2163 	if (ft->ftu_dcmp)
2164 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2165 
2166 	/*
2167 	 * compare source ports
2168 	 */
2169 	if (err && ft->ftu_scmp)
2170 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2171 
2172 	/*
2173 	 * If we don't have all the TCP/UDP header, then how can we
2174 	 * expect to do any sort of match on it ?  If we were looking for
2175 	 * TCP flags, then NO match.  If not, then match (which should
2176 	 * satisfy the "short" class too).
2177 	 */
2178 	if (err && (fi->fi_p == IPPROTO_TCP)) {
2179 		if (fi->fi_flx & FI_SHORT)
2180 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2181 		/*
2182 		 * Match the flags ?  If not, abort this match.
2183 		 */
2184 		if (ft->ftu_tcpfm &&
2185 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2186 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2187 				 ft->ftu_tcpfm, ft->ftu_tcpf));
2188 			err = 0;
2189 		}
2190 	}
2191 	return err;
2192 }
2193 
2194 
2195 /* ------------------------------------------------------------------------ */
2196 /* Function:    ipf_check_ipf                                               */
2197 /* Returns:     int - 0 == match, else no match                             */
2198 /* Parameters:  fin(I)     - pointer to packet information                  */
2199 /*              fr(I)      - pointer to filter rule                         */
2200 /*              portcmp(I) - flag indicating whether to attempt matching on */
2201 /*                           TCP/UDP port data.                             */
2202 /*                                                                          */
2203 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2204 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2205 /* this function.                                                           */
2206 /* ------------------------------------------------------------------------ */
2207 static INLINE int
ipf_check_ipf(fin,fr,portcmp)2208 ipf_check_ipf(fin, fr, portcmp)
2209 	fr_info_t *fin;
2210 	frentry_t *fr;
2211 	int portcmp;
2212 {
2213 	u_32_t	*ld, *lm, *lip;
2214 	fripf_t *fri;
2215 	fr_ip_t *fi;
2216 	int i;
2217 
2218 	fi = &fin->fin_fi;
2219 	fri = fr->fr_ipf;
2220 	lip = (u_32_t *)fi;
2221 	lm = (u_32_t *)&fri->fri_mip;
2222 	ld = (u_32_t *)&fri->fri_ip;
2223 
2224 	/*
2225 	 * first 32 bits to check coversion:
2226 	 * IP version, TOS, TTL, protocol
2227 	 */
2228 	i = ((*lip & *lm) != *ld);
2229 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2230 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2231 	if (i)
2232 		return 1;
2233 
2234 	/*
2235 	 * Next 32 bits is a constructed bitmask indicating which IP options
2236 	 * are present (if any) in this packet.
2237 	 */
2238 	lip++, lm++, ld++;
2239 	i = ((*lip & *lm) != *ld);
2240 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2241 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2242 	if (i != 0)
2243 		return 1;
2244 
2245 	lip++, lm++, ld++;
2246 	/*
2247 	 * Unrolled loops (4 each, for 32 bits) for address checks.
2248 	 */
2249 	/*
2250 	 * Check the source address.
2251 	 */
2252 	if (fr->fr_satype == FRI_LOOKUP) {
2253 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2254 				      fi->fi_v, lip, fin->fin_plen);
2255 		if (i == -1)
2256 			return 1;
2257 		lip += 3;
2258 		lm += 3;
2259 		ld += 3;
2260 	} else {
2261 		i = ((*lip & *lm) != *ld);
2262 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2263 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2264 		if (fi->fi_v == 6) {
2265 			lip++, lm++, ld++;
2266 			i |= ((*lip & *lm) != *ld);
2267 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2268 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2269 			lip++, lm++, ld++;
2270 			i |= ((*lip & *lm) != *ld);
2271 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2272 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2273 			lip++, lm++, ld++;
2274 			i |= ((*lip & *lm) != *ld);
2275 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2276 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2277 		} else {
2278 			lip += 3;
2279 			lm += 3;
2280 			ld += 3;
2281 		}
2282 	}
2283 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2284 	if (i != 0)
2285 		return 1;
2286 
2287 	/*
2288 	 * Check the destination address.
2289 	 */
2290 	lip++, lm++, ld++;
2291 	if (fr->fr_datype == FRI_LOOKUP) {
2292 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2293 				      fi->fi_v, lip, fin->fin_plen);
2294 		if (i == -1)
2295 			return 1;
2296 		lip += 3;
2297 		lm += 3;
2298 		ld += 3;
2299 	} else {
2300 		i = ((*lip & *lm) != *ld);
2301 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2302 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2303 		if (fi->fi_v == 6) {
2304 			lip++, lm++, ld++;
2305 			i |= ((*lip & *lm) != *ld);
2306 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2307 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2308 			lip++, lm++, ld++;
2309 			i |= ((*lip & *lm) != *ld);
2310 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2311 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2312 			lip++, lm++, ld++;
2313 			i |= ((*lip & *lm) != *ld);
2314 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2315 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2316 		} else {
2317 			lip += 3;
2318 			lm += 3;
2319 			ld += 3;
2320 		}
2321 	}
2322 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2323 	if (i != 0)
2324 		return 1;
2325 	/*
2326 	 * IP addresses matched.  The next 32bits contains:
2327 	 * mast of old IP header security & authentication bits.
2328 	 */
2329 	lip++, lm++, ld++;
2330 	i = (*ld - (*lip & *lm));
2331 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2332 
2333 	/*
2334 	 * Next we have 32 bits of packet flags.
2335 	 */
2336 	lip++, lm++, ld++;
2337 	i |= (*ld - (*lip & *lm));
2338 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2339 
2340 	if (i == 0) {
2341 		/*
2342 		 * If a fragment, then only the first has what we're
2343 		 * looking for here...
2344 		 */
2345 		if (portcmp) {
2346 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2347 				i = 1;
2348 		} else {
2349 			if (fr->fr_dcmp || fr->fr_scmp ||
2350 			    fr->fr_tcpf || fr->fr_tcpfm)
2351 				i = 1;
2352 			if (fr->fr_icmpm || fr->fr_icmp) {
2353 				if (((fi->fi_p != IPPROTO_ICMP) &&
2354 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2355 				    fin->fin_off || (fin->fin_dlen < 2))
2356 					i = 1;
2357 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2358 					 fr->fr_icmp) {
2359 					FR_DEBUG(("i. %#x & %#x != %#x\n",
2360 						 fin->fin_data[0],
2361 						 fr->fr_icmpm, fr->fr_icmp));
2362 					i = 1;
2363 				}
2364 			}
2365 		}
2366 	}
2367 	return i;
2368 }
2369 
2370 
2371 /* ------------------------------------------------------------------------ */
2372 /* Function:    ipf_scanlist                                                */
2373 /* Returns:     int - result flags of scanning filter list                  */
2374 /* Parameters:  fin(I) - pointer to packet information                      */
2375 /*              pass(I) - default result to return for filtering            */
2376 /*                                                                          */
2377 /* Check the input/output list of rules for a match to the current packet.  */
2378 /* If a match is found, the value of fr_flags from the rule becomes the     */
2379 /* return value and fin->fin_fr points to the matched rule.                 */
2380 /*                                                                          */
2381 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2382 /* When unwinding, it should finish up with fin_depth as 0.                 */
2383 /*                                                                          */
2384 /* Could be per interface, but this gets real nasty when you don't have,    */
2385 /* or can't easily change, the kernel source code to .                      */
2386 /* ------------------------------------------------------------------------ */
2387 int
ipf_scanlist(fin,pass)2388 ipf_scanlist(fin, pass)
2389 	fr_info_t *fin;
2390 	u_32_t pass;
2391 {
2392 	ipf_main_softc_t *softc = fin->fin_main_soft;
2393 	int rulen, portcmp, off, skip;
2394 	struct frentry *fr, *fnext;
2395 	u_32_t passt, passo;
2396 
2397 	/*
2398 	 * Do not allow nesting deeper than 16 levels.
2399 	 */
2400 	if (fin->fin_depth >= 16)
2401 		return pass;
2402 
2403 	fr = fin->fin_fr;
2404 
2405 	/*
2406 	 * If there are no rules in this list, return now.
2407 	 */
2408 	if (fr == NULL)
2409 		return pass;
2410 
2411 	skip = 0;
2412 	portcmp = 0;
2413 	fin->fin_depth++;
2414 	fin->fin_fr = NULL;
2415 	off = fin->fin_off;
2416 
2417 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2418 		portcmp = 1;
2419 
2420 	for (rulen = 0; fr; fr = fnext, rulen++) {
2421 		fnext = fr->fr_next;
2422 		if (skip != 0) {
2423 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2424 			skip--;
2425 			continue;
2426 		}
2427 
2428 		/*
2429 		 * In all checks below, a null (zero) value in the
2430 		 * filter struture is taken to mean a wildcard.
2431 		 *
2432 		 * check that we are working for the right interface
2433 		 */
2434 #ifdef	_KERNEL
2435 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2436 			continue;
2437 #else
2438 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2439 			printf("\n");
2440 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2441 				  FR_ISPASS(pass) ? 'p' :
2442 				  FR_ISACCOUNT(pass) ? 'A' :
2443 				  FR_ISAUTH(pass) ? 'a' :
2444 				  (pass & FR_NOMATCH) ? 'n' :'b'));
2445 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2446 			continue;
2447 		FR_VERBOSE((":i"));
2448 #endif
2449 
2450 		switch (fr->fr_type)
2451 		{
2452 		case FR_T_IPF :
2453 		case FR_T_IPF_BUILTIN :
2454 			if (ipf_check_ipf(fin, fr, portcmp))
2455 				continue;
2456 			break;
2457 #if defined(IPFILTER_BPF)
2458 		case FR_T_BPFOPC :
2459 		case FR_T_BPFOPC_BUILTIN :
2460 		    {
2461 			u_char *mc;
2462 			int wlen;
2463 
2464 			if (*fin->fin_mp == NULL)
2465 				continue;
2466 			if (fin->fin_family != fr->fr_family)
2467 				continue;
2468 			mc = (u_char *)fin->fin_m;
2469 			wlen = fin->fin_dlen + fin->fin_hlen;
2470 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2471 				continue;
2472 			break;
2473 		    }
2474 #endif
2475 		case FR_T_CALLFUNC_BUILTIN :
2476 		    {
2477 			frentry_t *f;
2478 
2479 			f = (*fr->fr_func)(fin, &pass);
2480 			if (f != NULL)
2481 				fr = f;
2482 			else
2483 				continue;
2484 			break;
2485 		    }
2486 
2487 		case FR_T_IPFEXPR :
2488 		case FR_T_IPFEXPR_BUILTIN :
2489 			if (fin->fin_family != fr->fr_family)
2490 				continue;
2491 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2492 				continue;
2493 			break;
2494 
2495 		default :
2496 			break;
2497 		}
2498 
2499 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2500 			if (fin->fin_nattag == NULL)
2501 				continue;
2502 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2503 				continue;
2504 		}
2505 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2506 
2507 		passt = fr->fr_flags;
2508 
2509 		/*
2510 		 * If the rule is a "call now" rule, then call the function
2511 		 * in the rule, if it exists and use the results from that.
2512 		 * If the function pointer is bad, just make like we ignore
2513 		 * it, except for increasing the hit counter.
2514 		 */
2515 		if ((passt & FR_CALLNOW) != 0) {
2516 			frentry_t *frs;
2517 
2518 			ATOMIC_INC64(fr->fr_hits);
2519 			if ((fr->fr_func == NULL) ||
2520 			    (fr->fr_func == (ipfunc_t)-1))
2521 				continue;
2522 
2523 			frs = fin->fin_fr;
2524 			fin->fin_fr = fr;
2525 			fr = (*fr->fr_func)(fin, &passt);
2526 			if (fr == NULL) {
2527 				fin->fin_fr = frs;
2528 				continue;
2529 			}
2530 			passt = fr->fr_flags;
2531 		}
2532 		fin->fin_fr = fr;
2533 
2534 #ifdef  IPFILTER_LOG
2535 		/*
2536 		 * Just log this packet...
2537 		 */
2538 		if ((passt & FR_LOGMASK) == FR_LOG) {
2539 			if (ipf_log_pkt(fin, passt) == -1) {
2540 				if (passt & FR_LOGORBLOCK) {
2541 					DT(frb_logfail);
2542 					passt &= ~FR_CMDMASK;
2543 					passt |= FR_BLOCK|FR_QUICK;
2544 					fin->fin_reason = FRB_LOGFAIL;
2545 				}
2546 			}
2547 		}
2548 #endif /* IPFILTER_LOG */
2549 
2550 		MUTEX_ENTER(&fr->fr_lock);
2551 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2552 		fr->fr_hits++;
2553 		MUTEX_EXIT(&fr->fr_lock);
2554 		fin->fin_rule = rulen;
2555 
2556 		passo = pass;
2557 		if (FR_ISSKIP(passt)) {
2558 			skip = fr->fr_arg;
2559 			continue;
2560 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2561 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2562 			pass = passt;
2563 		}
2564 
2565 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2566 			fin->fin_icode = fr->fr_icode;
2567 
2568 		if (fr->fr_group != -1) {
2569 			(void) strncpy(fin->fin_group,
2570 				       FR_NAME(fr, fr_group),
2571 				       strlen(FR_NAME(fr, fr_group)));
2572 		} else {
2573 			fin->fin_group[0] = '\0';
2574 		}
2575 
2576 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2577 
2578 		if (fr->fr_grphead != NULL) {
2579 			fin->fin_fr = fr->fr_grphead->fg_start;
2580 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2581 
2582 			if (FR_ISDECAPS(passt))
2583 				passt = ipf_decaps(fin, pass, fr->fr_icode);
2584 			else
2585 				passt = ipf_scanlist(fin, pass);
2586 
2587 			if (fin->fin_fr == NULL) {
2588 				fin->fin_rule = rulen;
2589 				if (fr->fr_group != -1)
2590 					(void) strncpy(fin->fin_group,
2591 						       fr->fr_names +
2592 						       fr->fr_group,
2593 						       strlen(fr->fr_names +
2594 							      fr->fr_group));
2595 				fin->fin_fr = fr;
2596 				passt = pass;
2597 			}
2598 			pass = passt;
2599 		}
2600 
2601 		if (pass & FR_QUICK) {
2602 			/*
2603 			 * Finally, if we've asked to track state for this
2604 			 * packet, set it up.  Add state for "quick" rules
2605 			 * here so that if the action fails we can consider
2606 			 * the rule to "not match" and keep on processing
2607 			 * filter rules.
2608 			 */
2609 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2610 			    !(fin->fin_flx & FI_STATE)) {
2611 				int out = fin->fin_out;
2612 
2613 				fin->fin_fr = fr;
2614 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2615 					LBUMPD(ipf_stats[out], fr_ads);
2616 				} else {
2617 					LBUMPD(ipf_stats[out], fr_bads);
2618 					pass = passo;
2619 					continue;
2620 				}
2621 			}
2622 			break;
2623 		}
2624 	}
2625 	fin->fin_depth--;
2626 	return pass;
2627 }
2628 
2629 
2630 /* ------------------------------------------------------------------------ */
2631 /* Function:    ipf_acctpkt                                                 */
2632 /* Returns:     frentry_t* - always returns NULL                            */
2633 /* Parameters:  fin(I) - pointer to packet information                      */
2634 /*              passp(IO) - pointer to current/new filter decision (unused) */
2635 /*                                                                          */
2636 /* Checks a packet against accounting rules, if there are any for the given */
2637 /* IP protocol version.                                                     */
2638 /*                                                                          */
2639 /* N.B.: this function returns NULL to match the prototype used by other    */
2640 /* functions called from the IPFilter "mainline" in ipf_check().            */
2641 /* ------------------------------------------------------------------------ */
2642 frentry_t *
ipf_acctpkt(fin,passp)2643 ipf_acctpkt(fin, passp)
2644 	fr_info_t *fin;
2645 	u_32_t *passp;
2646 {
2647 	ipf_main_softc_t *softc = fin->fin_main_soft;
2648 	char group[FR_GROUPLEN];
2649 	frentry_t *fr, *frsave;
2650 	u_32_t pass, rulen;
2651 
2652 	passp = passp;
2653 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2654 
2655 	if (fr != NULL) {
2656 		frsave = fin->fin_fr;
2657 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2658 		rulen = fin->fin_rule;
2659 		fin->fin_fr = fr;
2660 		pass = ipf_scanlist(fin, FR_NOMATCH);
2661 		if (FR_ISACCOUNT(pass)) {
2662 			LBUMPD(ipf_stats[0], fr_acct);
2663 		}
2664 		fin->fin_fr = frsave;
2665 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2666 		fin->fin_rule = rulen;
2667 	}
2668 	return NULL;
2669 }
2670 
2671 
2672 /* ------------------------------------------------------------------------ */
2673 /* Function:    ipf_firewall                                                */
2674 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2675 /*                           were found, returns NULL.                      */
2676 /* Parameters:  fin(I) - pointer to packet information                      */
2677 /*              passp(IO) - pointer to current/new filter decision (unused) */
2678 /*                                                                          */
2679 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2680 /* there are any matches.  The first check is to see if a match can be seen */
2681 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2682 /* matching rule is found, take any appropriate actions as defined by the   */
2683 /* rule - except logging.                                                   */
2684 /* ------------------------------------------------------------------------ */
2685 static frentry_t *
ipf_firewall(fin,passp)2686 ipf_firewall(fin, passp)
2687 	fr_info_t *fin;
2688 	u_32_t *passp;
2689 {
2690 	ipf_main_softc_t *softc = fin->fin_main_soft;
2691 	frentry_t *fr;
2692 	u_32_t pass;
2693 	int out;
2694 
2695 	out = fin->fin_out;
2696 	pass = *passp;
2697 
2698 	/*
2699 	 * This rule cache will only affect packets that are not being
2700 	 * statefully filtered.
2701 	 */
2702 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2703 	if (fin->fin_fr != NULL)
2704 		pass = ipf_scanlist(fin, softc->ipf_pass);
2705 
2706 	if ((pass & FR_NOMATCH)) {
2707 		LBUMPD(ipf_stats[out], fr_nom);
2708 	}
2709 	fr = fin->fin_fr;
2710 
2711 	/*
2712 	 * Apply packets per second rate-limiting to a rule as required.
2713 	 */
2714 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2715 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2716 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2717 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2718 		pass |= FR_BLOCK;
2719 		LBUMPD(ipf_stats[out], fr_ppshit);
2720 		fin->fin_reason = FRB_PPSRATE;
2721 	}
2722 
2723 	/*
2724 	 * If we fail to add a packet to the authorization queue, then we
2725 	 * drop the packet later.  However, if it was added then pretend
2726 	 * we've dropped it already.
2727 	 */
2728 	if (FR_ISAUTH(pass)) {
2729 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2730 			DT1(frb_authnew, fr_info_t *, fin);
2731 			fin->fin_m = *fin->fin_mp = NULL;
2732 			fin->fin_reason = FRB_AUTHNEW;
2733 			fin->fin_error = 0;
2734 		} else {
2735 			IPFERROR(1);
2736 			fin->fin_error = ENOSPC;
2737 		}
2738 	}
2739 
2740 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2741 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2742 		(void) (*fr->fr_func)(fin, &pass);
2743 
2744 	/*
2745 	 * If a rule is a pre-auth rule, check again in the list of rules
2746 	 * loaded for authenticated use.  It does not particulary matter
2747 	 * if this search fails because a "preauth" result, from a rule,
2748 	 * is treated as "not a pass", hence the packet is blocked.
2749 	 */
2750 	if (FR_ISPREAUTH(pass)) {
2751 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2752 	}
2753 
2754 	/*
2755 	 * If the rule has "keep frag" and the packet is actually a fragment,
2756 	 * then create a fragment state entry.
2757 	 */
2758 	if (pass & FR_KEEPFRAG) {
2759 		if (fin->fin_flx & FI_FRAG) {
2760 			if (ipf_frag_new(softc, fin, pass) == -1) {
2761 				LBUMP(ipf_stats[out].fr_bnfr);
2762 			} else {
2763 				LBUMP(ipf_stats[out].fr_nfr);
2764 			}
2765 		} else {
2766 			LBUMP(ipf_stats[out].fr_cfr);
2767 		}
2768 	}
2769 
2770 	fr = fin->fin_fr;
2771 	*passp = pass;
2772 
2773 	return fr;
2774 }
2775 
2776 
2777 /* ------------------------------------------------------------------------ */
2778 /* Function:    ipf_check                                                   */
2779 /* Returns:     int -  0 == packet allowed through,                         */
2780 /*              User space:                                                 */
2781 /*                    -1 == packet blocked                                  */
2782 /*                     1 == packet not matched                              */
2783 /*                    -2 == requires authentication                         */
2784 /*              Kernel:                                                     */
2785 /*                   > 0 == filter error # for packet                       */
2786 /* Parameters: ctx(I)  - pointer to the instance context                    */
2787 /*             ip(I)   - pointer to start of IPv4/6 packet                  */
2788 /*             hlen(I) - length of header                                   */
2789 /*             ifp(I)  - pointer to interface this packet is on             */
2790 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2791 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2792 /*                       IP packet.                                         */
2793 /* Solaris:                                                                 */
2794 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2795 /*                       interface & direction.                             */
2796 /*                                                                          */
2797 /* ipf_check() is the master function for all IPFilter packet processing.   */
2798 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2799 /* authorisation (or pre-authorisation), presence of related state info.,   */
2800 /* generating log entries, IP packet accounting, routing of packets as      */
2801 /* directed by firewall rules and of course whether or not to allow the     */
2802 /* packet to be further processed by the kernel.                            */
2803 /*                                                                          */
2804 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2805 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2806 /* by "mp" changed to a new buffer.                                         */
2807 /* ------------------------------------------------------------------------ */
2808 int
ipf_check(ctx,ip,hlen,ifp,out,qif,mp)2809 ipf_check(ctx, ip, hlen, ifp, out
2810 #if defined(_KERNEL) && defined(MENTAT)
2811 	, qif, mp)
2812 	void *qif;
2813 #else
2814 	, mp)
2815 #endif
2816 	mb_t **mp;
2817 	ip_t *ip;
2818 	int hlen;
2819 	struct ifnet *ifp;
2820 	int out;
2821 	void *ctx;
2822 {
2823 	/*
2824 	 * The above really sucks, but short of writing a diff
2825 	 */
2826 	ipf_main_softc_t *softc = ctx;
2827 	fr_info_t frinfo;
2828 	fr_info_t *fin = &frinfo;
2829 	u_32_t pass = softc->ipf_pass;
2830 	frentry_t *fr = NULL;
2831 	int v = IP_V(ip);
2832 	mb_t *mc = NULL;
2833 	mb_t *m;
2834 	/*
2835 	 * The first part of ipf_check() deals with making sure that what goes
2836 	 * into the filtering engine makes some sense.  Information about the
2837 	 * the packet is distilled, collected into a fr_info_t structure and
2838 	 * the an attempt to ensure the buffer the packet is in is big enough
2839 	 * to hold all the required packet headers.
2840 	 */
2841 #ifdef	_KERNEL
2842 # ifdef MENTAT
2843 	qpktinfo_t *qpi = qif;
2844 
2845 #  ifdef __sparc
2846 	if ((u_int)ip & 0x3)
2847 		return 2;
2848 #  endif
2849 # else
2850 	SPL_INT(s);
2851 # endif
2852 
2853 	if (softc->ipf_running <= 0) {
2854 		return 0;
2855 	}
2856 
2857 	bzero((char *)fin, sizeof(*fin));
2858 
2859 # ifdef MENTAT
2860 	if (qpi->qpi_flags & QF_BROADCAST)
2861 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2862 	if (qpi->qpi_flags & QF_MULTICAST)
2863 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2864 	m = qpi->qpi_m;
2865 	fin->fin_qfm = m;
2866 	fin->fin_qpi = qpi;
2867 # else /* MENTAT */
2868 
2869 	m = *mp;
2870 
2871 #  if defined(M_MCAST)
2872 	if ((m->m_flags & M_MCAST) != 0)
2873 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2874 #  endif
2875 #  if defined(M_MLOOP)
2876 	if ((m->m_flags & M_MLOOP) != 0)
2877 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2878 #  endif
2879 #  if defined(M_BCAST)
2880 	if ((m->m_flags & M_BCAST) != 0)
2881 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2882 #  endif
2883 #  ifdef M_CANFASTFWD
2884 	/*
2885 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2886 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2887 	 * XXX get a "can-fast-forward" filter rule.
2888 	 */
2889 	m->m_flags &= ~M_CANFASTFWD;
2890 #  endif /* M_CANFASTFWD */
2891 #  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2892 	/*
2893 	 * disable delayed checksums.
2894 	 */
2895 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2896 		in_delayed_cksum(m);
2897 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2898 	}
2899 #  endif /* CSUM_DELAY_DATA */
2900 # endif /* MENTAT */
2901 #else
2902 	bzero((char *)fin, sizeof(*fin));
2903 	m = *mp;
2904 # if defined(M_MCAST)
2905 	if ((m->m_flags & M_MCAST) != 0)
2906 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2907 # endif
2908 # if defined(M_MLOOP)
2909 	if ((m->m_flags & M_MLOOP) != 0)
2910 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2911 # endif
2912 # if defined(M_BCAST)
2913 	if ((m->m_flags & M_BCAST) != 0)
2914 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2915 # endif
2916 #endif /* _KERNEL */
2917 
2918 	fin->fin_v = v;
2919 	fin->fin_m = m;
2920 	fin->fin_ip = ip;
2921 	fin->fin_mp = mp;
2922 	fin->fin_out = out;
2923 	fin->fin_ifp = ifp;
2924 	fin->fin_error = ENETUNREACH;
2925 	fin->fin_hlen = (u_short)hlen;
2926 	fin->fin_dp = (char *)ip + hlen;
2927 	fin->fin_main_soft = softc;
2928 
2929 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2930 
2931 	SPL_NET(s);
2932 
2933 #ifdef	USE_INET6
2934 	if (v == 6) {
2935 		LBUMP(ipf_stats[out].fr_ipv6);
2936 		/*
2937 		 * Jumbo grams are quite likely too big for internal buffer
2938 		 * structures to handle comfortably, for now, so just drop
2939 		 * them.
2940 		 */
2941 		if (((ip6_t *)ip)->ip6_plen == 0) {
2942 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2943 			pass = FR_BLOCK|FR_NOMATCH;
2944 			fin->fin_reason = FRB_JUMBO;
2945 			goto finished;
2946 		}
2947 		fin->fin_family = AF_INET6;
2948 	} else
2949 #endif
2950 	{
2951 		fin->fin_family = AF_INET;
2952 	}
2953 
2954 	if (ipf_makefrip(hlen, ip, fin) == -1) {
2955 		DT1(frb_makefrip, fr_info_t *, fin);
2956 		pass = FR_BLOCK|FR_NOMATCH;
2957 		fin->fin_reason = FRB_MAKEFRIP;
2958 		goto finished;
2959 	}
2960 
2961 	/*
2962 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2963 	 * becomes NULL and so we have no packet to free.
2964 	 */
2965 	if (*fin->fin_mp == NULL)
2966 		goto finished;
2967 
2968 	if (!out) {
2969 		if (v == 4) {
2970 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2971 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2972 				fin->fin_flx |= FI_BADSRC;
2973 			}
2974 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2975 				LBUMPD(ipf_stats[0], fr_v4_badttl);
2976 				fin->fin_flx |= FI_LOWTTL;
2977 			}
2978 		}
2979 #ifdef USE_INET6
2980 		else  if (v == 6) {
2981 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2982 				LBUMPD(ipf_stats[0], fr_v6_badttl);
2983 				fin->fin_flx |= FI_LOWTTL;
2984 			}
2985 		}
2986 #endif
2987 	}
2988 
2989 	if (fin->fin_flx & FI_SHORT) {
2990 		LBUMPD(ipf_stats[out], fr_short);
2991 	}
2992 
2993 	READ_ENTER(&softc->ipf_mutex);
2994 
2995 	if (!out) {
2996 		switch (fin->fin_v)
2997 		{
2998 		case 4 :
2999 			if (ipf_nat_checkin(fin, &pass) == -1) {
3000 				goto filterdone;
3001 			}
3002 			break;
3003 #ifdef USE_INET6
3004 		case 6 :
3005 			if (ipf_nat6_checkin(fin, &pass) == -1) {
3006 				goto filterdone;
3007 			}
3008 			break;
3009 #endif
3010 		default :
3011 			break;
3012 		}
3013 	}
3014 	/*
3015 	 * Check auth now.
3016 	 * If a packet is found in the auth table, then skip checking
3017 	 * the access lists for permission but we do need to consider
3018 	 * the result as if it were from the ACL's.  In addition, being
3019 	 * found in the auth table means it has been seen before, so do
3020 	 * not pass it through accounting (again), lest it be counted twice.
3021 	 */
3022 	fr = ipf_auth_check(fin, &pass);
3023 	if (!out && (fr == NULL))
3024 		(void) ipf_acctpkt(fin, NULL);
3025 
3026 	if (fr == NULL) {
3027 		if ((fin->fin_flx & FI_FRAG) != 0)
3028 			fr = ipf_frag_known(fin, &pass);
3029 
3030 		if (fr == NULL)
3031 			fr = ipf_state_check(fin, &pass);
3032 	}
3033 
3034 	if ((pass & FR_NOMATCH) || (fr == NULL))
3035 		fr = ipf_firewall(fin, &pass);
3036 
3037 	/*
3038 	 * If we've asked to track state for this packet, set it up.
3039 	 * Here rather than ipf_firewall because ipf_checkauth may decide
3040 	 * to return a packet for "keep state"
3041 	 */
3042 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3043 	    !(fin->fin_flx & FI_STATE)) {
3044 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3045 			LBUMP(ipf_stats[out].fr_ads);
3046 		} else {
3047 			LBUMP(ipf_stats[out].fr_bads);
3048 			if (FR_ISPASS(pass)) {
3049 				DT(frb_stateadd);
3050 				pass &= ~FR_CMDMASK;
3051 				pass |= FR_BLOCK;
3052 				fin->fin_reason = FRB_STATEADD;
3053 			}
3054 		}
3055 	}
3056 
3057 	fin->fin_fr = fr;
3058 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3059 		fin->fin_dif = &fr->fr_dif;
3060 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3061 	}
3062 
3063 	/*
3064 	 * Only count/translate packets which will be passed on, out the
3065 	 * interface.
3066 	 */
3067 	if (out && FR_ISPASS(pass)) {
3068 		(void) ipf_acctpkt(fin, NULL);
3069 
3070 		switch (fin->fin_v)
3071 		{
3072 		case 4 :
3073 			if (ipf_nat_checkout(fin, &pass) == -1) {
3074 				;
3075 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3076 				if (ipf_updateipid(fin) == -1) {
3077 					DT(frb_updateipid);
3078 					LBUMP(ipf_stats[1].fr_ipud);
3079 					pass &= ~FR_CMDMASK;
3080 					pass |= FR_BLOCK;
3081 					fin->fin_reason = FRB_UPDATEIPID;
3082 				} else {
3083 					LBUMP(ipf_stats[0].fr_ipud);
3084 				}
3085 			}
3086 			break;
3087 #ifdef USE_INET6
3088 		case 6 :
3089 			(void) ipf_nat6_checkout(fin, &pass);
3090 			break;
3091 #endif
3092 		default :
3093 			break;
3094 		}
3095 	}
3096 
3097 filterdone:
3098 #ifdef	IPFILTER_LOG
3099 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3100 		(void) ipf_dolog(fin, &pass);
3101 	}
3102 #endif
3103 
3104 	/*
3105 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3106 	 * will work when called from inside of fr_fastroute.  Although
3107 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3108 	 * impact on code execution.
3109 	 */
3110 	fin->fin_flx &= ~FI_STATE;
3111 
3112 #if defined(FASTROUTE_RECURSION)
3113 	/*
3114 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3115 	 * a packet below can sometimes cause a recursive call into IPFilter.
3116 	 * On those platforms where that does happen, we need to hang onto
3117 	 * the filter rule just in case someone decides to remove or flush it
3118 	 * in the meantime.
3119 	 */
3120 	if (fr != NULL) {
3121 		MUTEX_ENTER(&fr->fr_lock);
3122 		fr->fr_ref++;
3123 		MUTEX_EXIT(&fr->fr_lock);
3124 	}
3125 
3126 	RWLOCK_EXIT(&softc->ipf_mutex);
3127 #endif
3128 
3129 	if ((pass & FR_RETMASK) != 0) {
3130 		/*
3131 		 * Should we return an ICMP packet to indicate error
3132 		 * status passing through the packet filter ?
3133 		 * WARNING: ICMP error packets AND TCP RST packets should
3134 		 * ONLY be sent in repsonse to incoming packets.  Sending
3135 		 * them in response to outbound packets can result in a
3136 		 * panic on some operating systems.
3137 		 */
3138 		if (!out) {
3139 			if (pass & FR_RETICMP) {
3140 				int dst;
3141 
3142 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3143 					dst = 1;
3144 				else
3145 					dst = 0;
3146 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3147 							 dst);
3148 				LBUMP(ipf_stats[0].fr_ret);
3149 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3150 				   !(fin->fin_flx & FI_SHORT)) {
3151 				if (((fin->fin_flx & FI_OOW) != 0) ||
3152 				    (ipf_send_reset(fin) == 0)) {
3153 					LBUMP(ipf_stats[1].fr_ret);
3154 				}
3155 			}
3156 
3157 			/*
3158 			 * When using return-* with auth rules, the auth code
3159 			 * takes over disposing of this packet.
3160 			 */
3161 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3162 				DT1(frb_authcapture, fr_info_t *, fin);
3163 				fin->fin_m = *fin->fin_mp = NULL;
3164 				fin->fin_reason = FRB_AUTHCAPTURE;
3165 				m = NULL;
3166 			}
3167 		} else {
3168 			if (pass & FR_RETRST) {
3169 				fin->fin_error = ECONNRESET;
3170 			}
3171 		}
3172 	}
3173 
3174 	/*
3175 	 * After the above so that ICMP unreachables and TCP RSTs get
3176 	 * created properly.
3177 	 */
3178 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3179 		ipf_nat_uncreate(fin);
3180 
3181 	/*
3182 	 * If we didn't drop off the bottom of the list of rules (and thus
3183 	 * the 'current' rule fr is not NULL), then we may have some extra
3184 	 * instructions about what to do with a packet.
3185 	 * Once we're finished return to our caller, freeing the packet if
3186 	 * we are dropping it.
3187 	 */
3188 	if (fr != NULL) {
3189 		frdest_t *fdp;
3190 
3191 		/*
3192 		 * Generate a duplicated packet first because ipf_fastroute
3193 		 * can lead to fin_m being free'd... not good.
3194 		 */
3195 		fdp = fin->fin_dif;
3196 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3197 		    (fdp->fd_ptr != (void *)-1)) {
3198 			mc = M_COPY(fin->fin_m);
3199 			if (mc != NULL)
3200 				ipf_fastroute(mc, &mc, fin, fdp);
3201 		}
3202 
3203 		fdp = fin->fin_tif;
3204 		if (!out && (pass & FR_FASTROUTE)) {
3205 			/*
3206 			 * For fastroute rule, no destination interface defined
3207 			 * so pass NULL as the frdest_t parameter
3208 			 */
3209 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3210 			m = *mp = NULL;
3211 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3212 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3213 			/* this is for to rules: */
3214 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3215 			m = *mp = NULL;
3216 		}
3217 
3218 #if defined(FASTROUTE_RECURSION)
3219 		(void) ipf_derefrule(softc, &fr);
3220 #endif
3221 	}
3222 #if !defined(FASTROUTE_RECURSION)
3223 	RWLOCK_EXIT(&softc->ipf_mutex);
3224 #endif
3225 
3226 finished:
3227 	if (!FR_ISPASS(pass)) {
3228 		LBUMP(ipf_stats[out].fr_block);
3229 		if (*mp != NULL) {
3230 #ifdef _KERNEL
3231 			FREE_MB_T(*mp);
3232 #endif
3233 			m = *mp = NULL;
3234 		}
3235 	} else {
3236 		LBUMP(ipf_stats[out].fr_pass);
3237 	}
3238 
3239 	SPL_X(s);
3240 
3241 #ifdef _KERNEL
3242 	if (FR_ISPASS(pass))
3243 		return 0;
3244 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3245 	return fin->fin_error;
3246 #else /* _KERNEL */
3247 	if (*mp != NULL)
3248 		(*mp)->mb_ifp = fin->fin_ifp;
3249 	blockreason = fin->fin_reason;
3250 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3251 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3252 		if ((pass & FR_NOMATCH) != 0)
3253 			return 1;
3254 
3255 	if ((pass & FR_RETMASK) != 0)
3256 		switch (pass & FR_RETMASK)
3257 		{
3258 		case FR_RETRST :
3259 			return 3;
3260 		case FR_RETICMP :
3261 			return 4;
3262 		case FR_FAKEICMP :
3263 			return 5;
3264 		}
3265 
3266 	switch (pass & FR_CMDMASK)
3267 	{
3268 	case FR_PASS :
3269 		return 0;
3270 	case FR_BLOCK :
3271 		return -1;
3272 	case FR_AUTH :
3273 		return -2;
3274 	case FR_ACCOUNT :
3275 		return -3;
3276 	case FR_PREAUTH :
3277 		return -4;
3278 	}
3279 	return 2;
3280 #endif /* _KERNEL */
3281 }
3282 
3283 
3284 #ifdef	IPFILTER_LOG
3285 /* ------------------------------------------------------------------------ */
3286 /* Function:    ipf_dolog                                                   */
3287 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3288 /* Parameters:  fin(I) - pointer to packet information                      */
3289 /*              passp(IO) - pointer to current/new filter decision (unused) */
3290 /*                                                                          */
3291 /* Checks flags set to see how a packet should be logged, if it is to be    */
3292 /* logged.  Adjust statistics based on its success or not.                  */
3293 /* ------------------------------------------------------------------------ */
3294 frentry_t *
ipf_dolog(fin,passp)3295 ipf_dolog(fin, passp)
3296 	fr_info_t *fin;
3297 	u_32_t *passp;
3298 {
3299 	ipf_main_softc_t *softc = fin->fin_main_soft;
3300 	u_32_t pass;
3301 	int out;
3302 
3303 	out = fin->fin_out;
3304 	pass = *passp;
3305 
3306 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3307 		pass |= FF_LOGNOMATCH;
3308 		LBUMPD(ipf_stats[out], fr_npkl);
3309 		goto logit;
3310 
3311 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3312 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3313 		if ((pass & FR_LOGMASK) != FR_LOGP)
3314 			pass |= FF_LOGPASS;
3315 		LBUMPD(ipf_stats[out], fr_ppkl);
3316 		goto logit;
3317 
3318 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3319 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3320 		if ((pass & FR_LOGMASK) != FR_LOGB)
3321 			pass |= FF_LOGBLOCK;
3322 		LBUMPD(ipf_stats[out], fr_bpkl);
3323 
3324 logit:
3325 		if (ipf_log_pkt(fin, pass) == -1) {
3326 			/*
3327 			 * If the "or-block" option has been used then
3328 			 * block the packet if we failed to log it.
3329 			 */
3330 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3331 				DT1(frb_logfail2, u_int, pass);
3332 				pass &= ~FR_CMDMASK;
3333 				pass |= FR_BLOCK;
3334 				fin->fin_reason = FRB_LOGFAIL2;
3335 			}
3336 		}
3337 		*passp = pass;
3338 	}
3339 
3340 	return fin->fin_fr;
3341 }
3342 #endif /* IPFILTER_LOG */
3343 
3344 
3345 /* ------------------------------------------------------------------------ */
3346 /* Function:    ipf_cksum                                                   */
3347 /* Returns:     u_short - IP header checksum                                */
3348 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3349 /*              len(I)  - length of buffer in bytes                         */
3350 /*                                                                          */
3351 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3352 /*                                                                          */
3353 /* N.B.: addr should be 16bit aligned.                                      */
3354 /* ------------------------------------------------------------------------ */
3355 u_short
ipf_cksum(addr,len)3356 ipf_cksum(addr, len)
3357 	u_short *addr;
3358 	int len;
3359 {
3360 	u_32_t sum = 0;
3361 
3362 	for (sum = 0; len > 1; len -= 2)
3363 		sum += *addr++;
3364 
3365 	/* mop up an odd byte, if necessary */
3366 	if (len == 1)
3367 		sum += *(u_char *)addr;
3368 
3369 	/*
3370 	 * add back carry outs from top 16 bits to low 16 bits
3371 	 */
3372 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3373 	sum += (sum >> 16);			/* add carry */
3374 	return (u_short)(~sum);
3375 }
3376 
3377 
3378 /* ------------------------------------------------------------------------ */
3379 /* Function:    fr_cksum                                                    */
3380 /* Returns:     u_short - layer 4 checksum                                  */
3381 /* Parameters:  fin(I)     - pointer to packet information                  */
3382 /*              ip(I)      - pointer to IP header                           */
3383 /*              l4proto(I) - protocol to caclulate checksum for             */
3384 /*              l4hdr(I)   - pointer to layer 4 header                      */
3385 /*                                                                          */
3386 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3387 /* in the IP header "ip" to seed it.                                        */
3388 /*                                                                          */
3389 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3390 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3391 /* odd sizes.                                                               */
3392 /*                                                                          */
3393 /* Expects ip_len and ip_off to be in network byte order when called.       */
3394 /* ------------------------------------------------------------------------ */
3395 u_short
fr_cksum(fin,ip,l4proto,l4hdr)3396 fr_cksum(fin, ip, l4proto, l4hdr)
3397 	fr_info_t *fin;
3398 	ip_t *ip;
3399 	int l4proto;
3400 	void *l4hdr;
3401 {
3402 	u_short *sp, slen, sumsave, *csump;
3403 	u_int sum, sum2;
3404 	int hlen;
3405 	int off;
3406 #ifdef	USE_INET6
3407 	ip6_t *ip6;
3408 #endif
3409 
3410 	csump = NULL;
3411 	sumsave = 0;
3412 	sp = NULL;
3413 	slen = 0;
3414 	hlen = 0;
3415 	sum = 0;
3416 
3417 	sum = htons((u_short)l4proto);
3418 	/*
3419 	 * Add up IP Header portion
3420 	 */
3421 #ifdef	USE_INET6
3422 	if (IP_V(ip) == 4) {
3423 #endif
3424 		hlen = IP_HL(ip) << 2;
3425 		off = hlen;
3426 		sp = (u_short *)&ip->ip_src;
3427 		sum += *sp++;	/* ip_src */
3428 		sum += *sp++;
3429 		sum += *sp++;	/* ip_dst */
3430 		sum += *sp++;
3431 		slen = fin->fin_plen - off;
3432 		sum += htons(slen);
3433 #ifdef	USE_INET6
3434 	} else if (IP_V(ip) == 6) {
3435 		mb_t *m;
3436 
3437 		m = fin->fin_m;
3438 		ip6 = (ip6_t *)ip;
3439 		off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3440 		int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3441 		return(ipf_pcksum6(m, ip6, off, len));
3442 	} else {
3443 		return 0xffff;
3444 	}
3445 #endif
3446 
3447 	switch (l4proto)
3448 	{
3449 	case IPPROTO_UDP :
3450 		csump = &((udphdr_t *)l4hdr)->uh_sum;
3451 		break;
3452 
3453 	case IPPROTO_TCP :
3454 		csump = &((tcphdr_t *)l4hdr)->th_sum;
3455 		break;
3456 	case IPPROTO_ICMP :
3457 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3458 		sum = 0;	/* Pseudo-checksum is not included */
3459 		break;
3460 #ifdef USE_INET6
3461 	case IPPROTO_ICMPV6 :
3462 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3463 		break;
3464 #endif
3465 	default :
3466 		break;
3467 	}
3468 
3469 	if (csump != NULL) {
3470 		sumsave = *csump;
3471 		*csump = 0;
3472 	}
3473 
3474 	sum2 = ipf_pcksum(fin, off, sum);
3475 	if (csump != NULL)
3476 		*csump = sumsave;
3477 	return sum2;
3478 }
3479 
3480 
3481 /* ------------------------------------------------------------------------ */
3482 /* Function:    ipf_findgroup                                               */
3483 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3484 /* Parameters:  softc(I) - pointer to soft context main structure           */
3485 /*              group(I) - group name to search for                         */
3486 /*              unit(I)  - device to which this group belongs               */
3487 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3488 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3489 /*                         to where to add the next (last) group or where   */
3490 /*                         to delete group from.                            */
3491 /*                                                                          */
3492 /* Search amongst the defined groups for a particular group number.         */
3493 /* ------------------------------------------------------------------------ */
3494 frgroup_t *
ipf_findgroup(softc,group,unit,set,fgpp)3495 ipf_findgroup(softc, group, unit, set, fgpp)
3496 	ipf_main_softc_t *softc;
3497 	char *group;
3498 	minor_t unit;
3499 	int set;
3500 	frgroup_t ***fgpp;
3501 {
3502 	frgroup_t *fg, **fgp;
3503 
3504 	/*
3505 	 * Which list of groups to search in is dependent on which list of
3506 	 * rules are being operated on.
3507 	 */
3508 	fgp = &softc->ipf_groups[unit][set];
3509 
3510 	while ((fg = *fgp) != NULL) {
3511 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3512 			break;
3513 		else
3514 			fgp = &fg->fg_next;
3515 	}
3516 	if (fgpp != NULL)
3517 		*fgpp = fgp;
3518 	return fg;
3519 }
3520 
3521 
3522 /* ------------------------------------------------------------------------ */
3523 /* Function:    ipf_group_add                                               */
3524 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3525 /*                            != NULL == pointer to the group               */
3526 /* Parameters:  softc(I) - pointer to soft context main structure           */
3527 /*              num(I)   - group number to add                              */
3528 /*              head(I)  - rule pointer that is using this as the head      */
3529 /*              flags(I) - rule flags which describe the type of rule it is */
3530 /*              unit(I)  - device to which this group will belong to        */
3531 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3532 /* Write Locks: ipf_mutex                                                   */
3533 /*                                                                          */
3534 /* Add a new group head, or if it already exists, increase the reference    */
3535 /* count to it.                                                             */
3536 /* ------------------------------------------------------------------------ */
3537 frgroup_t *
ipf_group_add(softc,group,head,flags,unit,set)3538 ipf_group_add(softc, group, head, flags, unit, set)
3539 	ipf_main_softc_t *softc;
3540 	char *group;
3541 	void *head;
3542 	u_32_t flags;
3543 	minor_t unit;
3544 	int set;
3545 {
3546 	frgroup_t *fg, **fgp;
3547 	u_32_t gflags;
3548 
3549 	if (group == NULL)
3550 		return NULL;
3551 
3552 	if (unit == IPL_LOGIPF && *group == '\0')
3553 		return NULL;
3554 
3555 	fgp = NULL;
3556 	gflags = flags & FR_INOUT;
3557 
3558 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3559 	if (fg != NULL) {
3560 		if (fg->fg_head == NULL && head != NULL)
3561 			fg->fg_head = head;
3562 		if (fg->fg_flags == 0)
3563 			fg->fg_flags = gflags;
3564 		else if (gflags != fg->fg_flags)
3565 			return NULL;
3566 		fg->fg_ref++;
3567 		return fg;
3568 	}
3569 
3570 	KMALLOC(fg, frgroup_t *);
3571 	if (fg != NULL) {
3572 		fg->fg_head = head;
3573 		fg->fg_start = NULL;
3574 		fg->fg_next = *fgp;
3575 		bcopy(group, fg->fg_name, strlen(group) + 1);
3576 		fg->fg_flags = gflags;
3577 		fg->fg_ref = 1;
3578 		fg->fg_set = &softc->ipf_groups[unit][set];
3579 		*fgp = fg;
3580 	}
3581 	return fg;
3582 }
3583 
3584 
3585 /* ------------------------------------------------------------------------ */
3586 /* Function:    ipf_group_del                                               */
3587 /* Returns:     int      - number of rules deleted                          */
3588 /* Parameters:  softc(I) - pointer to soft context main structure           */
3589 /*              group(I) - group name to delete                             */
3590 /*              fr(I)    - filter rule from which group is referenced       */
3591 /* Write Locks: ipf_mutex                                                   */
3592 /*                                                                          */
3593 /* This function is called whenever a reference to a group is to be dropped */
3594 /* and thus its reference count needs to be lowered and the group free'd if */
3595 /* the reference count reaches zero. Passing in fr is really for the sole   */
3596 /* purpose of knowing when the head rule is being deleted.                  */
3597 /* ------------------------------------------------------------------------ */
3598 void
ipf_group_del(softc,group,fr)3599 ipf_group_del(softc, group, fr)
3600 	ipf_main_softc_t *softc;
3601 	frgroup_t *group;
3602 	frentry_t *fr;
3603 {
3604 
3605 	if (group->fg_head == fr)
3606 		group->fg_head = NULL;
3607 
3608 	group->fg_ref--;
3609 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3610 		ipf_group_free(group);
3611 }
3612 
3613 
3614 /* ------------------------------------------------------------------------ */
3615 /* Function:    ipf_group_free                                              */
3616 /* Returns:     Nil                                                         */
3617 /* Parameters:  group(I) - pointer to filter rule group                     */
3618 /*                                                                          */
3619 /* Remove the group from the list of groups and free it.                    */
3620 /* ------------------------------------------------------------------------ */
3621 static void
ipf_group_free(group)3622 ipf_group_free(group)
3623 	frgroup_t *group;
3624 {
3625 	frgroup_t **gp;
3626 
3627 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3628 		if (*gp == group) {
3629 			*gp = group->fg_next;
3630 			break;
3631 		}
3632 	}
3633 	KFREE(group);
3634 }
3635 
3636 
3637 /* ------------------------------------------------------------------------ */
3638 /* Function:    ipf_group_flush                                             */
3639 /* Returns:     int      - number of rules flush from group                 */
3640 /* Parameters:  softc(I) - pointer to soft context main structure           */
3641 /* Parameters:  group(I) - pointer to filter rule group                     */
3642 /*                                                                          */
3643 /* Remove all of the rules that currently are listed under the given group. */
3644 /* ------------------------------------------------------------------------ */
3645 static int
ipf_group_flush(softc,group)3646 ipf_group_flush(softc, group)
3647 	ipf_main_softc_t *softc;
3648 	frgroup_t *group;
3649 {
3650 	int gone = 0;
3651 
3652 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3653 
3654 	return gone;
3655 }
3656 
3657 
3658 /* ------------------------------------------------------------------------ */
3659 /* Function:    ipf_getrulen                                                */
3660 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3661 /* Parameters:  softc(I) - pointer to soft context main structure           */
3662 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3663 /*              flags(I) - which set of rules to find the rule in           */
3664 /*              group(I) - group name                                       */
3665 /*              n(I)     - rule number to find                              */
3666 /*                                                                          */
3667 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3668 /* group # g doesn't exist or there are less than n rules in the group.     */
3669 /* ------------------------------------------------------------------------ */
3670 frentry_t *
ipf_getrulen(softc,unit,group,n)3671 ipf_getrulen(softc, unit, group, n)
3672 	ipf_main_softc_t *softc;
3673 	int unit;
3674 	char *group;
3675 	u_32_t n;
3676 {
3677 	frentry_t *fr;
3678 	frgroup_t *fg;
3679 
3680 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3681 	if (fg == NULL)
3682 		return NULL;
3683 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3684 		;
3685 	if (n != 0)
3686 		return NULL;
3687 	return fr;
3688 }
3689 
3690 
3691 /* ------------------------------------------------------------------------ */
3692 /* Function:    ipf_flushlist                                               */
3693 /* Returns:     int - >= 0 - number of flushed rules                        */
3694 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3695 /*              nfreedp(O) - pointer to int where flush count is stored     */
3696 /*              listp(I)   - pointer to list to flush pointer               */
3697 /* Write Locks: ipf_mutex                                                   */
3698 /*                                                                          */
3699 /* Recursively flush rules from the list, descending groups as they are     */
3700 /* encountered.  if a rule is the head of a group and it has lost all its   */
3701 /* group members, then also delete the group reference.  nfreedp is needed  */
3702 /* to store the accumulating count of rules removed, whereas the returned   */
3703 /* value is just the number removed from the current list.  The latter is   */
3704 /* needed to correctly adjust reference counts on rules that define groups. */
3705 /*                                                                          */
3706 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3707 /* ------------------------------------------------------------------------ */
3708 static int
ipf_flushlist(softc,nfreedp,listp)3709 ipf_flushlist(softc, nfreedp, listp)
3710 	ipf_main_softc_t *softc;
3711 	int *nfreedp;
3712 	frentry_t **listp;
3713 {
3714 	int freed = 0;
3715 	frentry_t *fp;
3716 
3717 	while ((fp = *listp) != NULL) {
3718 		if ((fp->fr_type & FR_T_BUILTIN) ||
3719 		    !(fp->fr_flags & FR_COPIED)) {
3720 			listp = &fp->fr_next;
3721 			continue;
3722 		}
3723 		*listp = fp->fr_next;
3724 		if (fp->fr_next != NULL)
3725 			fp->fr_next->fr_pnext = fp->fr_pnext;
3726 		fp->fr_pnext = NULL;
3727 
3728 		if (fp->fr_grphead != NULL) {
3729 			freed += ipf_group_flush(softc, fp->fr_grphead);
3730 			fp->fr_names[fp->fr_grhead] = '\0';
3731 		}
3732 
3733 		if (fp->fr_icmpgrp != NULL) {
3734 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3735 			fp->fr_names[fp->fr_icmphead] = '\0';
3736 		}
3737 
3738 		if (fp->fr_srctrack.ht_max_nodes)
3739 			ipf_rb_ht_flush(&fp->fr_srctrack);
3740 
3741 		fp->fr_next = NULL;
3742 
3743 		ASSERT(fp->fr_ref > 0);
3744 		if (ipf_derefrule(softc, &fp) == 0)
3745 			freed++;
3746 	}
3747 	*nfreedp += freed;
3748 	return freed;
3749 }
3750 
3751 
3752 /* ------------------------------------------------------------------------ */
3753 /* Function:    ipf_flush                                                   */
3754 /* Returns:     int - >= 0 - number of flushed rules                        */
3755 /* Parameters:  softc(I) - pointer to soft context main structure           */
3756 /*              unit(I)  - device for which to flush rules                  */
3757 /*              flags(I) - which set of rules to flush                      */
3758 /*                                                                          */
3759 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3760 /* and IPv6) as defined by the value of flags.                              */
3761 /* ------------------------------------------------------------------------ */
3762 int
ipf_flush(softc,unit,flags)3763 ipf_flush(softc, unit, flags)
3764 	ipf_main_softc_t *softc;
3765 	minor_t unit;
3766 	int flags;
3767 {
3768 	int flushed = 0, set;
3769 
3770 	WRITE_ENTER(&softc->ipf_mutex);
3771 
3772 	set = softc->ipf_active;
3773 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3774 		set = 1 - set;
3775 
3776 	if (flags & FR_OUTQUE) {
3777 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3778 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3779 	}
3780 	if (flags & FR_INQUE) {
3781 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3782 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3783 	}
3784 
3785 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3786 				    flags & (FR_INQUE|FR_OUTQUE));
3787 
3788 	RWLOCK_EXIT(&softc->ipf_mutex);
3789 
3790 	if (unit == IPL_LOGIPF) {
3791 		int tmp;
3792 
3793 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3794 		if (tmp >= 0)
3795 			flushed += tmp;
3796 	}
3797 	return flushed;
3798 }
3799 
3800 
3801 /* ------------------------------------------------------------------------ */
3802 /* Function:    ipf_flush_groups                                            */
3803 /* Returns:     int - >= 0 - number of flushed rules                        */
3804 /* Parameters:  softc(I)  - soft context pointerto work with                */
3805 /*              grhead(I) - pointer to the start of the group list to flush */
3806 /*              flags(I)  - which set of rules to flush                     */
3807 /*                                                                          */
3808 /* Walk through all of the groups under the given group head and remove all */
3809 /* of those that match the flags passed in. The for loop here is bit more   */
3810 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3811 /* may end up removing not only the structure pointed to by "fg" but also   */
3812 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3813 /* removed from the group then it is necessary to start again.              */
3814 /* ------------------------------------------------------------------------ */
3815 static int
ipf_flush_groups(softc,grhead,flags)3816 ipf_flush_groups(softc, grhead, flags)
3817 	ipf_main_softc_t *softc;
3818 	frgroup_t **grhead;
3819 	int flags;
3820 {
3821 	frentry_t *fr, **frp;
3822 	frgroup_t *fg, **fgp;
3823 	int flushed = 0;
3824 	int removed = 0;
3825 
3826 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3827 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3828 			fg = fg->fg_next;
3829 		if (fg == NULL)
3830 			break;
3831 		removed = 0;
3832 		frp = &fg->fg_start;
3833 		while ((removed == 0) && ((fr = *frp) != NULL)) {
3834 			if ((fr->fr_flags & flags) == 0) {
3835 				frp = &fr->fr_next;
3836 			} else {
3837 				if (fr->fr_next != NULL)
3838 					fr->fr_next->fr_pnext = fr->fr_pnext;
3839 				*frp = fr->fr_next;
3840 				fr->fr_pnext = NULL;
3841 				fr->fr_next = NULL;
3842 				(void) ipf_derefrule(softc, &fr);
3843 				flushed++;
3844 				removed++;
3845 			}
3846 		}
3847 		if (removed == 0)
3848 			fgp = &fg->fg_next;
3849 	}
3850 	return flushed;
3851 }
3852 
3853 
3854 /* ------------------------------------------------------------------------ */
3855 /* Function:    memstr                                                      */
3856 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3857 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3858 /*              dst(I)  - pointer to byte sequence to search                */
3859 /*              slen(I) - match length                                      */
3860 /*              dlen(I) - length available to search in                     */
3861 /*                                                                          */
3862 /* Search dst for a sequence of bytes matching those at src and extend for  */
3863 /* slen bytes.                                                              */
3864 /* ------------------------------------------------------------------------ */
3865 char *
memstr(src,dst,slen,dlen)3866 memstr(src, dst, slen, dlen)
3867 	const char *src;
3868 	char *dst;
3869 	size_t slen, dlen;
3870 {
3871 	char *s = NULL;
3872 
3873 	while (dlen >= slen) {
3874 		if (bcmp(src, dst, slen) == 0) {
3875 			s = dst;
3876 			break;
3877 		}
3878 		dst++;
3879 		dlen--;
3880 	}
3881 	return s;
3882 }
3883 /* ------------------------------------------------------------------------ */
3884 /* Function:    ipf_fixskip                                                 */
3885 /* Returns:     Nil                                                         */
3886 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3887 /*              rp(I)        - rule added/removed with skip in it.          */
3888 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3889 /*                             depending on whether a rule was just added   */
3890 /*                             or removed.                                  */
3891 /*                                                                          */
3892 /* Adjust all the rules in a list which would have skip'd past the position */
3893 /* where we are inserting to skip to the right place given the change.      */
3894 /* ------------------------------------------------------------------------ */
3895 void
ipf_fixskip(listp,rp,addremove)3896 ipf_fixskip(listp, rp, addremove)
3897 	frentry_t **listp, *rp;
3898 	int addremove;
3899 {
3900 	int rules, rn;
3901 	frentry_t *fp;
3902 
3903 	rules = 0;
3904 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3905 		rules++;
3906 
3907 	if (fp == NULL)
3908 		return;
3909 
3910 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3911 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3912 			fp->fr_arg += addremove;
3913 }
3914 
3915 
3916 #ifdef	_KERNEL
3917 /* ------------------------------------------------------------------------ */
3918 /* Function:    count4bits                                                  */
3919 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3920 /* Parameters:  ip(I) - 32bit IP address                                    */
3921 /*                                                                          */
3922 /* IPv4 ONLY                                                                */
3923 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3924 /* consecutive 1's is different to that passed, return -1, else return #    */
3925 /* of bits.                                                                 */
3926 /* ------------------------------------------------------------------------ */
3927 int
count4bits(ip)3928 count4bits(ip)
3929 	u_32_t	ip;
3930 {
3931 	u_32_t	ipn;
3932 	int	cnt = 0, i, j;
3933 
3934 	ip = ipn = ntohl(ip);
3935 	for (i = 32; i; i--, ipn *= 2)
3936 		if (ipn & 0x80000000)
3937 			cnt++;
3938 		else
3939 			break;
3940 	ipn = 0;
3941 	for (i = 32, j = cnt; i; i--, j--) {
3942 		ipn *= 2;
3943 		if (j > 0)
3944 			ipn++;
3945 	}
3946 	if (ipn == ip)
3947 		return cnt;
3948 	return -1;
3949 }
3950 
3951 
3952 /* ------------------------------------------------------------------------ */
3953 /* Function:    count6bits                                                  */
3954 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3955 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3956 /*                                                                          */
3957 /* IPv6 ONLY                                                                */
3958 /* count consecutive 1's in bit mask.                                       */
3959 /* ------------------------------------------------------------------------ */
3960 # ifdef USE_INET6
3961 int
count6bits(msk)3962 count6bits(msk)
3963 	u_32_t *msk;
3964 {
3965 	int i = 0, k;
3966 	u_32_t j;
3967 
3968 	for (k = 3; k >= 0; k--)
3969 		if (msk[k] == 0xffffffff)
3970 			i += 32;
3971 		else {
3972 			for (j = msk[k]; j; j <<= 1)
3973 				if (j & 0x80000000)
3974 					i++;
3975 		}
3976 	return i;
3977 }
3978 # endif
3979 #endif /* _KERNEL */
3980 
3981 
3982 /* ------------------------------------------------------------------------ */
3983 /* Function:    ipf_synclist                                                */
3984 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3985 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3986 /*              ifp(I) - interface pointer for limiting sync lookups        */
3987 /* Write Locks: ipf_mutex                                                   */
3988 /*                                                                          */
3989 /* Walk through a list of filter rules and resolve any interface names into */
3990 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3991 /* used in the rule.  The interface pointer is used to limit the lookups to */
3992 /* a specific set of matching names if it is non-NULL.                      */
3993 /* Errors can occur when resolving the destination name of to/dup-to fields */
3994 /* when the name points to a pool and that pool doest not exist. If this    */
3995 /* does happen then it is necessary to check if there are any lookup refs   */
3996 /* that need to be dropped before returning with an error.                  */
3997 /* ------------------------------------------------------------------------ */
3998 static int
ipf_synclist(softc,fr,ifp)3999 ipf_synclist(softc, fr, ifp)
4000 	ipf_main_softc_t *softc;
4001 	frentry_t *fr;
4002 	void *ifp;
4003 {
4004 	frentry_t *frt, *start = fr;
4005 	frdest_t *fdp;
4006 	char *name;
4007 	int error;
4008 	void *ifa;
4009 	int v, i;
4010 
4011 	error = 0;
4012 
4013 	for (; fr; fr = fr->fr_next) {
4014 		if (fr->fr_family == AF_INET)
4015 			v = 4;
4016 		else if (fr->fr_family == AF_INET6)
4017 			v = 6;
4018 		else
4019 			v = 0;
4020 
4021 		/*
4022 		 * Lookup all the interface names that are part of the rule.
4023 		 */
4024 		for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
4025 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4026 				continue;
4027 			if (fr->fr_ifnames[i] == -1)
4028 				continue;
4029 			name = FR_NAME(fr, fr_ifnames[i]);
4030 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4031 		}
4032 
4033 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4034 			if (fr->fr_satype != FRI_NORMAL &&
4035 			    fr->fr_satype != FRI_LOOKUP) {
4036 				ifa = ipf_resolvenic(softc, fr->fr_names +
4037 						     fr->fr_sifpidx, v);
4038 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4039 					    &fr->fr_src6, &fr->fr_smsk6);
4040 			}
4041 			if (fr->fr_datype != FRI_NORMAL &&
4042 			    fr->fr_datype != FRI_LOOKUP) {
4043 				ifa = ipf_resolvenic(softc, fr->fr_names +
4044 						     fr->fr_sifpidx, v);
4045 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4046 					    &fr->fr_dst6, &fr->fr_dmsk6);
4047 			}
4048 		}
4049 
4050 		fdp = &fr->fr_tifs[0];
4051 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4052 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4053 			if (error != 0)
4054 				goto unwind;
4055 		}
4056 
4057 		fdp = &fr->fr_tifs[1];
4058 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4059 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4060 			if (error != 0)
4061 				goto unwind;
4062 		}
4063 
4064 		fdp = &fr->fr_dif;
4065 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4066 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4067 			if (error != 0)
4068 				goto unwind;
4069 		}
4070 
4071 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4072 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4073 			fr->fr_srcptr = ipf_lookup_res_num(softc,
4074 							   fr->fr_srctype,
4075 							   IPL_LOGIPF,
4076 							   fr->fr_srcnum,
4077 							   &fr->fr_srcfunc);
4078 		}
4079 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4080 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4081 			fr->fr_dstptr = ipf_lookup_res_num(softc,
4082 							   fr->fr_dsttype,
4083 							   IPL_LOGIPF,
4084 							   fr->fr_dstnum,
4085 							   &fr->fr_dstfunc);
4086 		}
4087 	}
4088 	return 0;
4089 
4090 unwind:
4091 	for (frt = start; frt != fr; fr = fr->fr_next) {
4092 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4093 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4094 				ipf_lookup_deref(softc, frt->fr_srctype,
4095 						 frt->fr_srcptr);
4096 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4097 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4098 				ipf_lookup_deref(softc, frt->fr_dsttype,
4099 						 frt->fr_dstptr);
4100 	}
4101 	return error;
4102 }
4103 
4104 
4105 /* ------------------------------------------------------------------------ */
4106 /* Function:    ipf_sync                                                    */
4107 /* Returns:     void                                                        */
4108 /* Parameters:  Nil                                                         */
4109 /*                                                                          */
4110 /* ipf_sync() is called when we suspect that the interface list or          */
4111 /* information about interfaces (like IP#) has changed.  Go through all     */
4112 /* filter rules, NAT entries and the state table and check if anything      */
4113 /* needs to be changed/updated.                                             */
4114 /* ------------------------------------------------------------------------ */
4115 int
ipf_sync(softc,ifp)4116 ipf_sync(softc, ifp)
4117 	ipf_main_softc_t *softc;
4118 	void *ifp;
4119 {
4120 	int i;
4121 
4122 # if !SOLARIS
4123 	ipf_nat_sync(softc, ifp);
4124 	ipf_state_sync(softc, ifp);
4125 	ipf_lookup_sync(softc, ifp);
4126 # endif
4127 
4128 	WRITE_ENTER(&softc->ipf_mutex);
4129 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4130 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4131 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4132 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4133 
4134 	for (i = 0; i < IPL_LOGSIZE; i++) {
4135 		frgroup_t *g;
4136 
4137 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4138 			(void) ipf_synclist(softc, g->fg_start, ifp);
4139 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4140 			(void) ipf_synclist(softc, g->fg_start, ifp);
4141 	}
4142 	RWLOCK_EXIT(&softc->ipf_mutex);
4143 
4144 	return 0;
4145 }
4146 
4147 
4148 /*
4149  * In the functions below, bcopy() is called because the pointer being
4150  * copied _from_ in this instance is a pointer to a char buf (which could
4151  * end up being unaligned) and on the kernel's local stack.
4152  */
4153 /* ------------------------------------------------------------------------ */
4154 /* Function:    copyinptr                                                   */
4155 /* Returns:     int - 0 = success, else failure                             */
4156 /* Parameters:  src(I)  - pointer to the source address                     */
4157 /*              dst(I)  - destination address                               */
4158 /*              size(I) - number of bytes to copy                           */
4159 /*                                                                          */
4160 /* Copy a block of data in from user space, given a pointer to the pointer  */
4161 /* to start copying from (src) and a pointer to where to store it (dst).    */
4162 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4163 /* ------------------------------------------------------------------------ */
4164 int
copyinptr(softc,src,dst,size)4165 copyinptr(softc, src, dst, size)
4166 	ipf_main_softc_t *softc;
4167 	void *src, *dst;
4168 	size_t size;
4169 {
4170 	caddr_t ca;
4171 	int error;
4172 
4173 # if SOLARIS
4174 	error = COPYIN(src, &ca, sizeof(ca));
4175 	if (error != 0)
4176 		return error;
4177 # else
4178 	bcopy(src, (caddr_t)&ca, sizeof(ca));
4179 # endif
4180 	error = COPYIN(ca, dst, size);
4181 	if (error != 0) {
4182 		IPFERROR(3);
4183 		error = EFAULT;
4184 	}
4185 	return error;
4186 }
4187 
4188 
4189 /* ------------------------------------------------------------------------ */
4190 /* Function:    copyoutptr                                                  */
4191 /* Returns:     int - 0 = success, else failure                             */
4192 /* Parameters:  src(I)  - pointer to the source address                     */
4193 /*              dst(I)  - destination address                               */
4194 /*              size(I) - number of bytes to copy                           */
4195 /*                                                                          */
4196 /* Copy a block of data out to user space, given a pointer to the pointer   */
4197 /* to start copying from (src) and a pointer to where to store it (dst).    */
4198 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4199 /* ------------------------------------------------------------------------ */
4200 int
copyoutptr(softc,src,dst,size)4201 copyoutptr(softc, src, dst, size)
4202 	ipf_main_softc_t *softc;
4203 	void *src, *dst;
4204 	size_t size;
4205 {
4206 	caddr_t ca;
4207 	int error;
4208 
4209 	bcopy(dst, (caddr_t)&ca, sizeof(ca));
4210 	error = COPYOUT(src, ca, size);
4211 	if (error != 0) {
4212 		IPFERROR(4);
4213 		error = EFAULT;
4214 	}
4215 	return error;
4216 }
4217 
4218 
4219 /* ------------------------------------------------------------------------ */
4220 /* Function:    ipf_lock                                                    */
4221 /* Returns:     int      - 0 = success, else error                          */
4222 /* Parameters:  data(I)  - pointer to lock value to set                     */
4223 /*              lockp(O) - pointer to location to store old lock value      */
4224 /*                                                                          */
4225 /* Get the new value for the lock integer, set it and return the old value  */
4226 /* in *lockp.                                                               */
4227 /* ------------------------------------------------------------------------ */
4228 int
ipf_lock(data,lockp)4229 ipf_lock(data, lockp)
4230 	caddr_t data;
4231 	int *lockp;
4232 {
4233 	int arg, err;
4234 
4235 	err = BCOPYIN(data, &arg, sizeof(arg));
4236 	if (err != 0)
4237 		return EFAULT;
4238 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4239 	if (err != 0)
4240 		return EFAULT;
4241 	*lockp = arg;
4242 	return 0;
4243 }
4244 
4245 
4246 /* ------------------------------------------------------------------------ */
4247 /* Function:    ipf_getstat                                                 */
4248 /* Returns:     Nil                                                         */
4249 /* Parameters:  softc(I) - pointer to soft context main structure           */
4250 /*              fiop(I)  - pointer to ipfilter stats structure              */
4251 /*              rev(I)   - version claim by program doing ioctl             */
4252 /*                                                                          */
4253 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4254 /* structure.                                                               */
4255 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4256 /* program is looking for. This ensure that validation of the version it    */
4257 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4258 /* allow older binaries to work but kernels without it will not.            */
4259 /* ------------------------------------------------------------------------ */
4260 /*ARGSUSED*/
4261 static void
ipf_getstat(softc,fiop,rev)4262 ipf_getstat(softc, fiop, rev)
4263 	ipf_main_softc_t *softc;
4264 	friostat_t *fiop;
4265 	int rev;
4266 {
4267 	int i;
4268 
4269 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4270 	      sizeof(ipf_statistics_t) * 2);
4271 	fiop->f_locks[IPL_LOGSTATE] = -1;
4272 	fiop->f_locks[IPL_LOGNAT] = -1;
4273 	fiop->f_locks[IPL_LOGIPF] = -1;
4274 	fiop->f_locks[IPL_LOGAUTH] = -1;
4275 
4276 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4277 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4278 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4279 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4280 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4281 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4282 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4283 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4284 
4285 	fiop->f_ticks = softc->ipf_ticks;
4286 	fiop->f_active = softc->ipf_active;
4287 	fiop->f_froute[0] = softc->ipf_frouteok[0];
4288 	fiop->f_froute[1] = softc->ipf_frouteok[1];
4289 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4290 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4291 
4292 	fiop->f_running = softc->ipf_running;
4293 	for (i = 0; i < IPL_LOGSIZE; i++) {
4294 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4295 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4296 	}
4297 #ifdef  IPFILTER_LOG
4298 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4299 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4300 	fiop->f_logging = 1;
4301 #else
4302 	fiop->f_log_ok = 0;
4303 	fiop->f_log_fail = 0;
4304 	fiop->f_logging = 0;
4305 #endif
4306 	fiop->f_defpass = softc->ipf_pass;
4307 	fiop->f_features = ipf_features;
4308 
4309 #ifdef IPFILTER_COMPAT
4310 	sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4311 		(rev / 1000000) % 100,
4312 		(rev / 10000) % 100,
4313 		(rev / 100) % 100);
4314 #else
4315 	rev = rev;
4316 	(void) strncpy(fiop->f_version, ipfilter_version,
4317 		       sizeof(fiop->f_version));
4318 #endif
4319 }
4320 
4321 
4322 #ifdef	USE_INET6
4323 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4324 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4325 	-1,			/* 1: UNUSED */
4326 	-1,			/* 2: UNUSED */
4327 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4328 	-1,			/* 4: ICMP_SOURCEQUENCH */
4329 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4330 	-1,			/* 6: UNUSED */
4331 	-1,			/* 7: UNUSED */
4332 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4333 	-1,			/* 9: UNUSED */
4334 	-1,			/* 10: UNUSED */
4335 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4336 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4337 	-1,			/* 13: ICMP_TSTAMP */
4338 	-1,			/* 14: ICMP_TSTAMPREPLY */
4339 	-1,			/* 15: ICMP_IREQ */
4340 	-1,			/* 16: ICMP_IREQREPLY */
4341 	-1,			/* 17: ICMP_MASKREQ */
4342 	-1,			/* 18: ICMP_MASKREPLY */
4343 };
4344 
4345 
4346 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4347 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4348 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4349 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4350 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4351 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4352 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4353 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4354 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4355 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4356 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4357 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4358 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4359 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4360 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4361 };
4362 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4363 #endif
4364 
4365 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4366 
4367 
4368 /* ------------------------------------------------------------------------ */
4369 /* Function:    ipf_matchicmpqueryreply                                     */
4370 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4371 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4372 /*              ic(I)   - ICMP information                                  */
4373 /*              icmp(I) - ICMP packet header                                */
4374 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4375 /*                                                                          */
4376 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4377 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4378 /* else return 0 for no match.                                              */
4379 /* ------------------------------------------------------------------------ */
4380 int
ipf_matchicmpqueryreply(v,ic,icmp,rev)4381 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4382 	int v;
4383 	icmpinfo_t *ic;
4384 	icmphdr_t *icmp;
4385 	int rev;
4386 {
4387 	int ictype;
4388 
4389 	ictype = ic->ici_type;
4390 
4391 	if (v == 4) {
4392 		/*
4393 		 * If we matched its type on the way in, then when going out
4394 		 * it will still be the same type.
4395 		 */
4396 		if ((!rev && (icmp->icmp_type == ictype)) ||
4397 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4398 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4399 				return 1;
4400 			if (icmp->icmp_id == ic->ici_id)
4401 				return 1;
4402 		}
4403 	}
4404 #ifdef	USE_INET6
4405 	else if (v == 6) {
4406 		if ((!rev && (icmp->icmp_type == ictype)) ||
4407 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4408 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4409 				return 1;
4410 			if (icmp->icmp_id == ic->ici_id)
4411 				return 1;
4412 		}
4413 	}
4414 #endif
4415 	return 0;
4416 }
4417 
4418 
4419 /*
4420  * IFNAMES are located in the variable length field starting at
4421  * frentry.fr_names. As pointers within the struct cannot be passed
4422  * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4423  * is unused (invalid). If it is used (valid) it is an offset to the
4424  * character string of an interface name or a comment. The following
4425  * macros will assist those who follow to understand the code.
4426  */
4427 #define IPF_IFNAME_VALID(_a)	(_a != -1)
4428 #define IPF_IFNAME_INVALID(_a)	(_a == -1)
4429 #define IPF_IFNAMES_DIFFERENT(_a)	\
4430 	!((IPF_IFNAME_INVALID(fr1->_a) &&	\
4431 	IPF_IFNAME_INVALID(fr2->_a)) ||	\
4432 	(IPF_IFNAME_VALID(fr1->_a) &&	\
4433 	IPF_IFNAME_VALID(fr2->_a) &&	\
4434 	!strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4435 #define IPF_FRDEST_DIFFERENT(_a)	\
4436 	(memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr,	\
4437 	offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) ||	\
4438 	IPF_IFNAMES_DIFFERENT(_a.fd_name))
4439 
4440 
4441 /* ------------------------------------------------------------------------ */
4442 /* Function:    ipf_rule_compare                                            */
4443 /* Parameters:  fr1(I) - first rule structure to compare                    */
4444 /*              fr2(I) - second rule structure to compare                   */
4445 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4446 /*                                                                          */
4447 /* Compare two rules and return 0 if they match or a number indicating      */
4448 /* which of the individual checks failed.                                   */
4449 /* ------------------------------------------------------------------------ */
4450 static int
ipf_rule_compare(frentry_t * fr1,frentry_t * fr2)4451 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4452 {
4453 	int i;
4454 
4455 	if (fr1->fr_cksum != fr2->fr_cksum)
4456 		return (1);
4457 	if (fr1->fr_size != fr2->fr_size)
4458 		return (2);
4459 	if (fr1->fr_dsize != fr2->fr_dsize)
4460 		return (3);
4461 	if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4462 	    != 0)
4463 		return (4);
4464 	/*
4465 	 * XXX:	There is still a bug here as different rules with the
4466 	 *	the same interfaces but in a different order will compare
4467 	 *	differently. But since multiple interfaces in a rule doesn't
4468 	 *	work anyway a simple straightforward compare is performed
4469 	 *	here. Ultimately frentry_t creation will need to be
4470 	 *	revisited in ipf_y.y. While the other issue, recognition
4471 	 *	of only the first interface in a list of interfaces will
4472 	 *	need to be separately addressed along with why only four.
4473 	 */
4474 	for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4475 		/*
4476 		 * XXX:	It's either the same index or uninitialized.
4477 		 * 	We assume this because multiple interfaces
4478 		 *	referenced by the same rule doesn't work anyway.
4479 		 */
4480 		if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4481 			return(5);
4482 	}
4483 
4484 	if (IPF_FRDEST_DIFFERENT(fr_tif))
4485 		return (6);
4486 	if (IPF_FRDEST_DIFFERENT(fr_rif))
4487 		return (7);
4488 	if (IPF_FRDEST_DIFFERENT(fr_dif))
4489 		return (8);
4490 	if (!fr1->fr_data && !fr2->fr_data)
4491 		return (0);	/* move along, nothing to see here */
4492 	if (fr1->fr_data && fr2->fr_data) {
4493 		if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4494 			return (0);	/* same */
4495 	}
4496 	return (9);
4497 }
4498 
4499 
4500 /* ------------------------------------------------------------------------ */
4501 /* Function:    frrequest                                                   */
4502 /* Returns:     int - 0 == success, > 0 == errno value                      */
4503 /* Parameters:  unit(I)     - device for which this is for                  */
4504 /*              req(I)      - ioctl command (SIOC*)                         */
4505 /*              data(I)     - pointr to ioctl data                          */
4506 /*              set(I)      - 1 or 0 (filter set)                           */
4507 /*              makecopy(I) - flag indicating whether data points to a rule */
4508 /*                            in kernel space & hence doesn't need copying. */
4509 /*                                                                          */
4510 /* This function handles all the requests which operate on the list of      */
4511 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4512 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4513 /* names are resolved here and other sanity checks are made on the content  */
4514 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4515 /* then make sure they are created and initialised before exiting.          */
4516 /* ------------------------------------------------------------------------ */
4517 int
frrequest(softc,unit,req,data,set,makecopy)4518 frrequest(softc, unit, req, data, set, makecopy)
4519 	ipf_main_softc_t *softc;
4520 	int unit;
4521 	ioctlcmd_t req;
4522 	int set, makecopy;
4523 	caddr_t data;
4524 {
4525 	int error = 0, in, family, need_free = 0;
4526 	enum {	OP_ADD,		/* add rule */
4527 		OP_REM,		/* remove rule */
4528 		OP_ZERO 	/* zero statistics and counters */ }
4529 		addrem = OP_ADD;
4530 	frentry_t frd, *fp, *f, **fprev, **ftail;
4531 	void *ptr, *uptr, *cptr;
4532 	u_int *p, *pp;
4533 	frgroup_t *fg;
4534 	char *group;
4535 
4536 	ptr = NULL;
4537 	cptr = NULL;
4538 	fg = NULL;
4539 	fp = &frd;
4540 	if (makecopy != 0) {
4541 		bzero(fp, sizeof(frd));
4542 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4543 		if (error) {
4544 			return error;
4545 		}
4546 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4547 			IPFERROR(6);
4548 			return EINVAL;
4549 		}
4550 		KMALLOCS(f, frentry_t *, fp->fr_size);
4551 		if (f == NULL) {
4552 			IPFERROR(131);
4553 			return ENOMEM;
4554 		}
4555 		bzero(f, fp->fr_size);
4556 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4557 				    fp->fr_size);
4558 		if (error) {
4559 			KFREES(f, fp->fr_size);
4560 			return error;
4561 		}
4562 
4563 		fp = f;
4564 		f = NULL;
4565 		fp->fr_next = NULL;
4566 		fp->fr_dnext = NULL;
4567 		fp->fr_pnext = NULL;
4568 		fp->fr_pdnext = NULL;
4569 		fp->fr_grp = NULL;
4570 		fp->fr_grphead = NULL;
4571 		fp->fr_icmpgrp = NULL;
4572 		fp->fr_isc = (void *)-1;
4573 		fp->fr_ptr = NULL;
4574 		fp->fr_ref = 0;
4575 		fp->fr_flags |= FR_COPIED;
4576 	} else {
4577 		fp = (frentry_t *)data;
4578 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4579 			IPFERROR(7);
4580 			return EINVAL;
4581 		}
4582 		fp->fr_flags &= ~FR_COPIED;
4583 	}
4584 
4585 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4586 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4587 		IPFERROR(8);
4588 		error = EINVAL;
4589 		goto donenolock;
4590 	}
4591 
4592 	family = fp->fr_family;
4593 	uptr = fp->fr_data;
4594 
4595 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4596 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4597 		addrem = OP_ADD;	/* Add rule */
4598 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4599 		addrem = OP_REM;		/* Remove rule */
4600 	else if (req == (ioctlcmd_t)SIOCZRLST)
4601 		addrem = OP_ZERO;	/* Zero statistics and counters */
4602 	else {
4603 		IPFERROR(9);
4604 		error = EINVAL;
4605 		goto donenolock;
4606 	}
4607 
4608 	/*
4609 	 * Only filter rules for IPv4 or IPv6 are accepted.
4610 	 */
4611 	if (family == AF_INET) {
4612 		/*EMPTY*/;
4613 #ifdef	USE_INET6
4614 	} else if (family == AF_INET6) {
4615 		/*EMPTY*/;
4616 #endif
4617 	} else if (family != 0) {
4618 		IPFERROR(10);
4619 		error = EINVAL;
4620 		goto donenolock;
4621 	}
4622 
4623 	/*
4624 	 * If the rule is being loaded from user space, i.e. we had to copy it
4625 	 * into kernel space, then do not trust the function pointer in the
4626 	 * rule.
4627 	 */
4628 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4629 		if (ipf_findfunc(fp->fr_func) == NULL) {
4630 			IPFERROR(11);
4631 			error = ESRCH;
4632 			goto donenolock;
4633 		}
4634 
4635 		if (addrem == OP_ADD) {
4636 			error = ipf_funcinit(softc, fp);
4637 			if (error != 0)
4638 				goto donenolock;
4639 		}
4640 	}
4641 	if ((fp->fr_flags & FR_CALLNOW) &&
4642 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4643 		IPFERROR(142);
4644 		error = ESRCH;
4645 		goto donenolock;
4646 	}
4647 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4648 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4649 		IPFERROR(143);
4650 		error = ESRCH;
4651 		goto donenolock;
4652 	}
4653 
4654 	ptr = NULL;
4655 	cptr = NULL;
4656 
4657 	if (FR_ISACCOUNT(fp->fr_flags))
4658 		unit = IPL_LOGCOUNT;
4659 
4660 	/*
4661 	 * Check that each group name in the rule has a start index that
4662 	 * is valid.
4663 	 */
4664 	if (fp->fr_icmphead != -1) {
4665 		if ((fp->fr_icmphead < 0) ||
4666 		    (fp->fr_icmphead >= fp->fr_namelen)) {
4667 			IPFERROR(136);
4668 			error = EINVAL;
4669 			goto donenolock;
4670 		}
4671 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4672 			fp->fr_names[fp->fr_icmphead] = '\0';
4673 	}
4674 
4675 	if (fp->fr_grhead != -1) {
4676 		if ((fp->fr_grhead < 0) ||
4677 		    (fp->fr_grhead >= fp->fr_namelen)) {
4678 			IPFERROR(137);
4679 			error = EINVAL;
4680 			goto donenolock;
4681 		}
4682 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4683 			fp->fr_names[fp->fr_grhead] = '\0';
4684 	}
4685 
4686 	if (fp->fr_group != -1) {
4687 		if ((fp->fr_group < 0) ||
4688 		    (fp->fr_group >= fp->fr_namelen)) {
4689 			IPFERROR(138);
4690 			error = EINVAL;
4691 			goto donenolock;
4692 		}
4693 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4694 			/*
4695 			 * Allow loading rules that are in groups to cause
4696 			 * them to be created if they don't already exit.
4697 			 */
4698 			group = FR_NAME(fp, fr_group);
4699 			if (addrem == OP_ADD) {
4700 				fg = ipf_group_add(softc, group, NULL,
4701 						   fp->fr_flags, unit, set);
4702 				fp->fr_grp = fg;
4703 			} else {
4704 				fg = ipf_findgroup(softc, group, unit,
4705 						   set, NULL);
4706 				if (fg == NULL) {
4707 					IPFERROR(12);
4708 					error = ESRCH;
4709 					goto donenolock;
4710 				}
4711 			}
4712 
4713 			if (fg->fg_flags == 0) {
4714 				fg->fg_flags = fp->fr_flags & FR_INOUT;
4715 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4716 				IPFERROR(13);
4717 				error = ESRCH;
4718 				goto donenolock;
4719 			}
4720 		}
4721 	} else {
4722 		/*
4723 		 * If a rule is going to be part of a group then it does
4724 		 * not matter whether it is an in or out rule, but if it
4725 		 * isn't in a group, then it does...
4726 		 */
4727 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4728 			IPFERROR(14);
4729 			error = EINVAL;
4730 			goto donenolock;
4731 		}
4732 	}
4733 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4734 
4735 	/*
4736 	 * Work out which rule list this change is being applied to.
4737 	 */
4738 	ftail = NULL;
4739 	fprev = NULL;
4740 	if (unit == IPL_LOGAUTH) {
4741                 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4742 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4743 		    (fp->fr_dif.fd_ptr != NULL) ||
4744 		    (fp->fr_flags & FR_FASTROUTE)) {
4745 			softc->ipf_interror = 145;
4746 			error = EINVAL;
4747 			goto donenolock;
4748 		}
4749 		fprev = ipf_auth_rulehead(softc);
4750 	} else {
4751 		if (FR_ISACCOUNT(fp->fr_flags))
4752 			fprev = &softc->ipf_acct[in][set];
4753 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4754 			fprev = &softc->ipf_rules[in][set];
4755 	}
4756 	if (fprev == NULL) {
4757 		IPFERROR(15);
4758 		error = ESRCH;
4759 		goto donenolock;
4760 	}
4761 
4762 	if (fg != NULL)
4763 		fprev = &fg->fg_start;
4764 
4765 	/*
4766 	 * Copy in extra data for the rule.
4767 	 */
4768 	if (fp->fr_dsize != 0) {
4769 		if (makecopy != 0) {
4770 			KMALLOCS(ptr, void *, fp->fr_dsize);
4771 			if (ptr == NULL) {
4772 				IPFERROR(16);
4773 				error = ENOMEM;
4774 				goto donenolock;
4775 			}
4776 
4777 			/*
4778 			 * The bcopy case is for when the data is appended
4779 			 * to the rule by ipf_in_compat().
4780 			 */
4781 			if (uptr >= (void *)fp &&
4782 			    uptr < (void *)((char *)fp + fp->fr_size)) {
4783 				bcopy(uptr, ptr, fp->fr_dsize);
4784 				error = 0;
4785 			} else {
4786 				error = COPYIN(uptr, ptr, fp->fr_dsize);
4787 				if (error != 0) {
4788 					IPFERROR(17);
4789 					error = EFAULT;
4790 					goto donenolock;
4791 				}
4792 			}
4793 		} else {
4794 			ptr = uptr;
4795 		}
4796 		fp->fr_data = ptr;
4797 	} else {
4798 		fp->fr_data = NULL;
4799 	}
4800 
4801 	/*
4802 	 * Perform per-rule type sanity checks of their members.
4803 	 * All code after this needs to be aware that allocated memory
4804 	 * may need to be free'd before exiting.
4805 	 */
4806 	switch (fp->fr_type & ~FR_T_BUILTIN)
4807 	{
4808 #if defined(IPFILTER_BPF)
4809 	case FR_T_BPFOPC :
4810 		if (fp->fr_dsize == 0) {
4811 			IPFERROR(19);
4812 			error = EINVAL;
4813 			break;
4814 		}
4815 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4816 			IPFERROR(20);
4817 			error = EINVAL;
4818 			break;
4819 		}
4820 		break;
4821 #endif
4822 	case FR_T_IPF :
4823 		/*
4824 		 * Preparation for error case at the bottom of this function.
4825 		 */
4826 		if (fp->fr_datype == FRI_LOOKUP)
4827 			fp->fr_dstptr = NULL;
4828 		if (fp->fr_satype == FRI_LOOKUP)
4829 			fp->fr_srcptr = NULL;
4830 
4831 		if (fp->fr_dsize != sizeof(fripf_t)) {
4832 			IPFERROR(21);
4833 			error = EINVAL;
4834 			break;
4835 		}
4836 
4837 		/*
4838 		 * Allowing a rule with both "keep state" and "with oow" is
4839 		 * pointless because adding a state entry to the table will
4840 		 * fail with the out of window (oow) flag set.
4841 		 */
4842 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4843 			IPFERROR(22);
4844 			error = EINVAL;
4845 			break;
4846 		}
4847 
4848 		switch (fp->fr_satype)
4849 		{
4850 		case FRI_BROADCAST :
4851 		case FRI_DYNAMIC :
4852 		case FRI_NETWORK :
4853 		case FRI_NETMASKED :
4854 		case FRI_PEERADDR :
4855 			if (fp->fr_sifpidx < 0) {
4856 				IPFERROR(23);
4857 				error = EINVAL;
4858 			}
4859 			break;
4860 		case FRI_LOOKUP :
4861 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4862 						       &fp->fr_src6,
4863 						       &fp->fr_smsk6);
4864 			if (fp->fr_srcfunc == NULL) {
4865 				IPFERROR(132);
4866 				error = ESRCH;
4867 				break;
4868 			}
4869 			break;
4870 		case FRI_NORMAL :
4871 			break;
4872 		default :
4873 			IPFERROR(133);
4874 			error = EINVAL;
4875 			break;
4876 		}
4877 		if (error != 0)
4878 			break;
4879 
4880 		switch (fp->fr_datype)
4881 		{
4882 		case FRI_BROADCAST :
4883 		case FRI_DYNAMIC :
4884 		case FRI_NETWORK :
4885 		case FRI_NETMASKED :
4886 		case FRI_PEERADDR :
4887 			if (fp->fr_difpidx < 0) {
4888 				IPFERROR(24);
4889 				error = EINVAL;
4890 			}
4891 			break;
4892 		case FRI_LOOKUP :
4893 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4894 						       &fp->fr_dst6,
4895 						       &fp->fr_dmsk6);
4896 			if (fp->fr_dstfunc == NULL) {
4897 				IPFERROR(134);
4898 				error = ESRCH;
4899 			}
4900 			break;
4901 		case FRI_NORMAL :
4902 			break;
4903 		default :
4904 			IPFERROR(135);
4905 			error = EINVAL;
4906 		}
4907 		break;
4908 
4909 	case FR_T_NONE :
4910 	case FR_T_CALLFUNC :
4911 	case FR_T_COMPIPF :
4912 		break;
4913 
4914 	case FR_T_IPFEXPR :
4915 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4916 			IPFERROR(25);
4917 			error = EINVAL;
4918 		}
4919 		break;
4920 
4921 	default :
4922 		IPFERROR(26);
4923 		error = EINVAL;
4924 		break;
4925 	}
4926 	if (error != 0)
4927 		goto donenolock;
4928 
4929 	if (fp->fr_tif.fd_name != -1) {
4930 		if ((fp->fr_tif.fd_name < 0) ||
4931 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4932 			IPFERROR(139);
4933 			error = EINVAL;
4934 			goto donenolock;
4935 		}
4936 	}
4937 
4938 	if (fp->fr_dif.fd_name != -1) {
4939 		if ((fp->fr_dif.fd_name < 0) ||
4940 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4941 			IPFERROR(140);
4942 			error = EINVAL;
4943 			goto donenolock;
4944 		}
4945 	}
4946 
4947 	if (fp->fr_rif.fd_name != -1) {
4948 		if ((fp->fr_rif.fd_name < 0) ||
4949 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4950 			IPFERROR(141);
4951 			error = EINVAL;
4952 			goto donenolock;
4953 		}
4954 	}
4955 
4956 	/*
4957 	 * Lookup all the interface names that are part of the rule.
4958 	 */
4959 	error = ipf_synclist(softc, fp, NULL);
4960 	if (error != 0)
4961 		goto donenolock;
4962 	fp->fr_statecnt = 0;
4963 	if (fp->fr_srctrack.ht_max_nodes != 0)
4964 		ipf_rb_ht_init(&fp->fr_srctrack);
4965 
4966 	/*
4967 	 * Look for an existing matching filter rule, but don't include the
4968 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4969 	 * This elminates rules which are indentical being loaded.  Checksum
4970 	 * the constant part of the filter rule to make comparisons quicker
4971 	 * (this meaning no pointers are included).
4972 	 */
4973 	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4974 	for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4975 		fp->fr_cksum += *p;
4976 
4977 	WRITE_ENTER(&softc->ipf_mutex);
4978 
4979 	/*
4980 	 * Now that the filter rule lists are locked, we can walk the
4981 	 * chain of them without fear.
4982 	 */
4983 	ftail = fprev;
4984 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4985 		if (fp->fr_collect <= f->fr_collect) {
4986 			ftail = fprev;
4987 			f = NULL;
4988 			break;
4989 		}
4990 		fprev = ftail;
4991 	}
4992 
4993 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4994 		if (ipf_rule_compare(fp, f) == 0)
4995 			break;
4996 	}
4997 
4998 	/*
4999 	 * If zero'ing statistics, copy current to caller and zero.
5000 	 */
5001 	if (addrem == OP_ZERO) {
5002 		if (f == NULL) {
5003 			IPFERROR(27);
5004 			error = ESRCH;
5005 		} else {
5006 			/*
5007 			 * Copy and reduce lock because of impending copyout.
5008 			 * Well we should, but if we do then the atomicity of
5009 			 * this call and the correctness of fr_hits and
5010 			 * fr_bytes cannot be guaranteed.  As it is, this code
5011 			 * only resets them to 0 if they are successfully
5012 			 * copied out into user space.
5013 			 */
5014 			bcopy((char *)f, (char *)fp, f->fr_size);
5015 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
5016 
5017 			/*
5018 			 * When we copy this rule back out, set the data
5019 			 * pointer to be what it was in user space.
5020 			 */
5021 			fp->fr_data = uptr;
5022 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
5023 
5024 			if (error == 0) {
5025 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
5026 					error = COPYOUT(f->fr_data, uptr,
5027 							f->fr_dsize);
5028 					if (error == 0) {
5029 						f->fr_hits = 0;
5030 						f->fr_bytes = 0;
5031 					} else {
5032 						IPFERROR(28);
5033 						error = EFAULT;
5034 					}
5035 				}
5036 			}
5037 		}
5038 
5039 		if (makecopy != 0) {
5040 			if (ptr != NULL) {
5041 				KFREES(ptr, fp->fr_dsize);
5042 			}
5043 			KFREES(fp, fp->fr_size);
5044 		}
5045 		RWLOCK_EXIT(&softc->ipf_mutex);
5046 		return error;
5047 	}
5048 
5049 	if (f == NULL) {
5050 		/*
5051 		 * At the end of this, ftail must point to the place where the
5052 		 * new rule is to be saved/inserted/added.
5053 		 * For SIOCAD*FR, this should be the last rule in the group of
5054 		 * rules that have equal fr_collect fields.
5055 		 * For SIOCIN*FR, ...
5056 		 */
5057 		if (req == (ioctlcmd_t)SIOCADAFR ||
5058 		    req == (ioctlcmd_t)SIOCADIFR) {
5059 
5060 			for (ftail = fprev; (f = *ftail) != NULL; ) {
5061 				if (f->fr_collect > fp->fr_collect)
5062 					break;
5063 				ftail = &f->fr_next;
5064 				fprev = ftail;
5065 			}
5066 			ftail = fprev;
5067 			f = NULL;
5068 			ptr = NULL;
5069 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
5070 			   req == (ioctlcmd_t)SIOCINIFR) {
5071 			while ((f = *fprev) != NULL) {
5072 				if (f->fr_collect >= fp->fr_collect)
5073 					break;
5074 				fprev = &f->fr_next;
5075 			}
5076   			ftail = fprev;
5077   			if (fp->fr_hits != 0) {
5078 				while (fp->fr_hits && (f = *ftail)) {
5079 					if (f->fr_collect != fp->fr_collect)
5080 						break;
5081 					fprev = ftail;
5082   					ftail = &f->fr_next;
5083 					fp->fr_hits--;
5084 				}
5085   			}
5086   			f = NULL;
5087   			ptr = NULL;
5088 		}
5089 	}
5090 
5091 	/*
5092 	 * Request to remove a rule.
5093 	 */
5094 	if (addrem == OP_REM) {
5095 		if (f == NULL) {
5096 			IPFERROR(29);
5097 			error = ESRCH;
5098 		} else {
5099 			/*
5100 			 * Do not allow activity from user space to interfere
5101 			 * with rules not loaded that way.
5102 			 */
5103 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5104 				IPFERROR(30);
5105 				error = EPERM;
5106 				goto done;
5107 			}
5108 
5109 			/*
5110 			 * Return EBUSY if the rule is being reference by
5111 			 * something else (eg state information.)
5112 			 */
5113 			if (f->fr_ref > 1) {
5114 				IPFERROR(31);
5115 				error = EBUSY;
5116 				goto done;
5117 			}
5118 #ifdef	IPFILTER_SCAN
5119 			if (f->fr_isctag != -1 &&
5120 			    (f->fr_isc != (struct ipscan *)-1))
5121 				ipf_scan_detachfr(f);
5122 #endif
5123 
5124 			if (unit == IPL_LOGAUTH) {
5125 				error = ipf_auth_precmd(softc, req, f, ftail);
5126 				goto done;
5127 			}
5128 
5129 			ipf_rule_delete(softc, f, unit, set);
5130 
5131 			need_free = makecopy;
5132 		}
5133 	} else {
5134 		/*
5135 		 * Not removing, so we must be adding/inserting a rule.
5136 		 */
5137 		if (f != NULL) {
5138 			IPFERROR(32);
5139 			error = EEXIST;
5140 			goto done;
5141 		}
5142 		if (unit == IPL_LOGAUTH) {
5143 			error = ipf_auth_precmd(softc, req, fp, ftail);
5144 			goto done;
5145 		}
5146 
5147 		MUTEX_NUKE(&fp->fr_lock);
5148 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5149 		if (fp->fr_die != 0)
5150 			ipf_rule_expire_insert(softc, fp, set);
5151 
5152 		fp->fr_hits = 0;
5153 		if (makecopy != 0)
5154 			fp->fr_ref = 1;
5155 		fp->fr_pnext = ftail;
5156 		fp->fr_next = *ftail;
5157 		if (fp->fr_next != NULL)
5158 			fp->fr_next->fr_pnext = &fp->fr_next;
5159 		*ftail = fp;
5160 		ipf_fixskip(ftail, fp, 1);
5161 
5162 		fp->fr_icmpgrp = NULL;
5163 		if (fp->fr_icmphead != -1) {
5164 			group = FR_NAME(fp, fr_icmphead);
5165 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5166 			fp->fr_icmpgrp = fg;
5167 		}
5168 
5169 		fp->fr_grphead = NULL;
5170 		if (fp->fr_grhead != -1) {
5171 			group = FR_NAME(fp, fr_grhead);
5172 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5173 					   unit, set);
5174 			fp->fr_grphead = fg;
5175 		}
5176 	}
5177 done:
5178 	RWLOCK_EXIT(&softc->ipf_mutex);
5179 donenolock:
5180 	if (need_free || (error != 0)) {
5181 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5182 			if ((fp->fr_satype == FRI_LOOKUP) &&
5183 			    (fp->fr_srcptr != NULL))
5184 				ipf_lookup_deref(softc, fp->fr_srctype,
5185 						 fp->fr_srcptr);
5186 			if ((fp->fr_datype == FRI_LOOKUP) &&
5187 			    (fp->fr_dstptr != NULL))
5188 				ipf_lookup_deref(softc, fp->fr_dsttype,
5189 						 fp->fr_dstptr);
5190 		}
5191 		if (fp->fr_grp != NULL) {
5192 			WRITE_ENTER(&softc->ipf_mutex);
5193 			ipf_group_del(softc, fp->fr_grp, fp);
5194 			RWLOCK_EXIT(&softc->ipf_mutex);
5195 		}
5196 		if ((ptr != NULL) && (makecopy != 0)) {
5197 			KFREES(ptr, fp->fr_dsize);
5198 		}
5199 		KFREES(fp, fp->fr_size);
5200 	}
5201 	return (error);
5202 }
5203 
5204 
5205 /* ------------------------------------------------------------------------ */
5206 /* Function:   ipf_rule_delete                                              */
5207 /* Returns:    Nil                                                          */
5208 /* Parameters: softc(I) - pointer to soft context main structure            */
5209 /*             f(I)     - pointer to the rule being deleted                 */
5210 /*             ftail(I) - pointer to the pointer to f                       */
5211 /*             unit(I)  - device for which this is for                      */
5212 /*             set(I)   - 1 or 0 (filter set)                               */
5213 /*                                                                          */
5214 /* This function attempts to do what it can to delete a filter rule: remove */
5215 /* it from any linked lists and remove any groups it is responsible for.    */
5216 /* But in the end, removing a rule can only drop the reference count - we   */
5217 /* must use that as the guide for whether or not it can be freed.           */
5218 /* ------------------------------------------------------------------------ */
5219 static void
ipf_rule_delete(softc,f,unit,set)5220 ipf_rule_delete(softc, f, unit, set)
5221 	ipf_main_softc_t *softc;
5222 	frentry_t *f;
5223 	int unit, set;
5224 {
5225 
5226 	/*
5227 	 * If fr_pdnext is set, then the rule is on the expire list, so
5228 	 * remove it from there.
5229 	 */
5230 	if (f->fr_pdnext != NULL) {
5231 		*f->fr_pdnext = f->fr_dnext;
5232 		if (f->fr_dnext != NULL)
5233 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5234 		f->fr_pdnext = NULL;
5235 		f->fr_dnext = NULL;
5236 	}
5237 
5238 	ipf_fixskip(f->fr_pnext, f, -1);
5239 	if (f->fr_pnext != NULL)
5240 		*f->fr_pnext = f->fr_next;
5241 	if (f->fr_next != NULL)
5242 		f->fr_next->fr_pnext = f->fr_pnext;
5243 	f->fr_pnext = NULL;
5244 	f->fr_next = NULL;
5245 
5246 	(void) ipf_derefrule(softc, &f);
5247 }
5248 
5249 /* ------------------------------------------------------------------------ */
5250 /* Function:   ipf_rule_expire_insert                                       */
5251 /* Returns:    Nil                                                          */
5252 /* Parameters: softc(I) - pointer to soft context main structure            */
5253 /*             f(I)     - pointer to rule to be added to expire list        */
5254 /*             set(I)   - 1 or 0 (filter set)                               */
5255 /*                                                                          */
5256 /* If the new rule has a given expiration time, insert it into the list of  */
5257 /* expiring rules with the ones to be removed first added to the front of   */
5258 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5259 /* expiration interval checks.                                              */
5260 /* ------------------------------------------------------------------------ */
5261 static void
ipf_rule_expire_insert(softc,f,set)5262 ipf_rule_expire_insert(softc, f, set)
5263 	ipf_main_softc_t *softc;
5264 	frentry_t *f;
5265 	int set;
5266 {
5267 	frentry_t *fr;
5268 
5269 	/*
5270 	 */
5271 
5272 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5273 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5274 	     fr = fr->fr_dnext) {
5275 		if (f->fr_die < fr->fr_die)
5276 			break;
5277 		if (fr->fr_dnext == NULL) {
5278 			/*
5279 			 * We've got to the last rule and everything
5280 			 * wanted to be expired before this new node,
5281 			 * so we have to tack it on the end...
5282 			 */
5283 			fr->fr_dnext = f;
5284 			f->fr_pdnext = &fr->fr_dnext;
5285 			fr = NULL;
5286 			break;
5287 		}
5288 	}
5289 
5290 	if (softc->ipf_rule_explist[set] == NULL) {
5291 		softc->ipf_rule_explist[set] = f;
5292 		f->fr_pdnext = &softc->ipf_rule_explist[set];
5293 	} else if (fr != NULL) {
5294 		f->fr_dnext = fr;
5295 		f->fr_pdnext = fr->fr_pdnext;
5296 		fr->fr_pdnext = &f->fr_dnext;
5297 	}
5298 }
5299 
5300 
5301 /* ------------------------------------------------------------------------ */
5302 /* Function:   ipf_findlookup                                               */
5303 /* Returns:    NULL = failure, else success                                 */
5304 /* Parameters: softc(I) - pointer to soft context main structure            */
5305 /*             unit(I)  - ipf device we want to find match for              */
5306 /*             fp(I)    - rule for which lookup is for                      */
5307 /*             addrp(I) - pointer to lookup information in address struct   */
5308 /*             maskp(O) - pointer to lookup information for storage         */
5309 /*                                                                          */
5310 /* When using pools and hash tables to store addresses for matching in      */
5311 /* rules, it is necessary to resolve both the object referred to by the     */
5312 /* name or address (and return that pointer) and also provide the means by  */
5313 /* which to determine if an address belongs to that object to make the      */
5314 /* packet matching quicker.                                                 */
5315 /* ------------------------------------------------------------------------ */
5316 static void *
ipf_findlookup(softc,unit,fr,addrp,maskp)5317 ipf_findlookup(softc, unit, fr, addrp, maskp)
5318 	ipf_main_softc_t *softc;
5319 	int unit;
5320 	frentry_t *fr;
5321 	i6addr_t *addrp, *maskp;
5322 {
5323 	void *ptr = NULL;
5324 
5325 	switch (addrp->iplookupsubtype)
5326 	{
5327 	case 0 :
5328 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5329 					 addrp->iplookupnum,
5330 					 &maskp->iplookupfunc);
5331 		break;
5332 	case 1 :
5333 		if (addrp->iplookupname < 0)
5334 			break;
5335 		if (addrp->iplookupname >= fr->fr_namelen)
5336 			break;
5337 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5338 					  fr->fr_names + addrp->iplookupname,
5339 					  &maskp->iplookupfunc);
5340 		break;
5341 	default :
5342 		break;
5343 	}
5344 
5345 	return ptr;
5346 }
5347 
5348 
5349 /* ------------------------------------------------------------------------ */
5350 /* Function:    ipf_funcinit                                                */
5351 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5352 /* Parameters:  softc(I) - pointer to soft context main structure           */
5353 /*              fr(I)    - pointer to filter rule                           */
5354 /*                                                                          */
5355 /* If a rule is a call rule, then check if the function it points to needs  */
5356 /* an init function to be called now the rule has been loaded.              */
5357 /* ------------------------------------------------------------------------ */
5358 static int
ipf_funcinit(softc,fr)5359 ipf_funcinit(softc, fr)
5360 	ipf_main_softc_t *softc;
5361 	frentry_t *fr;
5362 {
5363 	ipfunc_resolve_t *ft;
5364 	int err;
5365 
5366 	IPFERROR(34);
5367 	err = ESRCH;
5368 
5369 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5370 		if (ft->ipfu_addr == fr->fr_func) {
5371 			err = 0;
5372 			if (ft->ipfu_init != NULL)
5373 				err = (*ft->ipfu_init)(softc, fr);
5374 			break;
5375 		}
5376 	return err;
5377 }
5378 
5379 
5380 /* ------------------------------------------------------------------------ */
5381 /* Function:    ipf_funcfini                                                */
5382 /* Returns:     Nil                                                         */
5383 /* Parameters:  softc(I) - pointer to soft context main structure           */
5384 /*              fr(I)    - pointer to filter rule                           */
5385 /*                                                                          */
5386 /* For a given filter rule, call the matching "fini" function if the rule   */
5387 /* is using a known function that would have resulted in the "init" being   */
5388 /* called for ealier.                                                       */
5389 /* ------------------------------------------------------------------------ */
5390 static void
ipf_funcfini(softc,fr)5391 ipf_funcfini(softc, fr)
5392 	ipf_main_softc_t *softc;
5393 	frentry_t *fr;
5394 {
5395 	ipfunc_resolve_t *ft;
5396 
5397 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5398 		if (ft->ipfu_addr == fr->fr_func) {
5399 			if (ft->ipfu_fini != NULL)
5400 				(void) (*ft->ipfu_fini)(softc, fr);
5401 			break;
5402 		}
5403 }
5404 
5405 
5406 /* ------------------------------------------------------------------------ */
5407 /* Function:    ipf_findfunc                                                */
5408 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5409 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5410 /*                                                                          */
5411 /* Look for a function in the table of known functions.                     */
5412 /* ------------------------------------------------------------------------ */
5413 static ipfunc_t
ipf_findfunc(funcptr)5414 ipf_findfunc(funcptr)
5415 	ipfunc_t funcptr;
5416 {
5417 	ipfunc_resolve_t *ft;
5418 
5419 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5420 		if (ft->ipfu_addr == funcptr)
5421 			return funcptr;
5422 	return NULL;
5423 }
5424 
5425 
5426 /* ------------------------------------------------------------------------ */
5427 /* Function:    ipf_resolvefunc                                             */
5428 /* Returns:     int - 0 == success, else error                              */
5429 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5430 /*                                                                          */
5431 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5432 /* This will either be the function name (if the pointer is set) or the     */
5433 /* function pointer if the name is set.  When found, fill in the other one  */
5434 /* so that the entire, complete, structure can be copied back to user space.*/
5435 /* ------------------------------------------------------------------------ */
5436 int
ipf_resolvefunc(softc,data)5437 ipf_resolvefunc(softc, data)
5438 	ipf_main_softc_t *softc;
5439 	void *data;
5440 {
5441 	ipfunc_resolve_t res, *ft;
5442 	int error;
5443 
5444 	error = BCOPYIN(data, &res, sizeof(res));
5445 	if (error != 0) {
5446 		IPFERROR(123);
5447 		return EFAULT;
5448 	}
5449 
5450 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5451 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5452 			if (strncmp(res.ipfu_name, ft->ipfu_name,
5453 				    sizeof(res.ipfu_name)) == 0) {
5454 				res.ipfu_addr = ft->ipfu_addr;
5455 				res.ipfu_init = ft->ipfu_init;
5456 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5457 					IPFERROR(35);
5458 					return EFAULT;
5459 				}
5460 				return 0;
5461 			}
5462 	}
5463 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5464 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5465 			if (ft->ipfu_addr == res.ipfu_addr) {
5466 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5467 					       sizeof(res.ipfu_name));
5468 				res.ipfu_init = ft->ipfu_init;
5469 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5470 					IPFERROR(36);
5471 					return EFAULT;
5472 				}
5473 				return 0;
5474 			}
5475 	}
5476 	IPFERROR(37);
5477 	return ESRCH;
5478 }
5479 
5480 
5481 #if !defined(_KERNEL) || SOLARIS
5482 /*
5483  * From: NetBSD
5484  * ppsratecheck(): packets (or events) per second limitation.
5485  */
5486 int
ppsratecheck(lasttime,curpps,maxpps)5487 ppsratecheck(lasttime, curpps, maxpps)
5488 	struct timeval *lasttime;
5489 	int *curpps;
5490 	int maxpps;	/* maximum pps allowed */
5491 {
5492 	struct timeval tv, delta;
5493 	int rv;
5494 
5495 	GETKTIME(&tv);
5496 
5497 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5498 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5499 	if (delta.tv_usec < 0) {
5500 		delta.tv_sec--;
5501 		delta.tv_usec += 1000000;
5502 	}
5503 
5504 	/*
5505 	 * check for 0,0 is so that the message will be seen at least once.
5506 	 * if more than one second have passed since the last update of
5507 	 * lasttime, reset the counter.
5508 	 *
5509 	 * we do increment *curpps even in *curpps < maxpps case, as some may
5510 	 * try to use *curpps for stat purposes as well.
5511 	 */
5512 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5513 	    delta.tv_sec >= 1) {
5514 		*lasttime = tv;
5515 		*curpps = 0;
5516 		rv = 1;
5517 	} else if (maxpps < 0)
5518 		rv = 1;
5519 	else if (*curpps < maxpps)
5520 		rv = 1;
5521 	else
5522 		rv = 0;
5523 	*curpps = *curpps + 1;
5524 
5525 	return (rv);
5526 }
5527 #endif
5528 
5529 
5530 /* ------------------------------------------------------------------------ */
5531 /* Function:    ipf_derefrule                                               */
5532 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5533 /* Parameters:  fr(I) - pointer to filter rule                              */
5534 /*                                                                          */
5535 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5536 /* free it and any associated storage space being used by it.               */
5537 /* ------------------------------------------------------------------------ */
5538 int
ipf_derefrule(softc,frp)5539 ipf_derefrule(softc, frp)
5540 	ipf_main_softc_t *softc;
5541 	frentry_t **frp;
5542 {
5543 	frentry_t *fr;
5544 	frdest_t *fdp;
5545 
5546 	fr = *frp;
5547 	*frp = NULL;
5548 
5549 	MUTEX_ENTER(&fr->fr_lock);
5550 	fr->fr_ref--;
5551 	if (fr->fr_ref == 0) {
5552 		MUTEX_EXIT(&fr->fr_lock);
5553 		MUTEX_DESTROY(&fr->fr_lock);
5554 
5555 		ipf_funcfini(softc, fr);
5556 
5557 		fdp = &fr->fr_tif;
5558 		if (fdp->fd_type == FRD_DSTLIST)
5559 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5560 
5561 		fdp = &fr->fr_rif;
5562 		if (fdp->fd_type == FRD_DSTLIST)
5563 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5564 
5565 		fdp = &fr->fr_dif;
5566 		if (fdp->fd_type == FRD_DSTLIST)
5567 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5568 
5569 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5570 		    fr->fr_satype == FRI_LOOKUP)
5571 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5572 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5573 		    fr->fr_datype == FRI_LOOKUP)
5574 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5575 
5576 		if (fr->fr_grp != NULL)
5577 			ipf_group_del(softc, fr->fr_grp, fr);
5578 
5579 		if (fr->fr_grphead != NULL)
5580 			ipf_group_del(softc, fr->fr_grphead, fr);
5581 
5582 		if (fr->fr_icmpgrp != NULL)
5583 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5584 
5585 		if ((fr->fr_flags & FR_COPIED) != 0) {
5586 			if (fr->fr_dsize) {
5587 				KFREES(fr->fr_data, fr->fr_dsize);
5588 			}
5589 			KFREES(fr, fr->fr_size);
5590 			return 0;
5591 		}
5592 		return 1;
5593 	} else {
5594 		MUTEX_EXIT(&fr->fr_lock);
5595 	}
5596 	return -1;
5597 }
5598 
5599 
5600 /* ------------------------------------------------------------------------ */
5601 /* Function:    ipf_grpmapinit                                              */
5602 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5603 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5604 /*                                                                          */
5605 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5606 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5607 /* ------------------------------------------------------------------------ */
5608 static int
ipf_grpmapinit(softc,fr)5609 ipf_grpmapinit(softc, fr)
5610 	ipf_main_softc_t *softc;
5611 	frentry_t *fr;
5612 {
5613 	char name[FR_GROUPLEN];
5614 	iphtable_t *iph;
5615 
5616 #if defined(SNPRINTF) && defined(_KERNEL)
5617 	SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5618 #else
5619 	(void) sprintf(name, "%d", fr->fr_arg);
5620 #endif
5621 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5622 	if (iph == NULL) {
5623 		IPFERROR(38);
5624 		return ESRCH;
5625 	}
5626 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5627 		IPFERROR(39);
5628 		return ESRCH;
5629 	}
5630 	iph->iph_ref++;
5631 	fr->fr_ptr = iph;
5632 	return 0;
5633 }
5634 
5635 
5636 /* ------------------------------------------------------------------------ */
5637 /* Function:    ipf_grpmapfini                                              */
5638 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5639 /* Parameters:  softc(I) - pointer to soft context main structure           */
5640 /*              fr(I)    - pointer to rule to release hash table for        */
5641 /*                                                                          */
5642 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5643 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5644 /* ------------------------------------------------------------------------ */
5645 static int
ipf_grpmapfini(softc,fr)5646 ipf_grpmapfini(softc, fr)
5647 	ipf_main_softc_t *softc;
5648 	frentry_t *fr;
5649 {
5650 	iphtable_t *iph;
5651 	iph = fr->fr_ptr;
5652 	if (iph != NULL)
5653 		ipf_lookup_deref(softc, IPLT_HASH, iph);
5654 	return 0;
5655 }
5656 
5657 
5658 /* ------------------------------------------------------------------------ */
5659 /* Function:    ipf_srcgrpmap                                               */
5660 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5661 /* Parameters:  fin(I)    - pointer to packet information                   */
5662 /*              passp(IO) - pointer to current/new filter decision (unused) */
5663 /*                                                                          */
5664 /* Look for a rule group head in a hash table, using the source address as  */
5665 /* the key, and descend into that group and continue matching rules against */
5666 /* the packet.                                                              */
5667 /* ------------------------------------------------------------------------ */
5668 frentry_t *
ipf_srcgrpmap(fin,passp)5669 ipf_srcgrpmap(fin, passp)
5670 	fr_info_t *fin;
5671 	u_32_t *passp;
5672 {
5673 	frgroup_t *fg;
5674 	void *rval;
5675 
5676 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5677 				 &fin->fin_src);
5678 	if (rval == NULL)
5679 		return NULL;
5680 
5681 	fg = rval;
5682 	fin->fin_fr = fg->fg_start;
5683 	(void) ipf_scanlist(fin, *passp);
5684 	return fin->fin_fr;
5685 }
5686 
5687 
5688 /* ------------------------------------------------------------------------ */
5689 /* Function:    ipf_dstgrpmap                                               */
5690 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5691 /* Parameters:  fin(I)    - pointer to packet information                   */
5692 /*              passp(IO) - pointer to current/new filter decision (unused) */
5693 /*                                                                          */
5694 /* Look for a rule group head in a hash table, using the destination        */
5695 /* address as the key, and descend into that group and continue matching    */
5696 /* rules against  the packet.                                               */
5697 /* ------------------------------------------------------------------------ */
5698 frentry_t *
ipf_dstgrpmap(fin,passp)5699 ipf_dstgrpmap(fin, passp)
5700 	fr_info_t *fin;
5701 	u_32_t *passp;
5702 {
5703 	frgroup_t *fg;
5704 	void *rval;
5705 
5706 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5707 				 &fin->fin_dst);
5708 	if (rval == NULL)
5709 		return NULL;
5710 
5711 	fg = rval;
5712 	fin->fin_fr = fg->fg_start;
5713 	(void) ipf_scanlist(fin, *passp);
5714 	return fin->fin_fr;
5715 }
5716 
5717 /*
5718  * Queue functions
5719  * ===============
5720  * These functions manage objects on queues for efficient timeouts.  There
5721  * are a number of system defined queues as well as user defined timeouts.
5722  * It is expected that a lock is held in the domain in which the queue
5723  * belongs (i.e. either state or NAT) when calling any of these functions
5724  * that prevents ipf_freetimeoutqueue() from being called at the same time
5725  * as any other.
5726  */
5727 
5728 
5729 /* ------------------------------------------------------------------------ */
5730 /* Function:    ipf_addtimeoutqueue                                         */
5731 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5732 /*                               timeout queue with given interval.         */
5733 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5734 /*                           of interface queues.                           */
5735 /*              seconds(I) - timeout value in seconds for this queue.       */
5736 /*                                                                          */
5737 /* This routine first looks for a timeout queue that matches the interval   */
5738 /* being requested.  If it finds one, increments the reference counter and  */
5739 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5740 /* inserts it at the top of the list.                                       */
5741 /*                                                                          */
5742 /* Locking.                                                                 */
5743 /* It is assumed that the caller of this function has an appropriate lock   */
5744 /* held (exclusively) in the domain that encompases 'parent'.               */
5745 /* ------------------------------------------------------------------------ */
5746 ipftq_t *
ipf_addtimeoutqueue(softc,parent,seconds)5747 ipf_addtimeoutqueue(softc, parent, seconds)
5748 	ipf_main_softc_t *softc;
5749 	ipftq_t **parent;
5750 	u_int seconds;
5751 {
5752 	ipftq_t *ifq;
5753 	u_int period;
5754 
5755 	period = seconds * IPF_HZ_DIVIDE;
5756 
5757 	MUTEX_ENTER(&softc->ipf_timeoutlock);
5758 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5759 		if (ifq->ifq_ttl == period) {
5760 			/*
5761 			 * Reset the delete flag, if set, so the structure
5762 			 * gets reused rather than freed and reallocated.
5763 			 */
5764 			MUTEX_ENTER(&ifq->ifq_lock);
5765 			ifq->ifq_flags &= ~IFQF_DELETE;
5766 			ifq->ifq_ref++;
5767 			MUTEX_EXIT(&ifq->ifq_lock);
5768 			MUTEX_EXIT(&softc->ipf_timeoutlock);
5769 
5770 			return ifq;
5771 		}
5772 	}
5773 
5774 	KMALLOC(ifq, ipftq_t *);
5775 	if (ifq != NULL) {
5776 		MUTEX_NUKE(&ifq->ifq_lock);
5777 		IPFTQ_INIT(ifq, period, "ipftq mutex");
5778 		ifq->ifq_next = *parent;
5779 		ifq->ifq_pnext = parent;
5780 		ifq->ifq_flags = IFQF_USER;
5781 		ifq->ifq_ref++;
5782 		*parent = ifq;
5783 		softc->ipf_userifqs++;
5784 	}
5785 	MUTEX_EXIT(&softc->ipf_timeoutlock);
5786 	return ifq;
5787 }
5788 
5789 
5790 /* ------------------------------------------------------------------------ */
5791 /* Function:    ipf_deletetimeoutqueue                                      */
5792 /* Returns:     int    - new reference count value of the timeout queue     */
5793 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5794 /* Locks:       ifq->ifq_lock                                               */
5795 /*                                                                          */
5796 /* This routine must be called when we're discarding a pointer to a timeout */
5797 /* queue object, taking care of the reference counter.                      */
5798 /*                                                                          */
5799 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5800 /* check the list of user defined timeout queues and call the free function */
5801 /* below (currently commented out) to stop memory leaking.  It is done this */
5802 /* way because the locking may not be sufficient to safely do a free when   */
5803 /* this function is called.                                                 */
5804 /* ------------------------------------------------------------------------ */
5805 int
ipf_deletetimeoutqueue(ifq)5806 ipf_deletetimeoutqueue(ifq)
5807 	ipftq_t *ifq;
5808 {
5809 
5810 	ifq->ifq_ref--;
5811 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5812 		ifq->ifq_flags |= IFQF_DELETE;
5813 	}
5814 
5815 	return ifq->ifq_ref;
5816 }
5817 
5818 
5819 /* ------------------------------------------------------------------------ */
5820 /* Function:    ipf_freetimeoutqueue                                        */
5821 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5822 /* Returns:     Nil                                                         */
5823 /*                                                                          */
5824 /* Locking:                                                                 */
5825 /* It is assumed that the caller of this function has an appropriate lock   */
5826 /* held (exclusively) in the domain that encompases the callers "domain".   */
5827 /* The ifq_lock for this structure should not be held.                      */
5828 /*                                                                          */
5829 /* Remove a user defined timeout queue from the list of queues it is in and */
5830 /* tidy up after this is done.                                              */
5831 /* ------------------------------------------------------------------------ */
5832 void
ipf_freetimeoutqueue(softc,ifq)5833 ipf_freetimeoutqueue(softc, ifq)
5834 	ipf_main_softc_t *softc;
5835 	ipftq_t *ifq;
5836 {
5837 
5838 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5839 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5840 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5841 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5842 		       ifq->ifq_ref);
5843 		return;
5844 	}
5845 
5846 	/*
5847 	 * Remove from its position in the list.
5848 	 */
5849 	*ifq->ifq_pnext = ifq->ifq_next;
5850 	if (ifq->ifq_next != NULL)
5851 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5852 	ifq->ifq_next = NULL;
5853 	ifq->ifq_pnext = NULL;
5854 
5855 	MUTEX_DESTROY(&ifq->ifq_lock);
5856 	ATOMIC_DEC(softc->ipf_userifqs);
5857 	KFREE(ifq);
5858 }
5859 
5860 
5861 /* ------------------------------------------------------------------------ */
5862 /* Function:    ipf_deletequeueentry                                        */
5863 /* Returns:     Nil                                                         */
5864 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5865 /*                                                                          */
5866 /* Remove a tail queue entry from its queue and make it an orphan.          */
5867 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5868 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5869 /* the correct lock(s) may not be held that would make it safe to do so.    */
5870 /* ------------------------------------------------------------------------ */
5871 void
ipf_deletequeueentry(tqe)5872 ipf_deletequeueentry(tqe)
5873 	ipftqent_t *tqe;
5874 {
5875 	ipftq_t *ifq;
5876 
5877 	ifq = tqe->tqe_ifq;
5878 
5879 	MUTEX_ENTER(&ifq->ifq_lock);
5880 
5881 	if (tqe->tqe_pnext != NULL) {
5882 		*tqe->tqe_pnext = tqe->tqe_next;
5883 		if (tqe->tqe_next != NULL)
5884 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5885 		else    /* we must be the tail anyway */
5886 			ifq->ifq_tail = tqe->tqe_pnext;
5887 
5888 		tqe->tqe_pnext = NULL;
5889 		tqe->tqe_ifq = NULL;
5890 	}
5891 
5892 	(void) ipf_deletetimeoutqueue(ifq);
5893 	ASSERT(ifq->ifq_ref > 0);
5894 
5895 	MUTEX_EXIT(&ifq->ifq_lock);
5896 }
5897 
5898 
5899 /* ------------------------------------------------------------------------ */
5900 /* Function:    ipf_queuefront                                              */
5901 /* Returns:     Nil                                                         */
5902 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5903 /*                                                                          */
5904 /* Move a queue entry to the front of the queue, if it isn't already there. */
5905 /* ------------------------------------------------------------------------ */
5906 void
ipf_queuefront(tqe)5907 ipf_queuefront(tqe)
5908 	ipftqent_t *tqe;
5909 {
5910 	ipftq_t *ifq;
5911 
5912 	ifq = tqe->tqe_ifq;
5913 	if (ifq == NULL)
5914 		return;
5915 
5916 	MUTEX_ENTER(&ifq->ifq_lock);
5917 	if (ifq->ifq_head != tqe) {
5918 		*tqe->tqe_pnext = tqe->tqe_next;
5919 		if (tqe->tqe_next)
5920 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5921 		else
5922 			ifq->ifq_tail = tqe->tqe_pnext;
5923 
5924 		tqe->tqe_next = ifq->ifq_head;
5925 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5926 		ifq->ifq_head = tqe;
5927 		tqe->tqe_pnext = &ifq->ifq_head;
5928 	}
5929 	MUTEX_EXIT(&ifq->ifq_lock);
5930 }
5931 
5932 
5933 /* ------------------------------------------------------------------------ */
5934 /* Function:    ipf_queueback                                               */
5935 /* Returns:     Nil                                                         */
5936 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5937 /*              tqe(I)   - pointer to timeout queue entry                   */
5938 /*                                                                          */
5939 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5940 /* We use use ticks to calculate the expiration and mark for when we last   */
5941 /* touched the structure.                                                   */
5942 /* ------------------------------------------------------------------------ */
5943 void
ipf_queueback(ticks,tqe)5944 ipf_queueback(ticks, tqe)
5945 	u_long ticks;
5946 	ipftqent_t *tqe;
5947 {
5948 	ipftq_t *ifq;
5949 
5950 	ifq = tqe->tqe_ifq;
5951 	if (ifq == NULL)
5952 		return;
5953 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5954 	tqe->tqe_touched = ticks;
5955 
5956 	MUTEX_ENTER(&ifq->ifq_lock);
5957 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5958 		/*
5959 		 * Remove from list
5960 		 */
5961 		*tqe->tqe_pnext = tqe->tqe_next;
5962 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5963 
5964 		/*
5965 		 * Make it the last entry.
5966 		 */
5967 		tqe->tqe_next = NULL;
5968 		tqe->tqe_pnext = ifq->ifq_tail;
5969 		*ifq->ifq_tail = tqe;
5970 		ifq->ifq_tail = &tqe->tqe_next;
5971 	}
5972 	MUTEX_EXIT(&ifq->ifq_lock);
5973 }
5974 
5975 
5976 /* ------------------------------------------------------------------------ */
5977 /* Function:    ipf_queueappend                                             */
5978 /* Returns:     Nil                                                         */
5979 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5980 /*              tqe(I)    - pointer to timeout queue entry                  */
5981 /*              ifq(I)    - pointer to timeout queue                        */
5982 /*              parent(I) - owing object pointer                            */
5983 /*                                                                          */
5984 /* Add a new item to this queue and put it on the very end.                 */
5985 /* We use use ticks to calculate the expiration and mark for when we last   */
5986 /* touched the structure.                                                   */
5987 /* ------------------------------------------------------------------------ */
5988 void
ipf_queueappend(ticks,tqe,ifq,parent)5989 ipf_queueappend(ticks, tqe, ifq, parent)
5990 	u_long ticks;
5991 	ipftqent_t *tqe;
5992 	ipftq_t *ifq;
5993 	void *parent;
5994 {
5995 
5996 	MUTEX_ENTER(&ifq->ifq_lock);
5997 	tqe->tqe_parent = parent;
5998 	tqe->tqe_pnext = ifq->ifq_tail;
5999 	*ifq->ifq_tail = tqe;
6000 	ifq->ifq_tail = &tqe->tqe_next;
6001 	tqe->tqe_next = NULL;
6002 	tqe->tqe_ifq = ifq;
6003 	tqe->tqe_die = ticks + ifq->ifq_ttl;
6004 	tqe->tqe_touched = ticks;
6005 	ifq->ifq_ref++;
6006 	MUTEX_EXIT(&ifq->ifq_lock);
6007 }
6008 
6009 
6010 /* ------------------------------------------------------------------------ */
6011 /* Function:    ipf_movequeue                                               */
6012 /* Returns:     Nil                                                         */
6013 /* Parameters:  tq(I)   - pointer to timeout queue information              */
6014 /*              oifp(I) - old timeout queue entry was on                    */
6015 /*              nifp(I) - new timeout queue to put entry on                 */
6016 /*                                                                          */
6017 /* Move a queue entry from one timeout queue to another timeout queue.      */
6018 /* If it notices that the current entry is already last and does not need   */
6019 /* to move queue, the return.                                               */
6020 /* ------------------------------------------------------------------------ */
6021 void
ipf_movequeue(ticks,tqe,oifq,nifq)6022 ipf_movequeue(ticks, tqe, oifq, nifq)
6023 	u_long ticks;
6024 	ipftqent_t *tqe;
6025 	ipftq_t *oifq, *nifq;
6026 {
6027 
6028 	/*
6029 	 * If the queue hasn't changed and we last touched this entry at the
6030 	 * same ipf time, then we're not going to achieve anything by either
6031 	 * changing the ttl or moving it on the queue.
6032 	 */
6033 	if (oifq == nifq && tqe->tqe_touched == ticks)
6034 		return;
6035 
6036 	/*
6037 	 * For any of this to be outside the lock, there is a risk that two
6038 	 * packets entering simultaneously, with one changing to a different
6039 	 * queue and one not, could end up with things in a bizarre state.
6040 	 */
6041 	MUTEX_ENTER(&oifq->ifq_lock);
6042 
6043 	tqe->tqe_touched = ticks;
6044 	tqe->tqe_die = ticks + nifq->ifq_ttl;
6045 	/*
6046 	 * Is the operation here going to be a no-op ?
6047 	 */
6048 	if (oifq == nifq) {
6049 		if ((tqe->tqe_next == NULL) ||
6050 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6051 			MUTEX_EXIT(&oifq->ifq_lock);
6052 			return;
6053 		}
6054 	}
6055 
6056 	/*
6057 	 * Remove from the old queue
6058 	 */
6059 	*tqe->tqe_pnext = tqe->tqe_next;
6060 	if (tqe->tqe_next)
6061 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6062 	else
6063 		oifq->ifq_tail = tqe->tqe_pnext;
6064 	tqe->tqe_next = NULL;
6065 
6066 	/*
6067 	 * If we're moving from one queue to another, release the
6068 	 * lock on the old queue and get a lock on the new queue.
6069 	 * For user defined queues, if we're moving off it, call
6070 	 * delete in case it can now be freed.
6071 	 */
6072 	if (oifq != nifq) {
6073 		tqe->tqe_ifq = NULL;
6074 
6075 		(void) ipf_deletetimeoutqueue(oifq);
6076 
6077 		MUTEX_EXIT(&oifq->ifq_lock);
6078 
6079 		MUTEX_ENTER(&nifq->ifq_lock);
6080 
6081 		tqe->tqe_ifq = nifq;
6082 		nifq->ifq_ref++;
6083 	}
6084 
6085 	/*
6086 	 * Add to the bottom of the new queue
6087 	 */
6088 	tqe->tqe_pnext = nifq->ifq_tail;
6089 	*nifq->ifq_tail = tqe;
6090 	nifq->ifq_tail = &tqe->tqe_next;
6091 	MUTEX_EXIT(&nifq->ifq_lock);
6092 }
6093 
6094 
6095 /* ------------------------------------------------------------------------ */
6096 /* Function:    ipf_updateipid                                              */
6097 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6098 /* Parameters:  fin(I) - pointer to packet information                      */
6099 /*                                                                          */
6100 /* When we are doing NAT, change the IP of every packet to represent a      */
6101 /* single sequence of packets coming from the host, hiding any host         */
6102 /* specific sequencing that might otherwise be revealed.  If the packet is  */
6103 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6104 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
6105 /* has no match in the cache, return an error.                              */
6106 /* ------------------------------------------------------------------------ */
6107 static int
ipf_updateipid(fin)6108 ipf_updateipid(fin)
6109 	fr_info_t *fin;
6110 {
6111 	u_short id, ido, sums;
6112 	u_32_t sumd, sum;
6113 	ip_t *ip;
6114 
6115 	ip = fin->fin_ip;
6116 	ido = ntohs(ip->ip_id);
6117 	if (fin->fin_off != 0) {
6118 		sum = ipf_frag_ipidknown(fin);
6119 		if (sum == 0xffffffff)
6120 			return -1;
6121 		sum &= 0xffff;
6122 		id = (u_short)sum;
6123 		ip->ip_id = htons(id);
6124 	} else {
6125 		ip_fillid(ip);
6126 		id = ntohs(ip->ip_id);
6127 		if ((fin->fin_flx & FI_FRAG) != 0)
6128 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
6129 	}
6130 
6131 	if (id == ido)
6132 		return 0;
6133 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
6134 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
6135 	sum += sumd;
6136 	sum = (sum >> 16) + (sum & 0xffff);
6137 	sum = (sum >> 16) + (sum & 0xffff);
6138 	sums = ~(u_short)sum;
6139 	ip->ip_sum = htons(sums);
6140 	return 0;
6141 }
6142 
6143 
6144 #ifdef	NEED_FRGETIFNAME
6145 /* ------------------------------------------------------------------------ */
6146 /* Function:    ipf_getifname                                               */
6147 /* Returns:     char *    - pointer to interface name                       */
6148 /* Parameters:  ifp(I)    - pointer to network interface                    */
6149 /*              buffer(O) - pointer to where to store interface name        */
6150 /*                                                                          */
6151 /* Constructs an interface name in the buffer passed.  The buffer passed is */
6152 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6153 /* as a NULL pointer then return a pointer to a static array.               */
6154 /* ------------------------------------------------------------------------ */
6155 char *
ipf_getifname(ifp,buffer)6156 ipf_getifname(ifp, buffer)
6157 	struct ifnet *ifp;
6158 	char *buffer;
6159 {
6160 	static char namebuf[LIFNAMSIZ];
6161 # if defined(MENTAT) || defined(__FreeBSD__)
6162 	int unit, space;
6163 	char temp[20];
6164 	char *s;
6165 # endif
6166 
6167 	if (buffer == NULL)
6168 		buffer = namebuf;
6169 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6170 	buffer[LIFNAMSIZ - 1] = '\0';
6171 # if defined(MENTAT) || defined(__FreeBSD__)
6172 	for (s = buffer; *s; s++)
6173 		;
6174 	unit = ifp->if_unit;
6175 	space = LIFNAMSIZ - (s - buffer);
6176 	if ((space > 0) && (unit >= 0)) {
6177 #  if defined(SNPRINTF) && defined(_KERNEL)
6178 		SNPRINTF(temp, sizeof(temp), "%d", unit);
6179 #  else
6180 		(void) sprintf(temp, "%d", unit);
6181 #  endif
6182 		(void) strncpy(s, temp, space);
6183 	}
6184 # endif
6185 	return buffer;
6186 }
6187 #endif
6188 
6189 
6190 /* ------------------------------------------------------------------------ */
6191 /* Function:    ipf_ioctlswitch                                             */
6192 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6193 /* Parameters:  unit(I) - device unit opened                                */
6194 /*              data(I) - pointer to ioctl data                             */
6195 /*              cmd(I)  - ioctl command                                     */
6196 /*              mode(I) - mode value                                        */
6197 /*              uid(I)  - uid making the ioctl call                         */
6198 /*              ctx(I)  - pointer to context data                           */
6199 /*                                                                          */
6200 /* Based on the value of unit, call the appropriate ioctl handler or return */
6201 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6202 /* for the device in order to execute the ioctl.  A special case is made    */
6203 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6204 /* The context data pointer is passed through as this is used as the key    */
6205 /* for locating a matching token for continued access for walking lists,    */
6206 /* etc.                                                                     */
6207 /* ------------------------------------------------------------------------ */
6208 int
ipf_ioctlswitch(softc,unit,data,cmd,mode,uid,ctx)6209 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6210 	ipf_main_softc_t *softc;
6211 	int unit, mode, uid;
6212 	ioctlcmd_t cmd;
6213 	void *data, *ctx;
6214 {
6215 	int error = 0;
6216 
6217 	switch (cmd)
6218 	{
6219 	case SIOCIPFINTERROR :
6220 		error = BCOPYOUT(&softc->ipf_interror, data,
6221 				 sizeof(softc->ipf_interror));
6222 		if (error != 0) {
6223 			IPFERROR(40);
6224 			error = EFAULT;
6225 		}
6226 		return error;
6227 	default :
6228 		break;
6229 	}
6230 
6231 	switch (unit)
6232 	{
6233 	case IPL_LOGIPF :
6234 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6235 		break;
6236 	case IPL_LOGNAT :
6237 		if (softc->ipf_running > 0) {
6238 			error = ipf_nat_ioctl(softc, data, cmd, mode,
6239 					      uid, ctx);
6240 		} else {
6241 			IPFERROR(42);
6242 			error = EIO;
6243 		}
6244 		break;
6245 	case IPL_LOGSTATE :
6246 		if (softc->ipf_running > 0) {
6247 			error = ipf_state_ioctl(softc, data, cmd, mode,
6248 						uid, ctx);
6249 		} else {
6250 			IPFERROR(43);
6251 			error = EIO;
6252 		}
6253 		break;
6254 	case IPL_LOGAUTH :
6255 		if (softc->ipf_running > 0) {
6256 			error = ipf_auth_ioctl(softc, data, cmd, mode,
6257 					       uid, ctx);
6258 		} else {
6259 			IPFERROR(44);
6260 			error = EIO;
6261 		}
6262 		break;
6263 	case IPL_LOGSYNC :
6264 		if (softc->ipf_running > 0) {
6265 			error = ipf_sync_ioctl(softc, data, cmd, mode,
6266 					       uid, ctx);
6267 		} else {
6268 			error = EIO;
6269 			IPFERROR(45);
6270 		}
6271 		break;
6272 	case IPL_LOGSCAN :
6273 #ifdef IPFILTER_SCAN
6274 		if (softc->ipf_running > 0)
6275 			error = ipf_scan_ioctl(softc, data, cmd, mode,
6276 					       uid, ctx);
6277 		else
6278 #endif
6279 		{
6280 			error = EIO;
6281 			IPFERROR(46);
6282 		}
6283 		break;
6284 	case IPL_LOGLOOKUP :
6285 		if (softc->ipf_running > 0) {
6286 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6287 						 uid, ctx);
6288 		} else {
6289 			error = EIO;
6290 			IPFERROR(47);
6291 		}
6292 		break;
6293 	default :
6294 		IPFERROR(48);
6295 		error = EIO;
6296 		break;
6297 	}
6298 
6299 	return error;
6300 }
6301 
6302 
6303 /*
6304  * This array defines the expected size of objects coming into the kernel
6305  * for the various recognised object types. The first column is flags (see
6306  * below), 2nd column is current size, 3rd column is the version number of
6307  * when the current size became current.
6308  * Flags:
6309  * 1 = minimum size, not absolute size
6310  */
6311 static const int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6312 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6313 	{ 1,	sizeof(struct friostat),	5010000 },
6314 	{ 0,	sizeof(struct fr_info),		5010000 },
6315 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6316 	{ 0,	sizeof(struct ipfrstat),	5010000 },
6317 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6318 	{ 0,	sizeof(struct natstat),		5010000 },
6319 	{ 0,	sizeof(struct ipstate_save),	5010000 },
6320 	{ 1,	sizeof(struct nat_save),	5010000 },
6321 	{ 0,	sizeof(struct natlookup),	5010000 },
6322 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6323 	{ 0,	sizeof(struct ips_stat),	5010000 },
6324 	{ 0,	sizeof(struct frauth),		5010000 },
6325 	{ 0,	sizeof(struct ipftune),		4010100 },
6326 	{ 0,	sizeof(struct nat),		5010000 },
6327 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6328 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6329 	{ 0,	sizeof(struct ipftable),	4011400 },
6330 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6331 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6332 	{ 1,	0,				0	}, /* IPFEXPR */
6333 	{ 0,	0,				0	}, /* PROXYCTL */
6334 	{ 0,	sizeof (struct fripf),		5010000	}
6335 };
6336 
6337 
6338 /* ------------------------------------------------------------------------ */
6339 /* Function:    ipf_inobj                                                   */
6340 /* Returns:     int     - 0 = success, else failure                         */
6341 /* Parameters:  softc(I) - soft context pointerto work with                 */
6342 /*              data(I)  - pointer to ioctl data                            */
6343 /*              objp(O)  - where to store ipfobj structure                  */
6344 /*              ptr(I)   - pointer to data to copy out                      */
6345 /*              type(I)  - type of structure being moved                    */
6346 /*                                                                          */
6347 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6348 /* add things to check for version numbers, sizes, etc, to make it backward */
6349 /* compatible at the ABI for user land.                                     */
6350 /* If objp is not NULL then we assume that the caller wants to see what is  */
6351 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6352 /* the caller what version of ipfilter the ioctl program was written to.    */
6353 /* ------------------------------------------------------------------------ */
6354 int
ipf_inobj(softc,data,objp,ptr,type)6355 ipf_inobj(softc, data, objp, ptr, type)
6356 	ipf_main_softc_t *softc;
6357 	void *data;
6358 	ipfobj_t *objp;
6359 	void *ptr;
6360 	int type;
6361 {
6362 	ipfobj_t obj;
6363 	int error;
6364 	int size;
6365 
6366 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6367 		IPFERROR(49);
6368 		return EINVAL;
6369 	}
6370 
6371 	if (objp == NULL)
6372 		objp = &obj;
6373 	error = BCOPYIN(data, objp, sizeof(*objp));
6374 	if (error != 0) {
6375 		IPFERROR(124);
6376 		return EFAULT;
6377 	}
6378 
6379 	if (objp->ipfo_type != type) {
6380 		IPFERROR(50);
6381 		return EINVAL;
6382 	}
6383 
6384 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6385 		if ((ipf_objbytes[type][0] & 1) != 0) {
6386 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6387 				IPFERROR(51);
6388 				return EINVAL;
6389 			}
6390 			size =  ipf_objbytes[type][1];
6391 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6392 			size =  objp->ipfo_size;
6393 		} else {
6394 			IPFERROR(52);
6395 			return EINVAL;
6396 		}
6397 		error = COPYIN(objp->ipfo_ptr, ptr, size);
6398 		if (error != 0) {
6399 			IPFERROR(55);
6400 			error = EFAULT;
6401 		}
6402 	} else {
6403 #ifdef  IPFILTER_COMPAT
6404 		error = ipf_in_compat(softc, objp, ptr, 0);
6405 #else
6406 		IPFERROR(54);
6407 		error = EINVAL;
6408 #endif
6409 	}
6410 	return error;
6411 }
6412 
6413 
6414 /* ------------------------------------------------------------------------ */
6415 /* Function:    ipf_inobjsz                                                 */
6416 /* Returns:     int     - 0 = success, else failure                         */
6417 /* Parameters:  softc(I) - soft context pointerto work with                 */
6418 /*              data(I)  - pointer to ioctl data                            */
6419 /*              ptr(I)   - pointer to store real data in                    */
6420 /*              type(I)  - type of structure being moved                    */
6421 /*              sz(I)    - size of data to copy                             */
6422 /*                                                                          */
6423 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6424 /* but it must not be smaller than the size defined for the type and the    */
6425 /* type must allow for varied sized objects.  The extra requirement here is */
6426 /* that sz must match the size of the object being passed in - this is not  */
6427 /* not possible nor required in ipf_inobj().                                */
6428 /* ------------------------------------------------------------------------ */
6429 int
ipf_inobjsz(softc,data,ptr,type,sz)6430 ipf_inobjsz(softc, data, ptr, type, sz)
6431 	ipf_main_softc_t *softc;
6432 	void *data;
6433 	void *ptr;
6434 	int type, sz;
6435 {
6436 	ipfobj_t obj;
6437 	int error;
6438 
6439 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6440 		IPFERROR(56);
6441 		return EINVAL;
6442 	}
6443 
6444 	error = BCOPYIN(data, &obj, sizeof(obj));
6445 	if (error != 0) {
6446 		IPFERROR(125);
6447 		return EFAULT;
6448 	}
6449 
6450 	if (obj.ipfo_type != type) {
6451 		IPFERROR(58);
6452 		return EINVAL;
6453 	}
6454 
6455 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6456 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6457 		    (sz < ipf_objbytes[type][1])) {
6458 			IPFERROR(57);
6459 			return EINVAL;
6460 		}
6461 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6462 		if (error != 0) {
6463 			IPFERROR(61);
6464 			error = EFAULT;
6465 		}
6466 	} else {
6467 #ifdef	IPFILTER_COMPAT
6468 		error = ipf_in_compat(softc, &obj, ptr, sz);
6469 #else
6470 		IPFERROR(60);
6471 		error = EINVAL;
6472 #endif
6473 	}
6474 	return error;
6475 }
6476 
6477 
6478 /* ------------------------------------------------------------------------ */
6479 /* Function:    ipf_outobjsz                                                */
6480 /* Returns:     int     - 0 = success, else failure                         */
6481 /* Parameters:  data(I) - pointer to ioctl data                             */
6482 /*              ptr(I)  - pointer to store real data in                     */
6483 /*              type(I) - type of structure being moved                     */
6484 /*              sz(I)   - size of data to copy                              */
6485 /*                                                                          */
6486 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6487 /* but it must not be smaller than the size defined for the type and the    */
6488 /* type must allow for varied sized objects.  The extra requirement here is */
6489 /* that sz must match the size of the object being passed in - this is not  */
6490 /* not possible nor required in ipf_outobj().                               */
6491 /* ------------------------------------------------------------------------ */
6492 int
ipf_outobjsz(softc,data,ptr,type,sz)6493 ipf_outobjsz(softc, data, ptr, type, sz)
6494 	ipf_main_softc_t *softc;
6495 	void *data;
6496 	void *ptr;
6497 	int type, sz;
6498 {
6499 	ipfobj_t obj;
6500 	int error;
6501 
6502 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6503 		IPFERROR(62);
6504 		return EINVAL;
6505 	}
6506 
6507 	error = BCOPYIN(data, &obj, sizeof(obj));
6508 	if (error != 0) {
6509 		IPFERROR(127);
6510 		return EFAULT;
6511 	}
6512 
6513 	if (obj.ipfo_type != type) {
6514 		IPFERROR(63);
6515 		return EINVAL;
6516 	}
6517 
6518 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6519 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6520 		    (sz < ipf_objbytes[type][1])) {
6521 			IPFERROR(146);
6522 			return EINVAL;
6523 		}
6524 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6525 		if (error != 0) {
6526 			IPFERROR(66);
6527 			error = EFAULT;
6528 		}
6529 	} else {
6530 #ifdef	IPFILTER_COMPAT
6531 		error = ipf_out_compat(softc, &obj, ptr);
6532 #else
6533 		IPFERROR(65);
6534 		error = EINVAL;
6535 #endif
6536 	}
6537 	return error;
6538 }
6539 
6540 
6541 /* ------------------------------------------------------------------------ */
6542 /* Function:    ipf_outobj                                                  */
6543 /* Returns:     int     - 0 = success, else failure                         */
6544 /* Parameters:  data(I) - pointer to ioctl data                             */
6545 /*              ptr(I)  - pointer to store real data in                     */
6546 /*              type(I) - type of structure being moved                     */
6547 /*                                                                          */
6548 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6549 /* future, we add things to check for version numbers, sizes, etc, to make  */
6550 /* it backward  compatible at the ABI for user land.                        */
6551 /* ------------------------------------------------------------------------ */
6552 int
ipf_outobj(softc,data,ptr,type)6553 ipf_outobj(softc, data, ptr, type)
6554 	ipf_main_softc_t *softc;
6555 	void *data;
6556 	void *ptr;
6557 	int type;
6558 {
6559 	ipfobj_t obj;
6560 	int error;
6561 
6562 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6563 		IPFERROR(67);
6564 		return EINVAL;
6565 	}
6566 
6567 	error = BCOPYIN(data, &obj, sizeof(obj));
6568 	if (error != 0) {
6569 		IPFERROR(126);
6570 		return EFAULT;
6571 	}
6572 
6573 	if (obj.ipfo_type != type) {
6574 		IPFERROR(68);
6575 		return EINVAL;
6576 	}
6577 
6578 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6579 		if ((ipf_objbytes[type][0] & 1) != 0) {
6580 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6581 				IPFERROR(69);
6582 				return EINVAL;
6583 			}
6584 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6585 			IPFERROR(70);
6586 			return EINVAL;
6587 		}
6588 
6589 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6590 		if (error != 0) {
6591 			IPFERROR(73);
6592 			error = EFAULT;
6593 		}
6594 	} else {
6595 #ifdef	IPFILTER_COMPAT
6596 		error = ipf_out_compat(softc, &obj, ptr);
6597 #else
6598 		IPFERROR(72);
6599 		error = EINVAL;
6600 #endif
6601 	}
6602 	return error;
6603 }
6604 
6605 
6606 /* ------------------------------------------------------------------------ */
6607 /* Function:    ipf_outobjk                                                 */
6608 /* Returns:     int     - 0 = success, else failure                         */
6609 /* Parameters:  obj(I)  - pointer to data description structure             */
6610 /*              ptr(I)  - pointer to kernel data to copy out                */
6611 /*                                                                          */
6612 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6613 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6614 /* already populated with information and now we just need to use it.       */
6615 /* There is no need for this function to have a "type" parameter as there   */
6616 /* is no point in validating information that comes from the kernel with    */
6617 /* itself.                                                                  */
6618 /* ------------------------------------------------------------------------ */
6619 int
ipf_outobjk(softc,obj,ptr)6620 ipf_outobjk(softc, obj, ptr)
6621 	ipf_main_softc_t *softc;
6622 	ipfobj_t *obj;
6623 	void *ptr;
6624 {
6625 	int type = obj->ipfo_type;
6626 	int error;
6627 
6628 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6629 		IPFERROR(147);
6630 		return EINVAL;
6631 	}
6632 
6633 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6634 		if ((ipf_objbytes[type][0] & 1) != 0) {
6635 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6636 				IPFERROR(148);
6637 				return EINVAL;
6638 			}
6639 
6640 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6641 			IPFERROR(149);
6642 			return EINVAL;
6643 		}
6644 
6645 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6646 		if (error != 0) {
6647 			IPFERROR(150);
6648 			error = EFAULT;
6649 		}
6650 	} else {
6651 #ifdef  IPFILTER_COMPAT
6652 		error = ipf_out_compat(softc, obj, ptr);
6653 #else
6654 		IPFERROR(151);
6655 		error = EINVAL;
6656 #endif
6657 	}
6658 	return error;
6659 }
6660 
6661 
6662 /* ------------------------------------------------------------------------ */
6663 /* Function:    ipf_checkl4sum                                              */
6664 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6665 /* Parameters:  fin(I) - pointer to packet information                      */
6666 /*                                                                          */
6667 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6668 /* not possible, return without indicating a failure or success but in a    */
6669 /* way that is ditinguishable. This function should only be called by the   */
6670 /* ipf_checkv6sum() for each platform.                                      */
6671 /* ------------------------------------------------------------------------ */
6672 INLINE int
ipf_checkl4sum(fin)6673 ipf_checkl4sum(fin)
6674 	fr_info_t *fin;
6675 {
6676 	u_short sum, hdrsum, *csump;
6677 	udphdr_t *udp;
6678 	int dosum;
6679 
6680 	/*
6681 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6682 	 * isn't already considered "bad", then validate the checksum.  If
6683 	 * this check fails then considered the packet to be "bad".
6684 	 */
6685 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6686 		return 1;
6687 
6688 	DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6689 	if (fin->fin_out == 1) {
6690 		fin->fin_cksum = FI_CK_SUMOK;
6691 		return 0;
6692 	}
6693 
6694 	csump = NULL;
6695 	hdrsum = 0;
6696 	dosum = 0;
6697 	sum = 0;
6698 
6699 	switch (fin->fin_p)
6700 	{
6701 	case IPPROTO_TCP :
6702 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6703 		dosum = 1;
6704 		break;
6705 
6706 	case IPPROTO_UDP :
6707 		udp = fin->fin_dp;
6708 		if (udp->uh_sum != 0) {
6709 			csump = &udp->uh_sum;
6710 			dosum = 1;
6711 		}
6712 		break;
6713 
6714 #ifdef USE_INET6
6715 	case IPPROTO_ICMPV6 :
6716 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6717 		dosum = 1;
6718 		break;
6719 #endif
6720 
6721 	case IPPROTO_ICMP :
6722 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6723 		dosum = 1;
6724 		break;
6725 
6726 	default :
6727 		return 1;
6728 		/*NOTREACHED*/
6729 	}
6730 
6731 	if (csump != NULL) {
6732 		hdrsum = *csump;
6733 		if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6734 			hdrsum = 0x0000;
6735 	}
6736 
6737 	if (dosum) {
6738 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6739 	}
6740 #if !defined(_KERNEL)
6741 	if (sum == hdrsum) {
6742 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6743 	} else {
6744 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6745 	}
6746 #endif
6747 	DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6748 #ifdef USE_INET6
6749 	if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6750 #else
6751 	if (hdrsum == sum) {
6752 #endif
6753 		fin->fin_cksum = FI_CK_SUMOK;
6754 		return 0;
6755 	}
6756 	fin->fin_cksum = FI_CK_BAD;
6757 	return -1;
6758 }
6759 
6760 
6761 /* ------------------------------------------------------------------------ */
6762 /* Function:    ipf_ifpfillv4addr                                           */
6763 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6764 /* Parameters:  atype(I)   - type of network address update to perform      */
6765 /*              sin(I)     - pointer to source of address information       */
6766 /*              mask(I)    - pointer to source of netmask information       */
6767 /*              inp(I)     - pointer to destination address store           */
6768 /*              inpmask(I) - pointer to destination netmask store           */
6769 /*                                                                          */
6770 /* Given a type of network address update (atype) to perform, copy          */
6771 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6772 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6773 /* which case the operation fails.  For all values of atype other than      */
6774 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6775 /* value.                                                                   */
6776 /* ------------------------------------------------------------------------ */
6777 int
ipf_ifpfillv4addr(atype,sin,mask,inp,inpmask)6778 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6779 	int atype;
6780 	struct sockaddr_in *sin, *mask;
6781 	struct in_addr *inp, *inpmask;
6782 {
6783 	if (inpmask != NULL && atype != FRI_NETMASKED)
6784 		inpmask->s_addr = 0xffffffff;
6785 
6786 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6787 		if (atype == FRI_NETMASKED) {
6788 			if (inpmask == NULL)
6789 				return -1;
6790 			inpmask->s_addr = mask->sin_addr.s_addr;
6791 		}
6792 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6793 	} else {
6794 		inp->s_addr = sin->sin_addr.s_addr;
6795 	}
6796 	return 0;
6797 }
6798 
6799 
6800 #ifdef	USE_INET6
6801 /* ------------------------------------------------------------------------ */
6802 /* Function:    ipf_ifpfillv6addr                                           */
6803 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6804 /* Parameters:  atype(I)   - type of network address update to perform      */
6805 /*              sin(I)     - pointer to source of address information       */
6806 /*              mask(I)    - pointer to source of netmask information       */
6807 /*              inp(I)     - pointer to destination address store           */
6808 /*              inpmask(I) - pointer to destination netmask store           */
6809 /*                                                                          */
6810 /* Given a type of network address update (atype) to perform, copy          */
6811 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6812 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6813 /* which case the operation fails.  For all values of atype other than      */
6814 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6815 /* value.                                                                   */
6816 /* ------------------------------------------------------------------------ */
6817 int
ipf_ifpfillv6addr(atype,sin,mask,inp,inpmask)6818 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6819 	int atype;
6820 	struct sockaddr_in6 *sin, *mask;
6821 	i6addr_t *inp, *inpmask;
6822 {
6823 	i6addr_t *src, *and;
6824 
6825 	src = (i6addr_t *)&sin->sin6_addr;
6826 	and = (i6addr_t *)&mask->sin6_addr;
6827 
6828 	if (inpmask != NULL && atype != FRI_NETMASKED) {
6829 		inpmask->i6[0] = 0xffffffff;
6830 		inpmask->i6[1] = 0xffffffff;
6831 		inpmask->i6[2] = 0xffffffff;
6832 		inpmask->i6[3] = 0xffffffff;
6833 	}
6834 
6835 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6836 		if (atype == FRI_NETMASKED) {
6837 			if (inpmask == NULL)
6838 				return -1;
6839 			inpmask->i6[0] = and->i6[0];
6840 			inpmask->i6[1] = and->i6[1];
6841 			inpmask->i6[2] = and->i6[2];
6842 			inpmask->i6[3] = and->i6[3];
6843 		}
6844 
6845 		inp->i6[0] = src->i6[0] & and->i6[0];
6846 		inp->i6[1] = src->i6[1] & and->i6[1];
6847 		inp->i6[2] = src->i6[2] & and->i6[2];
6848 		inp->i6[3] = src->i6[3] & and->i6[3];
6849 	} else {
6850 		inp->i6[0] = src->i6[0];
6851 		inp->i6[1] = src->i6[1];
6852 		inp->i6[2] = src->i6[2];
6853 		inp->i6[3] = src->i6[3];
6854 	}
6855 	return 0;
6856 }
6857 #endif
6858 
6859 
6860 /* ------------------------------------------------------------------------ */
6861 /* Function:    ipf_matchtag                                                */
6862 /* Returns:     0 == mismatch, 1 == match.                                  */
6863 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6864 /*              tag2(I) - pointer to second tag to compare                  */
6865 /*                                                                          */
6866 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6867 /* considered to be a match or not match, respectively.  The tag is 16      */
6868 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6869 /* compare the ints instead, for speed. tag1 is the master of the           */
6870 /* comparison.  This function should only be called with both tag1 and tag2 */
6871 /* as non-NULL pointers.                                                    */
6872 /* ------------------------------------------------------------------------ */
6873 int
ipf_matchtag(tag1,tag2)6874 ipf_matchtag(tag1, tag2)
6875 	ipftag_t *tag1, *tag2;
6876 {
6877 	if (tag1 == tag2)
6878 		return 1;
6879 
6880 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6881 		return 1;
6882 
6883 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6884 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6885 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6886 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6887 		return 1;
6888 	return 0;
6889 }
6890 
6891 
6892 /* ------------------------------------------------------------------------ */
6893 /* Function:    ipf_coalesce                                                */
6894 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6895 /* Parameters:  fin(I) - pointer to packet information                      */
6896 /*                                                                          */
6897 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6898 /* If this call returns a failure then the buffers have also been freed.    */
6899 /* ------------------------------------------------------------------------ */
6900 int
ipf_coalesce(fin)6901 ipf_coalesce(fin)
6902 	fr_info_t *fin;
6903 {
6904 
6905 	if ((fin->fin_flx & FI_COALESCE) != 0)
6906 		return 1;
6907 
6908 	/*
6909 	 * If the mbuf pointers indicate that there is no mbuf to work with,
6910 	 * return but do not indicate success or failure.
6911 	 */
6912 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6913 		return 0;
6914 
6915 #if defined(_KERNEL)
6916 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6917 		ipf_main_softc_t *softc = fin->fin_main_soft;
6918 
6919 		DT1(frb_coalesce, fr_info_t *, fin);
6920 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6921 # ifdef MENTAT
6922 		FREE_MB_T(*fin->fin_mp);
6923 # endif
6924 		fin->fin_reason = FRB_COALESCE;
6925 		*fin->fin_mp = NULL;
6926 		fin->fin_m = NULL;
6927 		return -1;
6928 	}
6929 #else
6930 	fin = fin;	/* LINT */
6931 #endif
6932 	return 1;
6933 }
6934 
6935 
6936 /*
6937  * The following table lists all of the tunable variables that can be
6938  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6939  * in the table below is as follows:
6940  *
6941  * pointer to value, name of value, minimum, maximum, size of the value's
6942  *     container, value attribute flags
6943  *
6944  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6945  * means the value can only be written to when IPFilter is loaded but disabled.
6946  * The obvious implication is if neither of these are set then the value can be
6947  * changed at any time without harm.
6948  */
6949 
6950 
6951 /* ------------------------------------------------------------------------ */
6952 /* Function:    ipf_tune_findbycookie                                       */
6953 /* Returns:     NULL = search failed, else pointer to tune struct           */
6954 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6955 /*              next(O)   - pointer to place to store the cookie for the    */
6956 /*                          "next" tuneable, if it is desired.              */
6957 /*                                                                          */
6958 /* This function is used to walk through all of the existing tunables with  */
6959 /* successive calls.  It searches the known tunables for the one which has  */
6960 /* a matching value for "cookie" - ie its address.  When returning a match, */
6961 /* the next one to be found may be returned inside next.                    */
6962 /* ------------------------------------------------------------------------ */
6963 static ipftuneable_t *
ipf_tune_findbycookie(ptop,cookie,next)6964 ipf_tune_findbycookie(ptop, cookie, next)
6965 	ipftuneable_t **ptop;
6966 	void *cookie, **next;
6967 {
6968 	ipftuneable_t *ta, **tap;
6969 
6970 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6971 		if (ta == cookie) {
6972 			if (next != NULL) {
6973 				/*
6974 				 * If the next entry in the array has a name
6975 				 * present, then return a pointer to it for
6976 				 * where to go next, else return a pointer to
6977 				 * the dynaminc list as a key to search there
6978 				 * next.  This facilitates a weak linking of
6979 				 * the two "lists" together.
6980 				 */
6981 				if ((ta + 1)->ipft_name != NULL)
6982 					*next = ta + 1;
6983 				else
6984 					*next = ptop;
6985 			}
6986 			return ta;
6987 		}
6988 
6989 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6990 		if (tap == cookie) {
6991 			if (next != NULL)
6992 				*next = &ta->ipft_next;
6993 			return ta;
6994 		}
6995 
6996 	if (next != NULL)
6997 		*next = NULL;
6998 	return NULL;
6999 }
7000 
7001 
7002 /* ------------------------------------------------------------------------ */
7003 /* Function:    ipf_tune_findbyname                                         */
7004 /* Returns:     NULL = search failed, else pointer to tune struct           */
7005 /* Parameters:  name(I) - name of the tuneable entry to find.               */
7006 /*                                                                          */
7007 /* Search the static array of tuneables and the list of dynamic tuneables   */
7008 /* for an entry with a matching name.  If we can find one, return a pointer */
7009 /* to the matching structure.                                               */
7010 /* ------------------------------------------------------------------------ */
7011 static ipftuneable_t *
ipf_tune_findbyname(top,name)7012 ipf_tune_findbyname(top, name)
7013 	ipftuneable_t *top;
7014 	const char *name;
7015 {
7016 	ipftuneable_t *ta;
7017 
7018 	for (ta = top; ta != NULL; ta = ta->ipft_next)
7019 		if (!strcmp(ta->ipft_name, name)) {
7020 			return ta;
7021 		}
7022 
7023 	return NULL;
7024 }
7025 
7026 
7027 /* ------------------------------------------------------------------------ */
7028 /* Function:    ipf_tune_add_array                                          */
7029 /* Returns:     int - 0 == success, else failure                            */
7030 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
7031 /*                                                                          */
7032 /* Appends tune structures from the array passed in (newtune) to the end of */
7033 /* the current list of "dynamic" tuneable parameters.                       */
7034 /* If any entry to be added is already present (by name) then the operation */
7035 /* is aborted - entries that have been added are removed before returning.  */
7036 /* An entry with no name (NULL) is used as the indication that the end of   */
7037 /* the array has been reached.                                              */
7038 /* ------------------------------------------------------------------------ */
7039 int
ipf_tune_add_array(softc,newtune)7040 ipf_tune_add_array(softc, newtune)
7041 	ipf_main_softc_t *softc;
7042 	ipftuneable_t *newtune;
7043 {
7044 	ipftuneable_t *nt, *dt;
7045 	int error = 0;
7046 
7047 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
7048 		error = ipf_tune_add(softc, nt);
7049 		if (error != 0) {
7050 			for (dt = newtune; dt != nt; dt++) {
7051 				(void) ipf_tune_del(softc, dt);
7052 			}
7053 		}
7054 	}
7055 
7056 	return error;
7057 }
7058 
7059 
7060 /* ------------------------------------------------------------------------ */
7061 /* Function:    ipf_tune_array_link                                         */
7062 /* Returns:     0 == success, -1 == failure                                 */
7063 /* Parameters:  softc(I) - soft context pointerto work with                 */
7064 /*              array(I) - pointer to an array of tuneables                 */
7065 /*                                                                          */
7066 /* Given an array of tunables (array), append them to the current list of   */
7067 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7068 /* the array for being appended to the list, initialise all of the next     */
7069 /* pointers so we don't need to walk parts of it with ++ and others with    */
7070 /* next. The array is expected to have an entry with a NULL name as the     */
7071 /* terminator. Trying to add an array with no non-NULL names will return as */
7072 /* a failure.                                                               */
7073 /* ------------------------------------------------------------------------ */
7074 int
ipf_tune_array_link(softc,array)7075 ipf_tune_array_link(softc, array)
7076 	ipf_main_softc_t *softc;
7077 	ipftuneable_t *array;
7078 {
7079 	ipftuneable_t *t, **p;
7080 
7081 	t = array;
7082 	if (t->ipft_name == NULL)
7083 		return -1;
7084 
7085 	for (; t[1].ipft_name != NULL; t++)
7086 		t[0].ipft_next = &t[1];
7087 	t->ipft_next = NULL;
7088 
7089 	/*
7090 	 * Since a pointer to the last entry isn't kept, we need to find it
7091 	 * each time we want to add new variables to the list.
7092 	 */
7093 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7094 		if (t->ipft_name == NULL)
7095 			break;
7096 	*p = array;
7097 
7098 	return 0;
7099 }
7100 
7101 
7102 /* ------------------------------------------------------------------------ */
7103 /* Function:    ipf_tune_array_unlink                                       */
7104 /* Returns:     0 == success, -1 == failure                                 */
7105 /* Parameters:  softc(I) - soft context pointerto work with                 */
7106 /*              array(I) - pointer to an array of tuneables                 */
7107 /*                                                                          */
7108 /* ------------------------------------------------------------------------ */
7109 int
ipf_tune_array_unlink(softc,array)7110 ipf_tune_array_unlink(softc, array)
7111 	ipf_main_softc_t *softc;
7112 	ipftuneable_t *array;
7113 {
7114 	ipftuneable_t *t, **p;
7115 
7116 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7117 		if (t == array)
7118 			break;
7119 	if (t == NULL)
7120 		return -1;
7121 
7122 	for (; t[1].ipft_name != NULL; t++)
7123 		;
7124 
7125 	*p = t->ipft_next;
7126 
7127 	return 0;
7128 }
7129 
7130 
7131 /* ------------------------------------------------------------------------ */
7132 /* Function:   ipf_tune_array_copy                                          */
7133 /* Returns:    NULL = failure, else pointer to new array                    */
7134 /* Parameters: base(I)     - pointer to structure base                      */
7135 /*             size(I)     - size of the array at template                  */
7136 /*             template(I) - original array to copy                         */
7137 /*                                                                          */
7138 /* Allocate memory for a new set of tuneable values and copy everything     */
7139 /* from template into the new region of memory.  The new region is full of  */
7140 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7141 /*                                                                          */
7142 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7143 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
7144 /* location of the tuneable value inside the structure pointed to by base.  */
7145 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7146 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7147 /* ipftp_void that points to the stored value.                              */
7148 /* ------------------------------------------------------------------------ */
7149 ipftuneable_t *
ipf_tune_array_copy(base,size,template)7150 ipf_tune_array_copy(base, size, template)
7151 	void *base;
7152 	size_t size;
7153 	ipftuneable_t *template;
7154 {
7155 	ipftuneable_t *copy;
7156 	int i;
7157 
7158 
7159 	KMALLOCS(copy, ipftuneable_t *, size);
7160 	if (copy == NULL) {
7161 		return NULL;
7162 	}
7163 	bcopy(template, copy, size);
7164 
7165 	for (i = 0; copy[i].ipft_name; i++) {
7166 		copy[i].ipft_una.ipftp_offset += (u_long)base;
7167 		copy[i].ipft_next = copy + i + 1;
7168 	}
7169 
7170 	return copy;
7171 }
7172 
7173 
7174 /* ------------------------------------------------------------------------ */
7175 /* Function:    ipf_tune_add                                                */
7176 /* Returns:     int - 0 == success, else failure                            */
7177 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7178 /*                                                                          */
7179 /* Appends tune structures from the array passed in (newtune) to the end of */
7180 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
7181 /* owner of the object is not expected to ever change "ipft_next".          */
7182 /* ------------------------------------------------------------------------ */
7183 int
ipf_tune_add(softc,newtune)7184 ipf_tune_add(softc, newtune)
7185 	ipf_main_softc_t *softc;
7186 	ipftuneable_t *newtune;
7187 {
7188 	ipftuneable_t *ta, **tap;
7189 
7190 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7191 	if (ta != NULL) {
7192 		IPFERROR(74);
7193 		return EEXIST;
7194 	}
7195 
7196 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7197 		;
7198 
7199 	newtune->ipft_next = NULL;
7200 	*tap = newtune;
7201 	return 0;
7202 }
7203 
7204 
7205 /* ------------------------------------------------------------------------ */
7206 /* Function:    ipf_tune_del                                                */
7207 /* Returns:     int - 0 == success, else failure                            */
7208 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7209 /*                        current dynamic tuneables                         */
7210 /*                                                                          */
7211 /* Search for the tune structure, by pointer, in the list of those that are */
7212 /* dynamically added at run time.  If found, adjust the list so that this   */
7213 /* structure is no longer part of it.                                       */
7214 /* ------------------------------------------------------------------------ */
7215 int
ipf_tune_del(softc,oldtune)7216 ipf_tune_del(softc, oldtune)
7217 	ipf_main_softc_t *softc;
7218 	ipftuneable_t *oldtune;
7219 {
7220 	ipftuneable_t *ta, **tap;
7221 	int error = 0;
7222 
7223 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7224 	     tap = &ta->ipft_next) {
7225 		if (ta == oldtune) {
7226 			*tap = oldtune->ipft_next;
7227 			oldtune->ipft_next = NULL;
7228 			break;
7229 		}
7230 	}
7231 
7232 	if (ta == NULL) {
7233 		error = ESRCH;
7234 		IPFERROR(75);
7235 	}
7236 	return error;
7237 }
7238 
7239 
7240 /* ------------------------------------------------------------------------ */
7241 /* Function:    ipf_tune_del_array                                          */
7242 /* Returns:     int - 0 == success, else failure                            */
7243 /* Parameters:  oldtune - pointer to tuneables array                        */
7244 /*                                                                          */
7245 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7246 /* tunables.  If one entry should fail to be found, an error will be        */
7247 /* returned and no further ones removed.                                    */
7248 /* An entry with a NULL name is used as the indicator of the last entry in  */
7249 /* the array.                                                               */
7250 /* ------------------------------------------------------------------------ */
7251 int
ipf_tune_del_array(softc,oldtune)7252 ipf_tune_del_array(softc, oldtune)
7253 	ipf_main_softc_t *softc;
7254 	ipftuneable_t *oldtune;
7255 {
7256 	ipftuneable_t *ot;
7257 	int error = 0;
7258 
7259 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7260 		error = ipf_tune_del(softc, ot);
7261 		if (error != 0)
7262 			break;
7263 	}
7264 
7265 	return error;
7266 
7267 }
7268 
7269 
7270 /* ------------------------------------------------------------------------ */
7271 /* Function:    ipf_tune                                                    */
7272 /* Returns:     int - 0 == success, else failure                            */
7273 /* Parameters:  cmd(I)  - ioctl command number                              */
7274 /*              data(I) - pointer to ioctl data structure                   */
7275 /*                                                                          */
7276 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7277 /* three ioctls provide the means to access and control global variables    */
7278 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7279 /* changed without rebooting, reloading or recompiling.  The initialisation */
7280 /* and 'destruction' routines of the various components of ipfilter are all */
7281 /* each responsible for handling their own values being too big.            */
7282 /* ------------------------------------------------------------------------ */
7283 int
ipf_ipftune(softc,cmd,data)7284 ipf_ipftune(softc, cmd, data)
7285 	ipf_main_softc_t *softc;
7286 	ioctlcmd_t cmd;
7287 	void *data;
7288 {
7289 	ipftuneable_t *ta;
7290 	ipftune_t tu;
7291 	void *cookie;
7292 	int error;
7293 
7294 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7295 	if (error != 0)
7296 		return error;
7297 
7298 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7299 	cookie = tu.ipft_cookie;
7300 	ta = NULL;
7301 
7302 	switch (cmd)
7303 	{
7304 	case SIOCIPFGETNEXT :
7305 		/*
7306 		 * If cookie is non-NULL, assume it to be a pointer to the last
7307 		 * entry we looked at, so find it (if possible) and return a
7308 		 * pointer to the next one after it.  The last entry in the
7309 		 * the table is a NULL entry, so when we get to it, set cookie
7310 		 * to NULL and return that, indicating end of list, erstwhile
7311 		 * if we come in with cookie set to NULL, we are starting anew
7312 		 * at the front of the list.
7313 		 */
7314 		if (cookie != NULL) {
7315 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7316 						   cookie, &tu.ipft_cookie);
7317 		} else {
7318 			ta = softc->ipf_tuners;
7319 			tu.ipft_cookie = ta + 1;
7320 		}
7321 		if (ta != NULL) {
7322 			/*
7323 			 * Entry found, but does the data pointed to by that
7324 			 * row fit in what we can return?
7325 			 */
7326 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7327 				IPFERROR(76);
7328 				return EINVAL;
7329 			}
7330 
7331 			tu.ipft_vlong = 0;
7332 			if (ta->ipft_sz == sizeof(u_long))
7333 				tu.ipft_vlong = *ta->ipft_plong;
7334 			else if (ta->ipft_sz == sizeof(u_int))
7335 				tu.ipft_vint = *ta->ipft_pint;
7336 			else if (ta->ipft_sz == sizeof(u_short))
7337 				tu.ipft_vshort = *ta->ipft_pshort;
7338 			else if (ta->ipft_sz == sizeof(u_char))
7339 				tu.ipft_vchar = *ta->ipft_pchar;
7340 
7341 			tu.ipft_sz = ta->ipft_sz;
7342 			tu.ipft_min = ta->ipft_min;
7343 			tu.ipft_max = ta->ipft_max;
7344 			tu.ipft_flags = ta->ipft_flags;
7345 			bcopy(ta->ipft_name, tu.ipft_name,
7346 			      MIN(sizeof(tu.ipft_name),
7347 				  strlen(ta->ipft_name) + 1));
7348 		}
7349 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7350 		break;
7351 
7352 	case SIOCIPFGET :
7353 	case SIOCIPFSET :
7354 		/*
7355 		 * Search by name or by cookie value for a particular entry
7356 		 * in the tuning paramter table.
7357 		 */
7358 		IPFERROR(77);
7359 		error = ESRCH;
7360 		if (cookie != NULL) {
7361 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7362 						   cookie, NULL);
7363 			if (ta != NULL)
7364 				error = 0;
7365 		} else if (tu.ipft_name[0] != '\0') {
7366 			ta = ipf_tune_findbyname(softc->ipf_tuners,
7367 						 tu.ipft_name);
7368 			if (ta != NULL)
7369 				error = 0;
7370 		}
7371 		if (error != 0)
7372 			break;
7373 
7374 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7375 			/*
7376 			 * Fetch the tuning parameters for a particular value
7377 			 */
7378 			tu.ipft_vlong = 0;
7379 			if (ta->ipft_sz == sizeof(u_long))
7380 				tu.ipft_vlong = *ta->ipft_plong;
7381 			else if (ta->ipft_sz == sizeof(u_int))
7382 				tu.ipft_vint = *ta->ipft_pint;
7383 			else if (ta->ipft_sz == sizeof(u_short))
7384 				tu.ipft_vshort = *ta->ipft_pshort;
7385 			else if (ta->ipft_sz == sizeof(u_char))
7386 				tu.ipft_vchar = *ta->ipft_pchar;
7387 			tu.ipft_cookie = ta;
7388 			tu.ipft_sz = ta->ipft_sz;
7389 			tu.ipft_min = ta->ipft_min;
7390 			tu.ipft_max = ta->ipft_max;
7391 			tu.ipft_flags = ta->ipft_flags;
7392 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7393 
7394 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7395 			/*
7396 			 * Set an internal parameter.  The hard part here is
7397 			 * getting the new value safely and correctly out of
7398 			 * the kernel (given we only know its size, not type.)
7399 			 */
7400 			u_long in;
7401 
7402 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7403 			    (softc->ipf_running > 0)) {
7404 				IPFERROR(78);
7405 				error = EBUSY;
7406 				break;
7407 			}
7408 
7409 			in = tu.ipft_vlong;
7410 			if (in < ta->ipft_min || in > ta->ipft_max) {
7411 				IPFERROR(79);
7412 				error = EINVAL;
7413 				break;
7414 			}
7415 
7416 			if (ta->ipft_func != NULL) {
7417 				SPL_INT(s);
7418 
7419 				SPL_NET(s);
7420 				error = (*ta->ipft_func)(softc, ta,
7421 							 &tu.ipft_un);
7422 				SPL_X(s);
7423 
7424 			} else if (ta->ipft_sz == sizeof(u_long)) {
7425 				tu.ipft_vlong = *ta->ipft_plong;
7426 				*ta->ipft_plong = in;
7427 
7428 			} else if (ta->ipft_sz == sizeof(u_int)) {
7429 				tu.ipft_vint = *ta->ipft_pint;
7430 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7431 
7432 			} else if (ta->ipft_sz == sizeof(u_short)) {
7433 				tu.ipft_vshort = *ta->ipft_pshort;
7434 				*ta->ipft_pshort = (u_short)(in & 0xffff);
7435 
7436 			} else if (ta->ipft_sz == sizeof(u_char)) {
7437 				tu.ipft_vchar = *ta->ipft_pchar;
7438 				*ta->ipft_pchar = (u_char)(in & 0xff);
7439 			}
7440 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7441 		}
7442 		break;
7443 
7444 	default :
7445 		IPFERROR(80);
7446 		error = EINVAL;
7447 		break;
7448 	}
7449 
7450 	return error;
7451 }
7452 
7453 
7454 /* ------------------------------------------------------------------------ */
7455 /* Function:    ipf_zerostats                                               */
7456 /* Returns:     int - 0 = success, else failure                             */
7457 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7458 /*                                                                          */
7459 /* Copies the current statistics out to userspace and then zero's the       */
7460 /* current ones in the kernel. The lock is only held across the bzero() as  */
7461 /* the copyout may result in paging (ie network activity.)                  */
7462 /* ------------------------------------------------------------------------ */
7463 int
ipf_zerostats(softc,data)7464 ipf_zerostats(softc, data)
7465 	ipf_main_softc_t *softc;
7466 	caddr_t	data;
7467 {
7468 	friostat_t fio;
7469 	ipfobj_t obj;
7470 	int error;
7471 
7472 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7473 	if (error != 0)
7474 		return error;
7475 	ipf_getstat(softc, &fio, obj.ipfo_rev);
7476 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7477 	if (error != 0)
7478 		return error;
7479 
7480 	WRITE_ENTER(&softc->ipf_mutex);
7481 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7482 	RWLOCK_EXIT(&softc->ipf_mutex);
7483 
7484 	return 0;
7485 }
7486 
7487 
7488 /* ------------------------------------------------------------------------ */
7489 /* Function:    ipf_resolvedest                                             */
7490 /* Returns:     Nil                                                         */
7491 /* Parameters:  softc(I) - pointer to soft context main structure           */
7492 /*              base(I)  - where strings are stored                         */
7493 /*              fdp(IO)  - pointer to destination information to resolve    */
7494 /*              v(I)     - IP protocol version to match                     */
7495 /*                                                                          */
7496 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7497 /* if a matching name can be found for the particular IP protocol version   */
7498 /* then store the interface pointer in the frdest struct.  If no match is   */
7499 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7500 /* indicate there is no information at all in the structure.                */
7501 /* ------------------------------------------------------------------------ */
7502 int
ipf_resolvedest(softc,base,fdp,v)7503 ipf_resolvedest(softc, base, fdp, v)
7504 	ipf_main_softc_t *softc;
7505 	char *base;
7506 	frdest_t *fdp;
7507 	int v;
7508 {
7509 	int errval = 0;
7510 	void *ifp;
7511 
7512 	ifp = NULL;
7513 
7514 	if (fdp->fd_name != -1) {
7515 		if (fdp->fd_type == FRD_DSTLIST) {
7516 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7517 						  IPLT_DSTLIST,
7518 						  base + fdp->fd_name,
7519 						  NULL);
7520 			if (ifp == NULL) {
7521 				IPFERROR(144);
7522 				errval = ESRCH;
7523 			}
7524 		} else {
7525 			ifp = GETIFP(base + fdp->fd_name, v);
7526 			if (ifp == NULL)
7527 				ifp = (void *)-1;
7528 		}
7529 	}
7530 	fdp->fd_ptr = ifp;
7531 
7532 	return errval;
7533 }
7534 
7535 
7536 /* ------------------------------------------------------------------------ */
7537 /* Function:    ipf_resolvenic                                              */
7538 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7539 /*                      pointer to interface structure for NIC              */
7540 /* Parameters:  softc(I)- pointer to soft context main structure            */
7541 /*              name(I) - complete interface name                           */
7542 /*              v(I)    - IP protocol version                               */
7543 /*                                                                          */
7544 /* Look for a network interface structure that firstly has a matching name  */
7545 /* to that passed in and that is also being used for that IP protocol       */
7546 /* version (necessary on some platforms where there are separate listings   */
7547 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7548 /* ------------------------------------------------------------------------ */
7549 void *
ipf_resolvenic(softc,name,v)7550 ipf_resolvenic(softc, name, v)
7551 	ipf_main_softc_t *softc;
7552 	char *name;
7553 	int v;
7554 {
7555 	void *nic;
7556 
7557 	softc = softc;	/* gcc -Wextra */
7558 	if (name[0] == '\0')
7559 		return NULL;
7560 
7561 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7562 		return NULL;
7563 	}
7564 
7565 	nic = GETIFP(name, v);
7566 	if (nic == NULL)
7567 		nic = (void *)-1;
7568 	return nic;
7569 }
7570 
7571 
7572 /* ------------------------------------------------------------------------ */
7573 /* Function:    ipf_token_expire                                            */
7574 /* Returns:     None.                                                       */
7575 /* Parameters:  softc(I) - pointer to soft context main structure           */
7576 /*                                                                          */
7577 /* This function is run every ipf tick to see if there are any tokens that  */
7578 /* have been held for too long and need to be freed up.                     */
7579 /* ------------------------------------------------------------------------ */
7580 void
ipf_token_expire(softc)7581 ipf_token_expire(softc)
7582 	ipf_main_softc_t *softc;
7583 {
7584 	ipftoken_t *it;
7585 
7586 	WRITE_ENTER(&softc->ipf_tokens);
7587 	while ((it = softc->ipf_token_head) != NULL) {
7588 		if (it->ipt_die > softc->ipf_ticks)
7589 			break;
7590 
7591 		ipf_token_deref(softc, it);
7592 	}
7593 	RWLOCK_EXIT(&softc->ipf_tokens);
7594 }
7595 
7596 
7597 /* ------------------------------------------------------------------------ */
7598 /* Function:    ipf_token_flush                                             */
7599 /* Returns:     None.                                                       */
7600 /* Parameters:  softc(I) - pointer to soft context main structure           */
7601 /*                                                                          */
7602 /* Loop through all of the existing tokens and call deref to see if they    */
7603 /* can be freed. Normally a function like this might just loop on           */
7604 /* ipf_token_head but there is a chance that a token might have a ref count */
7605 /* of greater than one and in that case the the reference would drop twice  */
7606 /* by code that is only entitled to drop it once.                           */
7607 /* ------------------------------------------------------------------------ */
7608 static void
ipf_token_flush(softc)7609 ipf_token_flush(softc)
7610 	ipf_main_softc_t *softc;
7611 {
7612 	ipftoken_t *it, *next;
7613 
7614 	WRITE_ENTER(&softc->ipf_tokens);
7615 	for (it = softc->ipf_token_head; it != NULL; it = next) {
7616 		next = it->ipt_next;
7617 		(void) ipf_token_deref(softc, it);
7618 	}
7619 	RWLOCK_EXIT(&softc->ipf_tokens);
7620 }
7621 
7622 
7623 /* ------------------------------------------------------------------------ */
7624 /* Function:    ipf_token_del                                               */
7625 /* Returns:     int     - 0 = success, else error                           */
7626 /* Parameters:  softc(I)- pointer to soft context main structure            */
7627 /*              type(I) - the token type to match                           */
7628 /*              uid(I)  - uid owning the token                              */
7629 /*              ptr(I)  - context pointer for the token                     */
7630 /*                                                                          */
7631 /* This function looks for a a token in the current list that matches up    */
7632 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7633 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7634 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7635 /* enables debugging to distinguish between the two paths that ultimately   */
7636 /* lead to a token to be deleted.                                           */
7637 /* ------------------------------------------------------------------------ */
7638 int
ipf_token_del(softc,type,uid,ptr)7639 ipf_token_del(softc, type, uid, ptr)
7640 	ipf_main_softc_t *softc;
7641 	int type, uid;
7642 	void *ptr;
7643 {
7644 	ipftoken_t *it;
7645 	int error;
7646 
7647 	IPFERROR(82);
7648 	error = ESRCH;
7649 
7650 	WRITE_ENTER(&softc->ipf_tokens);
7651 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7652 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7653 		    uid == it->ipt_uid) {
7654 			it->ipt_complete = 2;
7655 			ipf_token_deref(softc, it);
7656 			error = 0;
7657 			break;
7658 		}
7659 	}
7660 	RWLOCK_EXIT(&softc->ipf_tokens);
7661 
7662 	return error;
7663 }
7664 
7665 
7666 /* ------------------------------------------------------------------------ */
7667 /* Function:    ipf_token_mark_complete                                     */
7668 /* Returns:     None.                                                       */
7669 /* Parameters:  token(I) - pointer to token structure                       */
7670 /*                                                                          */
7671 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7672 /* ------------------------------------------------------------------------ */
7673 void
ipf_token_mark_complete(token)7674 ipf_token_mark_complete(token)
7675 	ipftoken_t *token;
7676 {
7677 	if (token->ipt_complete == 0)
7678 		token->ipt_complete = 1;
7679 }
7680 
7681 
7682 /* ------------------------------------------------------------------------ */
7683 /* Function:    ipf_token_find                                               */
7684 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7685 /* Parameters:  softc(I)- pointer to soft context main structure            */
7686 /*              type(I) - the token type to match                           */
7687 /*              uid(I)  - uid owning the token                              */
7688 /*              ptr(I)  - context pointer for the token                     */
7689 /*                                                                          */
7690 /* This function looks for a live token in the list of current tokens that  */
7691 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7692 /* allocated.  If one is found then it is moved to the top of the list of   */
7693 /* currently active tokens.                                                 */
7694 /* ------------------------------------------------------------------------ */
7695 ipftoken_t *
ipf_token_find(softc,type,uid,ptr)7696 ipf_token_find(softc, type, uid, ptr)
7697 	ipf_main_softc_t *softc;
7698 	int type, uid;
7699 	void *ptr;
7700 {
7701 	ipftoken_t *it, *new;
7702 
7703 	KMALLOC(new, ipftoken_t *);
7704 	if (new != NULL)
7705 		bzero((char *)new, sizeof(*new));
7706 
7707 	WRITE_ENTER(&softc->ipf_tokens);
7708 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7709 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7710 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7711 			break;
7712 	}
7713 
7714 	if (it == NULL) {
7715 		it = new;
7716 		new = NULL;
7717 		if (it == NULL) {
7718 			RWLOCK_EXIT(&softc->ipf_tokens);
7719 			return NULL;
7720 		}
7721 		it->ipt_ctx = ptr;
7722 		it->ipt_uid = uid;
7723 		it->ipt_type = type;
7724 		it->ipt_ref = 1;
7725 	} else {
7726 		if (new != NULL) {
7727 			KFREE(new);
7728 			new = NULL;
7729 		}
7730 
7731 		if (it->ipt_complete > 0)
7732 			it = NULL;
7733 		else
7734 			ipf_token_unlink(softc, it);
7735 	}
7736 
7737 	if (it != NULL) {
7738 		it->ipt_pnext = softc->ipf_token_tail;
7739 		*softc->ipf_token_tail = it;
7740 		softc->ipf_token_tail = &it->ipt_next;
7741 		it->ipt_next = NULL;
7742 		it->ipt_ref++;
7743 
7744 		it->ipt_die = softc->ipf_ticks + 20;
7745 	}
7746 
7747 	RWLOCK_EXIT(&softc->ipf_tokens);
7748 
7749 	return it;
7750 }
7751 
7752 
7753 /* ------------------------------------------------------------------------ */
7754 /* Function:    ipf_token_unlink                                            */
7755 /* Returns:     None.                                                       */
7756 /* Parameters:  softc(I) - pointer to soft context main structure           */
7757 /*              token(I) - pointer to token structure                       */
7758 /* Write Locks: ipf_tokens                                                  */
7759 /*                                                                          */
7760 /* This function unlinks a token structure from the linked list of tokens   */
7761 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7762 /* but the tail does due to the linked list implementation.                 */
7763 /* ------------------------------------------------------------------------ */
7764 static void
ipf_token_unlink(softc,token)7765 ipf_token_unlink(softc, token)
7766 	ipf_main_softc_t *softc;
7767 	ipftoken_t *token;
7768 {
7769 
7770 	if (softc->ipf_token_tail == &token->ipt_next)
7771 		softc->ipf_token_tail = token->ipt_pnext;
7772 
7773 	*token->ipt_pnext = token->ipt_next;
7774 	if (token->ipt_next != NULL)
7775 		token->ipt_next->ipt_pnext = token->ipt_pnext;
7776 	token->ipt_next = NULL;
7777 	token->ipt_pnext = NULL;
7778 }
7779 
7780 
7781 /* ------------------------------------------------------------------------ */
7782 /* Function:    ipf_token_deref                                             */
7783 /* Returns:     int      - 0 == token freed, else reference count           */
7784 /* Parameters:  softc(I) - pointer to soft context main structure           */
7785 /*              token(I) - pointer to token structure                       */
7786 /* Write Locks: ipf_tokens                                                  */
7787 /*                                                                          */
7788 /* Drop the reference count on the token structure and if it drops to zero, */
7789 /* call the dereference function for the token type because it is then      */
7790 /* possible to free the token data structure.                               */
7791 /* ------------------------------------------------------------------------ */
7792 int
ipf_token_deref(softc,token)7793 ipf_token_deref(softc, token)
7794 	ipf_main_softc_t *softc;
7795 	ipftoken_t *token;
7796 {
7797 	void *data, **datap;
7798 
7799 	ASSERT(token->ipt_ref > 0);
7800 	token->ipt_ref--;
7801 	if (token->ipt_ref > 0)
7802 		return token->ipt_ref;
7803 
7804 	data = token->ipt_data;
7805 	datap = &data;
7806 
7807 	if ((data != NULL) && (data != (void *)-1)) {
7808 		switch (token->ipt_type)
7809 		{
7810 		case IPFGENITER_IPF :
7811 			(void) ipf_derefrule(softc, (frentry_t **)datap);
7812 			break;
7813 		case IPFGENITER_IPNAT :
7814 			WRITE_ENTER(&softc->ipf_nat);
7815 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7816 			RWLOCK_EXIT(&softc->ipf_nat);
7817 			break;
7818 		case IPFGENITER_NAT :
7819 			ipf_nat_deref(softc, (nat_t **)datap);
7820 			break;
7821 		case IPFGENITER_STATE :
7822 			ipf_state_deref(softc, (ipstate_t **)datap);
7823 			break;
7824 		case IPFGENITER_FRAG :
7825 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7826 			break;
7827 		case IPFGENITER_NATFRAG :
7828 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7829 			break;
7830 		case IPFGENITER_HOSTMAP :
7831 			WRITE_ENTER(&softc->ipf_nat);
7832 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7833 			RWLOCK_EXIT(&softc->ipf_nat);
7834 			break;
7835 		default :
7836 			ipf_lookup_iterderef(softc, token->ipt_type, data);
7837 			break;
7838 		}
7839 	}
7840 
7841 	ipf_token_unlink(softc, token);
7842 	KFREE(token);
7843 	return 0;
7844 }
7845 
7846 
7847 /* ------------------------------------------------------------------------ */
7848 /* Function:    ipf_nextrule                                                */
7849 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7850 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7851 /*              fr(I)       - pointer to filter rule                        */
7852 /*              out(I)      - 1 == out rules, 0 == input rules              */
7853 /*                                                                          */
7854 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7855 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7856 /* last rule in the list. When walking rule lists, it is either input or    */
7857 /* output rules that are returned, never both.                              */
7858 /* ------------------------------------------------------------------------ */
7859 static frentry_t *
ipf_nextrule(softc,active,unit,fr,out)7860 ipf_nextrule(softc, active, unit, fr, out)
7861 	ipf_main_softc_t *softc;
7862 	int active, unit;
7863 	frentry_t *fr;
7864 	int out;
7865 {
7866 	frentry_t *next;
7867 	frgroup_t *fg;
7868 
7869 	if (fr != NULL && fr->fr_group != -1) {
7870 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7871 				   unit, active, NULL);
7872 		if (fg != NULL)
7873 			fg = fg->fg_next;
7874 	} else {
7875 		fg = softc->ipf_groups[unit][active];
7876 	}
7877 
7878 	while (fg != NULL) {
7879 		next = fg->fg_start;
7880 		while (next != NULL) {
7881 			if (out) {
7882 				if (next->fr_flags & FR_OUTQUE)
7883 					return next;
7884 			} else if (next->fr_flags & FR_INQUE) {
7885 				return next;
7886 			}
7887 			next = next->fr_next;
7888 		}
7889 		if (next == NULL)
7890 			fg = fg->fg_next;
7891 	}
7892 
7893 	return NULL;
7894 }
7895 
7896 /* ------------------------------------------------------------------------ */
7897 /* Function:    ipf_getnextrule                                             */
7898 /* Returns:     int - 0 = success, else error                               */
7899 /* Parameters:  softc(I)- pointer to soft context main structure            */
7900 /*              t(I)   - pointer to destination information to resolve      */
7901 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7902 /*                                                                          */
7903 /* This function's first job is to bring in the ipfruleiter_t structure via */
7904 /* the ipfobj_t structure to determine what should be the next rule to      */
7905 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7906 /* find the 'next rule'.  This may include searching rule group lists or    */
7907 /* just be as simple as looking at the 'next' field in the rule structure.  */
7908 /* When we have found the rule to return, increase its reference count and  */
7909 /* if we used an existing rule to get here, decrease its reference count.   */
7910 /* ------------------------------------------------------------------------ */
7911 int
ipf_getnextrule(softc,t,ptr)7912 ipf_getnextrule(softc, t, ptr)
7913 	ipf_main_softc_t *softc;
7914 	ipftoken_t *t;
7915 	void *ptr;
7916 {
7917 	frentry_t *fr, *next, zero;
7918 	ipfruleiter_t it;
7919 	int error, out;
7920 	frgroup_t *fg;
7921 	ipfobj_t obj;
7922 	int predict;
7923 	char *dst;
7924 	int unit;
7925 
7926 	if (t == NULL || ptr == NULL) {
7927 		IPFERROR(84);
7928 		return EFAULT;
7929 	}
7930 
7931 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7932 	if (error != 0)
7933 		return error;
7934 
7935 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7936 		IPFERROR(85);
7937 		return EINVAL;
7938 	}
7939 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7940 		IPFERROR(86);
7941 		return EINVAL;
7942 	}
7943 	if (it.iri_nrules == 0) {
7944 		IPFERROR(87);
7945 		return ENOSPC;
7946 	}
7947 	if (it.iri_rule == NULL) {
7948 		IPFERROR(88);
7949 		return EFAULT;
7950 	}
7951 
7952 	fg = NULL;
7953 	fr = t->ipt_data;
7954 	if ((it.iri_inout & F_OUT) != 0)
7955 		out = 1;
7956 	else
7957 		out = 0;
7958 	if ((it.iri_inout & F_ACIN) != 0)
7959 		unit = IPL_LOGCOUNT;
7960 	else
7961 		unit = IPL_LOGIPF;
7962 
7963 	READ_ENTER(&softc->ipf_mutex);
7964 	if (fr == NULL) {
7965 		if (*it.iri_group == '\0') {
7966 			if (unit == IPL_LOGCOUNT) {
7967 				next = softc->ipf_acct[out][it.iri_active];
7968 			} else {
7969 				next = softc->ipf_rules[out][it.iri_active];
7970 			}
7971 			if (next == NULL)
7972 				next = ipf_nextrule(softc, it.iri_active,
7973 						    unit, NULL, out);
7974 		} else {
7975 			fg = ipf_findgroup(softc, it.iri_group, unit,
7976 					   it.iri_active, NULL);
7977 			if (fg != NULL)
7978 				next = fg->fg_start;
7979 			else
7980 				next = NULL;
7981 		}
7982 	} else {
7983 		next = fr->fr_next;
7984 		if (next == NULL)
7985 			next = ipf_nextrule(softc, it.iri_active, unit,
7986 					    fr, out);
7987 	}
7988 
7989 	if (next != NULL && next->fr_next != NULL)
7990 		predict = 1;
7991 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7992 		predict = 1;
7993 	else
7994 		predict = 0;
7995 
7996 	if (fr != NULL)
7997 		(void) ipf_derefrule(softc, &fr);
7998 
7999 	obj.ipfo_type = IPFOBJ_FRENTRY;
8000 	dst = (char *)it.iri_rule;
8001 
8002 	if (next != NULL) {
8003 		obj.ipfo_size = next->fr_size;
8004 		MUTEX_ENTER(&next->fr_lock);
8005 		next->fr_ref++;
8006 		MUTEX_EXIT(&next->fr_lock);
8007 		t->ipt_data = next;
8008 	} else {
8009 		obj.ipfo_size = sizeof(frentry_t);
8010 		bzero(&zero, sizeof(zero));
8011 		next = &zero;
8012 		t->ipt_data = NULL;
8013 	}
8014 	it.iri_rule = predict ? next : NULL;
8015 	if (predict == 0)
8016 		ipf_token_mark_complete(t);
8017 
8018 	RWLOCK_EXIT(&softc->ipf_mutex);
8019 
8020 	obj.ipfo_ptr = dst;
8021 	error = ipf_outobjk(softc, &obj, next);
8022 	if (error == 0 && t->ipt_data != NULL) {
8023 		dst += obj.ipfo_size;
8024 		if (next->fr_data != NULL) {
8025 			ipfobj_t dobj;
8026 
8027 			if (next->fr_type == FR_T_IPFEXPR)
8028 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
8029 			else
8030 				dobj.ipfo_type = IPFOBJ_FRIPF;
8031 			dobj.ipfo_size = next->fr_dsize;
8032 			dobj.ipfo_rev = obj.ipfo_rev;
8033 			dobj.ipfo_ptr = dst;
8034 			error = ipf_outobjk(softc, &dobj, next->fr_data);
8035 		}
8036 	}
8037 
8038 	if ((fr != NULL) && (next == &zero))
8039 		(void) ipf_derefrule(softc, &fr);
8040 
8041 	return error;
8042 }
8043 
8044 
8045 /* ------------------------------------------------------------------------ */
8046 /* Function:    ipf_frruleiter                                              */
8047 /* Returns:     int - 0 = success, else error                               */
8048 /* Parameters:  softc(I)- pointer to soft context main structure            */
8049 /*              data(I) - the token type to match                           */
8050 /*              uid(I)  - uid owning the token                              */
8051 /*              ptr(I)  - context pointer for the token                     */
8052 /*                                                                          */
8053 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8054 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8055 /* the process doing the ioctl and use that to ask for the next rule.       */
8056 /* ------------------------------------------------------------------------ */
8057 static int
ipf_frruleiter(softc,data,uid,ctx)8058 ipf_frruleiter(softc, data, uid, ctx)
8059 	ipf_main_softc_t *softc;
8060 	void *data, *ctx;
8061 	int uid;
8062 {
8063 	ipftoken_t *token;
8064 	ipfruleiter_t it;
8065 	ipfobj_t obj;
8066 	int error;
8067 
8068 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8069 	if (token != NULL) {
8070 		error = ipf_getnextrule(softc, token, data);
8071 		WRITE_ENTER(&softc->ipf_tokens);
8072 		ipf_token_deref(softc, token);
8073 		RWLOCK_EXIT(&softc->ipf_tokens);
8074 	} else {
8075 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8076 		if (error != 0)
8077 			return error;
8078 		it.iri_rule = NULL;
8079 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8080 	}
8081 
8082 	return error;
8083 }
8084 
8085 
8086 /* ------------------------------------------------------------------------ */
8087 /* Function:    ipf_geniter                                                 */
8088 /* Returns:     int - 0 = success, else error                               */
8089 /* Parameters:  softc(I) - pointer to soft context main structure           */
8090 /*              token(I) - pointer to ipftoken_t structure                  */
8091 /*              itp(I)   - pointer to iterator data                         */
8092 /*                                                                          */
8093 /* Decide which iterator function to call using information passed through  */
8094 /* the ipfgeniter_t structure at itp.                                       */
8095 /* ------------------------------------------------------------------------ */
8096 static int
ipf_geniter(softc,token,itp)8097 ipf_geniter(softc, token, itp)
8098 	ipf_main_softc_t *softc;
8099 	ipftoken_t *token;
8100 	ipfgeniter_t *itp;
8101 {
8102 	int error;
8103 
8104 	switch (itp->igi_type)
8105 	{
8106 	case IPFGENITER_FRAG :
8107 		error = ipf_frag_pkt_next(softc, token, itp);
8108 		break;
8109 	default :
8110 		IPFERROR(92);
8111 		error = EINVAL;
8112 		break;
8113 	}
8114 
8115 	return error;
8116 }
8117 
8118 
8119 /* ------------------------------------------------------------------------ */
8120 /* Function:    ipf_genericiter                                             */
8121 /* Returns:     int - 0 = success, else error                               */
8122 /* Parameters:  softc(I)- pointer to soft context main structure            */
8123 /*              data(I) - the token type to match                           */
8124 /*              uid(I)  - uid owning the token                              */
8125 /*              ptr(I)  - context pointer for the token                     */
8126 /*                                                                          */
8127 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8128 /* ------------------------------------------------------------------------ */
8129 int
ipf_genericiter(softc,data,uid,ctx)8130 ipf_genericiter(softc, data, uid, ctx)
8131 	ipf_main_softc_t *softc;
8132 	void *data, *ctx;
8133 	int uid;
8134 {
8135 	ipftoken_t *token;
8136 	ipfgeniter_t iter;
8137 	int error;
8138 
8139 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8140 	if (error != 0)
8141 		return error;
8142 
8143 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8144 	if (token != NULL) {
8145 		token->ipt_subtype = iter.igi_type;
8146 		error = ipf_geniter(softc, token, &iter);
8147 		WRITE_ENTER(&softc->ipf_tokens);
8148 		ipf_token_deref(softc, token);
8149 		RWLOCK_EXIT(&softc->ipf_tokens);
8150 	} else {
8151 		IPFERROR(93);
8152 		error = 0;
8153 	}
8154 
8155 	return error;
8156 }
8157 
8158 
8159 /* ------------------------------------------------------------------------ */
8160 /* Function:    ipf_ipf_ioctl                                               */
8161 /* Returns:     int - 0 = success, else error                               */
8162 /* Parameters:  softc(I)- pointer to soft context main structure           */
8163 /*              data(I) - the token type to match                           */
8164 /*              cmd(I)  - the ioctl command number                          */
8165 /*              mode(I) - mode flags for the ioctl                          */
8166 /*              uid(I)  - uid owning the token                              */
8167 /*              ptr(I)  - context pointer for the token                     */
8168 /*                                                                          */
8169 /* This function handles all of the ioctl command that are actually isssued */
8170 /* to the /dev/ipl device.                                                  */
8171 /* ------------------------------------------------------------------------ */
8172 int
ipf_ipf_ioctl(softc,data,cmd,mode,uid,ctx)8173 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8174 	ipf_main_softc_t *softc;
8175 	caddr_t data;
8176 	ioctlcmd_t cmd;
8177 	int mode, uid;
8178 	void *ctx;
8179 {
8180 	friostat_t fio;
8181 	int error, tmp;
8182 	ipfobj_t obj;
8183 	SPL_INT(s);
8184 
8185 	switch (cmd)
8186 	{
8187 	case SIOCFRENB :
8188 		if (!(mode & FWRITE)) {
8189 			IPFERROR(94);
8190 			error = EPERM;
8191 		} else {
8192 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8193 			if (error != 0) {
8194 				IPFERROR(95);
8195 				error = EFAULT;
8196 				break;
8197 			}
8198 
8199 			WRITE_ENTER(&softc->ipf_global);
8200 			if (tmp) {
8201 				if (softc->ipf_running > 0)
8202 					error = 0;
8203 				else
8204 					error = ipfattach(softc);
8205 				if (error == 0)
8206 					softc->ipf_running = 1;
8207 				else
8208 					(void) ipfdetach(softc);
8209 			} else {
8210 				if (softc->ipf_running == 1)
8211 					error = ipfdetach(softc);
8212 				else
8213 					error = 0;
8214 				if (error == 0)
8215 					softc->ipf_running = -1;
8216 			}
8217 			RWLOCK_EXIT(&softc->ipf_global);
8218 		}
8219 		break;
8220 
8221 	case SIOCIPFSET :
8222 		if (!(mode & FWRITE)) {
8223 			IPFERROR(96);
8224 			error = EPERM;
8225 			break;
8226 		}
8227 		/* FALLTHRU */
8228 	case SIOCIPFGETNEXT :
8229 	case SIOCIPFGET :
8230 		error = ipf_ipftune(softc, cmd, (void *)data);
8231 		break;
8232 
8233 	case SIOCSETFF :
8234 		if (!(mode & FWRITE)) {
8235 			IPFERROR(97);
8236 			error = EPERM;
8237 		} else {
8238 			error = BCOPYIN(data, &softc->ipf_flags,
8239 					sizeof(softc->ipf_flags));
8240 			if (error != 0) {
8241 				IPFERROR(98);
8242 				error = EFAULT;
8243 			}
8244 		}
8245 		break;
8246 
8247 	case SIOCGETFF :
8248 		error = BCOPYOUT(&softc->ipf_flags, data,
8249 				 sizeof(softc->ipf_flags));
8250 		if (error != 0) {
8251 			IPFERROR(99);
8252 			error = EFAULT;
8253 		}
8254 		break;
8255 
8256 	case SIOCFUNCL :
8257 		error = ipf_resolvefunc(softc, (void *)data);
8258 		break;
8259 
8260 	case SIOCINAFR :
8261 	case SIOCRMAFR :
8262 	case SIOCADAFR :
8263 	case SIOCZRLST :
8264 		if (!(mode & FWRITE)) {
8265 			IPFERROR(100);
8266 			error = EPERM;
8267 		} else {
8268 			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8269 					  softc->ipf_active, 1);
8270 		}
8271 		break;
8272 
8273 	case SIOCINIFR :
8274 	case SIOCRMIFR :
8275 	case SIOCADIFR :
8276 		if (!(mode & FWRITE)) {
8277 			IPFERROR(101);
8278 			error = EPERM;
8279 		} else {
8280 			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8281 					  1 - softc->ipf_active, 1);
8282 		}
8283 		break;
8284 
8285 	case SIOCSWAPA :
8286 		if (!(mode & FWRITE)) {
8287 			IPFERROR(102);
8288 			error = EPERM;
8289 		} else {
8290 			WRITE_ENTER(&softc->ipf_mutex);
8291 			error = BCOPYOUT(&softc->ipf_active, data,
8292 					 sizeof(softc->ipf_active));
8293 			if (error != 0) {
8294 				IPFERROR(103);
8295 				error = EFAULT;
8296 			} else {
8297 				softc->ipf_active = 1 - softc->ipf_active;
8298 			}
8299 			RWLOCK_EXIT(&softc->ipf_mutex);
8300 		}
8301 		break;
8302 
8303 	case SIOCGETFS :
8304 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8305 				  IPFOBJ_IPFSTAT);
8306 		if (error != 0)
8307 			break;
8308 		ipf_getstat(softc, &fio, obj.ipfo_rev);
8309 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8310 		break;
8311 
8312 	case SIOCFRZST :
8313 		if (!(mode & FWRITE)) {
8314 			IPFERROR(104);
8315 			error = EPERM;
8316 		} else
8317 			error = ipf_zerostats(softc, (caddr_t)data);
8318 		break;
8319 
8320 	case SIOCIPFFL :
8321 		if (!(mode & FWRITE)) {
8322 			IPFERROR(105);
8323 			error = EPERM;
8324 		} else {
8325 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8326 			if (!error) {
8327 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8328 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8329 				if (error != 0) {
8330 					IPFERROR(106);
8331 					error = EFAULT;
8332 				}
8333 			} else {
8334 				IPFERROR(107);
8335 				error = EFAULT;
8336 			}
8337 		}
8338 		break;
8339 
8340 #ifdef USE_INET6
8341 	case SIOCIPFL6 :
8342 		if (!(mode & FWRITE)) {
8343 			IPFERROR(108);
8344 			error = EPERM;
8345 		} else {
8346 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8347 			if (!error) {
8348 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8349 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8350 				if (error != 0) {
8351 					IPFERROR(109);
8352 					error = EFAULT;
8353 				}
8354 			} else {
8355 				IPFERROR(110);
8356 				error = EFAULT;
8357 			}
8358 		}
8359 		break;
8360 #endif
8361 
8362 	case SIOCSTLCK :
8363 		if (!(mode & FWRITE)) {
8364 			IPFERROR(122);
8365 			error = EPERM;
8366 		} else {
8367 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8368 			if (error == 0) {
8369 				ipf_state_setlock(softc->ipf_state_soft, tmp);
8370 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8371 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8372 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8373 			} else {
8374 				IPFERROR(111);
8375 				error = EFAULT;
8376 			}
8377 		}
8378 		break;
8379 
8380 #ifdef	IPFILTER_LOG
8381 	case SIOCIPFFB :
8382 		if (!(mode & FWRITE)) {
8383 			IPFERROR(112);
8384 			error = EPERM;
8385 		} else {
8386 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8387 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8388 			if (error) {
8389 				IPFERROR(113);
8390 				error = EFAULT;
8391 			}
8392 		}
8393 		break;
8394 #endif /* IPFILTER_LOG */
8395 
8396 	case SIOCFRSYN :
8397 		if (!(mode & FWRITE)) {
8398 			IPFERROR(114);
8399 			error = EPERM;
8400 		} else {
8401 			WRITE_ENTER(&softc->ipf_global);
8402 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8403 			error = ipfsync();
8404 #else
8405 			ipf_sync(softc, NULL);
8406 			error = 0;
8407 #endif
8408 			RWLOCK_EXIT(&softc->ipf_global);
8409 
8410 		}
8411 		break;
8412 
8413 	case SIOCGFRST :
8414 		error = ipf_outobj(softc, (void *)data,
8415 				   ipf_frag_stats(softc->ipf_frag_soft),
8416 				   IPFOBJ_FRAGSTAT);
8417 		break;
8418 
8419 #ifdef	IPFILTER_LOG
8420 	case FIONREAD :
8421 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8422 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8423 		break;
8424 #endif
8425 
8426 	case SIOCIPFITER :
8427 		SPL_SCHED(s);
8428 		error = ipf_frruleiter(softc, data, uid, ctx);
8429 		SPL_X(s);
8430 		break;
8431 
8432 	case SIOCGENITER :
8433 		SPL_SCHED(s);
8434 		error = ipf_genericiter(softc, data, uid, ctx);
8435 		SPL_X(s);
8436 		break;
8437 
8438 	case SIOCIPFDELTOK :
8439 		error = BCOPYIN(data, &tmp, sizeof(tmp));
8440 		if (error == 0) {
8441 			SPL_SCHED(s);
8442 			error = ipf_token_del(softc, tmp, uid, ctx);
8443 			SPL_X(s);
8444 		}
8445 		break;
8446 
8447 	default :
8448 		IPFERROR(115);
8449 		error = EINVAL;
8450 		break;
8451 	}
8452 
8453 	return error;
8454 }
8455 
8456 
8457 /* ------------------------------------------------------------------------ */
8458 /* Function:    ipf_decaps                                                  */
8459 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8460 /*                           flags indicating packet filtering decision.    */
8461 /* Parameters:  fin(I)     - pointer to packet information                  */
8462 /*              pass(I)    - IP protocol version to match                   */
8463 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8464 /*                                                                          */
8465 /* This function is called for packets that are wrapt up in other packets,  */
8466 /* for example, an IP packet that is the entire data segment for another IP */
8467 /* packet.  If the basic constraints for this are satisfied, change the     */
8468 /* buffer to point to the start of the inner packet and start processing    */
8469 /* rules belonging to the head group this rule specifies.                   */
8470 /* ------------------------------------------------------------------------ */
8471 u_32_t
ipf_decaps(fin,pass,l5proto)8472 ipf_decaps(fin, pass, l5proto)
8473 	fr_info_t *fin;
8474 	u_32_t pass;
8475 	int l5proto;
8476 {
8477 	fr_info_t fin2, *fino = NULL;
8478 	int elen, hlen, nh;
8479 	grehdr_t gre;
8480 	ip_t *ip;
8481 	mb_t *m;
8482 
8483 	if ((fin->fin_flx & FI_COALESCE) == 0)
8484 		if (ipf_coalesce(fin) == -1)
8485 			goto cantdecaps;
8486 
8487 	m = fin->fin_m;
8488 	hlen = fin->fin_hlen;
8489 
8490 	switch (fin->fin_p)
8491 	{
8492 	case IPPROTO_UDP :
8493 		/*
8494 		 * In this case, the specific protocol being decapsulated
8495 		 * inside UDP frames comes from the rule.
8496 		 */
8497 		nh = fin->fin_fr->fr_icode;
8498 		break;
8499 
8500 	case IPPROTO_GRE :	/* 47 */
8501 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8502 		hlen += sizeof(grehdr_t);
8503 		if (gre.gr_R|gre.gr_s)
8504 			goto cantdecaps;
8505 		if (gre.gr_C)
8506 			hlen += 4;
8507 		if (gre.gr_K)
8508 			hlen += 4;
8509 		if (gre.gr_S)
8510 			hlen += 4;
8511 
8512 		nh = IPPROTO_IP;
8513 
8514 		/*
8515 		 * If the routing options flag is set, validate that it is
8516 		 * there and bounce over it.
8517 		 */
8518 #if 0
8519 		/* This is really heavy weight and lots of room for error, */
8520 		/* so for now, put it off and get the simple stuff right.  */
8521 		if (gre.gr_R) {
8522 			u_char off, len, *s;
8523 			u_short af;
8524 			int end;
8525 
8526 			end = 0;
8527 			s = fin->fin_dp;
8528 			s += hlen;
8529 			aplen = fin->fin_plen - hlen;
8530 			while (aplen > 3) {
8531 				af = (s[0] << 8) | s[1];
8532 				off = s[2];
8533 				len = s[3];
8534 				aplen -= 4;
8535 				s += 4;
8536 				if (af == 0 && len == 0) {
8537 					end = 1;
8538 					break;
8539 				}
8540 				if (aplen < len)
8541 					break;
8542 				s += len;
8543 				aplen -= len;
8544 			}
8545 			if (end != 1)
8546 				goto cantdecaps;
8547 			hlen = s - (u_char *)fin->fin_dp;
8548 		}
8549 #endif
8550 		break;
8551 
8552 #ifdef IPPROTO_IPIP
8553 	case IPPROTO_IPIP :	/* 4 */
8554 #endif
8555 		nh = IPPROTO_IP;
8556 		break;
8557 
8558 	default :	/* Includes ESP, AH is special for IPv4 */
8559 		goto cantdecaps;
8560 	}
8561 
8562 	switch (nh)
8563 	{
8564 	case IPPROTO_IP :
8565 	case IPPROTO_IPV6 :
8566 		break;
8567 	default :
8568 		goto cantdecaps;
8569 	}
8570 
8571 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8572 	fino = fin;
8573 	fin = &fin2;
8574 	elen = hlen;
8575 #if defined(MENTAT) && defined(_KERNEL)
8576 	m->b_rptr += elen;
8577 #else
8578 	m->m_data += elen;
8579 	m->m_len -= elen;
8580 #endif
8581 	fin->fin_plen -= elen;
8582 
8583 	ip = (ip_t *)((char *)fin->fin_ip + elen);
8584 
8585 	/*
8586 	 * Make sure we have at least enough data for the network layer
8587 	 * header.
8588 	 */
8589 	if (IP_V(ip) == 4)
8590 		hlen = IP_HL(ip) << 2;
8591 #ifdef USE_INET6
8592 	else if (IP_V(ip) == 6)
8593 		hlen = sizeof(ip6_t);
8594 #endif
8595 	else
8596 		goto cantdecaps2;
8597 
8598 	if (fin->fin_plen < hlen)
8599 		goto cantdecaps2;
8600 
8601 	fin->fin_dp = (char *)ip + hlen;
8602 
8603 	if (IP_V(ip) == 4) {
8604 		/*
8605 		 * Perform IPv4 header checksum validation.
8606 		 */
8607 		if (ipf_cksum((u_short *)ip, hlen))
8608 			goto cantdecaps2;
8609 	}
8610 
8611 	if (ipf_makefrip(hlen, ip, fin) == -1) {
8612 cantdecaps2:
8613 		if (m != NULL) {
8614 #if defined(MENTAT) && defined(_KERNEL)
8615 			m->b_rptr -= elen;
8616 #else
8617 			m->m_data -= elen;
8618 			m->m_len += elen;
8619 #endif
8620 		}
8621 cantdecaps:
8622 		DT1(frb_decapfrip, fr_info_t *, fin);
8623 		pass &= ~FR_CMDMASK;
8624 		pass |= FR_BLOCK|FR_QUICK;
8625 		fin->fin_reason = FRB_DECAPFRIP;
8626 		return -1;
8627 	}
8628 
8629 	pass = ipf_scanlist(fin, pass);
8630 
8631 	/*
8632 	 * Copy the packet filter "result" fields out of the fr_info_t struct
8633 	 * that is local to the decapsulation processing and back into the
8634 	 * one we were called with.
8635 	 */
8636 	fino->fin_flx = fin->fin_flx;
8637 	fino->fin_rev = fin->fin_rev;
8638 	fino->fin_icode = fin->fin_icode;
8639 	fino->fin_rule = fin->fin_rule;
8640 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8641 	fino->fin_fr = fin->fin_fr;
8642 	fino->fin_error = fin->fin_error;
8643 	fino->fin_mp = fin->fin_mp;
8644 	fino->fin_m = fin->fin_m;
8645 	m = fin->fin_m;
8646 	if (m != NULL) {
8647 #if defined(MENTAT) && defined(_KERNEL)
8648 		m->b_rptr -= elen;
8649 #else
8650 		m->m_data -= elen;
8651 		m->m_len += elen;
8652 #endif
8653 	}
8654 	return pass;
8655 }
8656 
8657 
8658 /* ------------------------------------------------------------------------ */
8659 /* Function:    ipf_matcharray_load                                         */
8660 /* Returns:     int         - 0 = success, else error                       */
8661 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8662 /*              data(I)     - pointer to ioctl data                         */
8663 /*              objp(I)     - ipfobj_t structure to load data into          */
8664 /*              arrayptr(I) - pointer to location to store array pointer    */
8665 /*                                                                          */
8666 /* This function loads in a mathing array through the ipfobj_t struct that  */
8667 /* describes it.  Sanity checking and array size limitations are enforced   */
8668 /* in this function to prevent userspace from trying to load in something   */
8669 /* that is insanely big.  Once the size of the array is known, the memory   */
8670 /* required is malloc'd and returned through changing *arrayptr.  The       */
8671 /* contents of the array are verified before returning.  Only in the event  */
8672 /* of a successful call is the caller required to free up the malloc area.  */
8673 /* ------------------------------------------------------------------------ */
8674 int
ipf_matcharray_load(softc,data,objp,arrayptr)8675 ipf_matcharray_load(softc, data, objp, arrayptr)
8676 	ipf_main_softc_t *softc;
8677 	caddr_t data;
8678 	ipfobj_t *objp;
8679 	int **arrayptr;
8680 {
8681 	int arraysize, *array, error;
8682 
8683 	*arrayptr = NULL;
8684 
8685 	error = BCOPYIN(data, objp, sizeof(*objp));
8686 	if (error != 0) {
8687 		IPFERROR(116);
8688 		return EFAULT;
8689 	}
8690 
8691 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8692 		IPFERROR(117);
8693 		return EINVAL;
8694 	}
8695 
8696 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8697 	    (objp->ipfo_size > 1024)) {
8698 		IPFERROR(118);
8699 		return EINVAL;
8700 	}
8701 
8702 	arraysize = objp->ipfo_size * sizeof(*array);
8703 	KMALLOCS(array, int *, arraysize);
8704 	if (array == NULL) {
8705 		IPFERROR(119);
8706 		return ENOMEM;
8707 	}
8708 
8709 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8710 	if (error != 0) {
8711 		KFREES(array, arraysize);
8712 		IPFERROR(120);
8713 		return EFAULT;
8714 	}
8715 
8716 	if (ipf_matcharray_verify(array, arraysize) != 0) {
8717 		KFREES(array, arraysize);
8718 		IPFERROR(121);
8719 		return EINVAL;
8720 	}
8721 
8722 	*arrayptr = array;
8723 	return 0;
8724 }
8725 
8726 
8727 /* ------------------------------------------------------------------------ */
8728 /* Function:    ipf_matcharray_verify                                       */
8729 /* Returns:     Nil                                                         */
8730 /* Parameters:  array(I)     - pointer to matching array                    */
8731 /*              arraysize(I) - number of elements in the array              */
8732 /*                                                                          */
8733 /* Verify the contents of a matching array by stepping through each element */
8734 /* in it.  The actual commands in the array are not verified for            */
8735 /* correctness, only that all of the sizes are correctly within limits.     */
8736 /* ------------------------------------------------------------------------ */
8737 int
ipf_matcharray_verify(array,arraysize)8738 ipf_matcharray_verify(array, arraysize)
8739 	int *array, arraysize;
8740 {
8741 	int i, nelem, maxidx;
8742 	ipfexp_t *e;
8743 
8744 	nelem = arraysize / sizeof(*array);
8745 
8746 	/*
8747 	 * Currently, it makes no sense to have an array less than 6
8748 	 * elements long - the initial size at the from, a single operation
8749 	 * (minimum 4 in length) and a trailer, for a total of 6.
8750 	 */
8751 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8752 		return -1;
8753 	}
8754 
8755 	/*
8756 	 * Verify the size of data pointed to by array with how long
8757 	 * the array claims to be itself.
8758 	 */
8759 	if (array[0] * sizeof(*array) != arraysize) {
8760 		return -1;
8761 	}
8762 
8763 	maxidx = nelem - 1;
8764 	/*
8765 	 * The last opcode in this array should be an IPF_EXP_END.
8766 	 */
8767 	if (array[maxidx] != IPF_EXP_END) {
8768 		return -1;
8769 	}
8770 
8771 	for (i = 1; i < maxidx; ) {
8772 		e = (ipfexp_t *)(array + i);
8773 
8774 		/*
8775 		 * The length of the bits to check must be at least 1
8776 		 * (or else there is nothing to comapre with!) and it
8777 		 * cannot exceed the length of the data present.
8778 		 */
8779 		if ((e->ipfe_size < 1 ) ||
8780 		    (e->ipfe_size + i > maxidx)) {
8781 			return -1;
8782 		}
8783 		i += e->ipfe_size;
8784 	}
8785 	return 0;
8786 }
8787 
8788 
8789 /* ------------------------------------------------------------------------ */
8790 /* Function:    ipf_fr_matcharray                                           */
8791 /* Returns:     int      - 0 = match failed, else positive match            */
8792 /* Parameters:  fin(I)   - pointer to packet information                    */
8793 /*              array(I) - pointer to matching array                        */
8794 /*                                                                          */
8795 /* This function is used to apply a matching array against a packet and     */
8796 /* return an indication of whether or not the packet successfully matches   */
8797 /* all of the commands in it.                                               */
8798 /* ------------------------------------------------------------------------ */
8799 static int
ipf_fr_matcharray(fin,array)8800 ipf_fr_matcharray(fin, array)
8801 	fr_info_t *fin;
8802 	int *array;
8803 {
8804 	int i, n, *x, rv, p;
8805 	ipfexp_t *e;
8806 
8807 	rv = 0;
8808 	n = array[0];
8809 	x = array + 1;
8810 
8811 	for (; n > 0; x += 3 + x[3], rv = 0) {
8812 		e = (ipfexp_t *)x;
8813 		if (e->ipfe_cmd == IPF_EXP_END)
8814 			break;
8815 		n -= e->ipfe_size;
8816 
8817 		/*
8818 		 * The upper 16 bits currently store the protocol value.
8819 		 * This is currently used with TCP and UDP port compares and
8820 		 * allows "tcp.port = 80" without requiring an explicit
8821 		 " "ip.pr = tcp" first.
8822 		 */
8823 		p = e->ipfe_cmd >> 16;
8824 		if ((p != 0) && (p != fin->fin_p))
8825 			break;
8826 
8827 		switch (e->ipfe_cmd)
8828 		{
8829 		case IPF_EXP_IP_PR :
8830 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8831 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8832 			}
8833 			break;
8834 
8835 		case IPF_EXP_IP_SRCADDR :
8836 			if (fin->fin_v != 4)
8837 				break;
8838 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8839 				rv |= ((fin->fin_saddr &
8840 					e->ipfe_arg0[i * 2 + 1]) ==
8841 				       e->ipfe_arg0[i * 2]);
8842 			}
8843 			break;
8844 
8845 		case IPF_EXP_IP_DSTADDR :
8846 			if (fin->fin_v != 4)
8847 				break;
8848 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8849 				rv |= ((fin->fin_daddr &
8850 					e->ipfe_arg0[i * 2 + 1]) ==
8851 				       e->ipfe_arg0[i * 2]);
8852 			}
8853 			break;
8854 
8855 		case IPF_EXP_IP_ADDR :
8856 			if (fin->fin_v != 4)
8857 				break;
8858 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8859 				rv |= ((fin->fin_saddr &
8860 					e->ipfe_arg0[i * 2 + 1]) ==
8861 				       e->ipfe_arg0[i * 2]) ||
8862 				      ((fin->fin_daddr &
8863 					e->ipfe_arg0[i * 2 + 1]) ==
8864 				       e->ipfe_arg0[i * 2]);
8865 			}
8866 			break;
8867 
8868 #ifdef USE_INET6
8869 		case IPF_EXP_IP6_SRCADDR :
8870 			if (fin->fin_v != 6)
8871 				break;
8872 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8873 				rv |= IP6_MASKEQ(&fin->fin_src6,
8874 						 &e->ipfe_arg0[i * 8 + 4],
8875 						 &e->ipfe_arg0[i * 8]);
8876 			}
8877 			break;
8878 
8879 		case IPF_EXP_IP6_DSTADDR :
8880 			if (fin->fin_v != 6)
8881 				break;
8882 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8883 				rv |= IP6_MASKEQ(&fin->fin_dst6,
8884 						 &e->ipfe_arg0[i * 8 + 4],
8885 						 &e->ipfe_arg0[i * 8]);
8886 			}
8887 			break;
8888 
8889 		case IPF_EXP_IP6_ADDR :
8890 			if (fin->fin_v != 6)
8891 				break;
8892 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8893 				rv |= IP6_MASKEQ(&fin->fin_src6,
8894 						 &e->ipfe_arg0[i * 8 + 4],
8895 						 &e->ipfe_arg0[i * 8]) ||
8896 				      IP6_MASKEQ(&fin->fin_dst6,
8897 						 &e->ipfe_arg0[i * 8 + 4],
8898 						 &e->ipfe_arg0[i * 8]);
8899 			}
8900 			break;
8901 #endif
8902 
8903 		case IPF_EXP_UDP_PORT :
8904 		case IPF_EXP_TCP_PORT :
8905 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8906 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8907 				      (fin->fin_dport == e->ipfe_arg0[i]);
8908 			}
8909 			break;
8910 
8911 		case IPF_EXP_UDP_SPORT :
8912 		case IPF_EXP_TCP_SPORT :
8913 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8914 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8915 			}
8916 			break;
8917 
8918 		case IPF_EXP_UDP_DPORT :
8919 		case IPF_EXP_TCP_DPORT :
8920 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8921 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8922 			}
8923 			break;
8924 
8925 		case IPF_EXP_TCP_FLAGS :
8926 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8927 				rv |= ((fin->fin_tcpf &
8928 					e->ipfe_arg0[i * 2 + 1]) ==
8929 				       e->ipfe_arg0[i * 2]);
8930 			}
8931 			break;
8932 		}
8933 		rv ^= e->ipfe_not;
8934 
8935 		if (rv == 0)
8936 			break;
8937 	}
8938 
8939 	return rv;
8940 }
8941 
8942 
8943 /* ------------------------------------------------------------------------ */
8944 /* Function:    ipf_queueflush                                              */
8945 /* Returns:     int - number of entries flushed (0 = none)                  */
8946 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8947 /*              deletefn(I) - function to call to delete entry              */
8948 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8949 /*              userqs(I)   - top of the list of user defined timeouts      */
8950 /*                                                                          */
8951 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8952 /* need to try a bit harder to free up some space.  The algorithm used here */
8953 /* split into two parts but both halves have the same goal: to reduce the   */
8954 /* number of connections considered to be "active" to the low watermark.    */
8955 /* There are two steps in doing this:                                       */
8956 /* 1) Remove any TCP connections that are already considered to be "closed" */
8957 /*    but have not yet been removed from the state table.  The two states   */
8958 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8959 /*    candidates for this style of removal.  If freeing up entries in       */
8960 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8961 /*    we do not go on to step 2.                                            */
8962 /*                                                                          */
8963 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8964 /*    they are within the given window we are considering.  Where the       */
8965 /*    window starts and the steps taken to increase its size depend upon    */
8966 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8967 /*    last 30 seconds is not touched.                                       */
8968 /*                                              touched                     */
8969 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8970 /*           |          |        |           |     |     |                  */
8971 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8972 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8973 /*                                                                          */
8974 /* Points to note:                                                          */
8975 /* - tqe_die is the time, in the future, when entries die.                  */
8976 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8977 /*   ticks.                                                                 */
8978 /* - tqe_touched is when the entry was last used by NAT/state               */
8979 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8980 /*   ipf_ticks any given timeout queue and vice versa.                      */
8981 /* - both tqe_die and tqe_touched increase over time                        */
8982 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8983 /*   bottom and therefore the smallest values of each are at the top        */
8984 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8985 /*   queues representing each of the TCP states                             */
8986 /*                                                                          */
8987 /* We start by setting up a maximum range to scan for things to move of     */
8988 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8989 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8990 /* we start again with a new value for "iend" and "istart".  This is        */
8991 /* continued until we either finish the scan of 30 second intervals or the  */
8992 /* low water mark is reached.                                               */
8993 /* ------------------------------------------------------------------------ */
8994 int
ipf_queueflush(softc,deletefn,ipfqs,userqs,activep,size,low)8995 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8996 	ipf_main_softc_t *softc;
8997 	ipftq_delete_fn_t deletefn;
8998 	ipftq_t *ipfqs, *userqs;
8999 	u_int *activep;
9000 	int size, low;
9001 {
9002 	u_long interval, istart, iend;
9003 	ipftq_t *ifq, *ifqnext;
9004 	ipftqent_t *tqe, *tqn;
9005 	int removed = 0;
9006 
9007 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
9008 		tqn = tqe->tqe_next;
9009 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9010 			removed++;
9011 	}
9012 	if ((*activep * 100 / size) > low) {
9013 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
9014 		     ((tqe = tqn) != NULL); ) {
9015 			tqn = tqe->tqe_next;
9016 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9017 				removed++;
9018 		}
9019 	}
9020 
9021 	if ((*activep * 100 / size) <= low) {
9022 		return removed;
9023 	}
9024 
9025 	/*
9026 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
9027 	 *       used then the operations are upgraded to floating point
9028 	 *       and kernels don't like floating point...
9029 	 */
9030 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
9031 		istart = IPF_TTLVAL(86400 * 4);
9032 		interval = IPF_TTLVAL(43200);
9033 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9034 		istart = IPF_TTLVAL(43200);
9035 		interval = IPF_TTLVAL(1800);
9036 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9037 		istart = IPF_TTLVAL(1800);
9038 		interval = IPF_TTLVAL(30);
9039 	} else {
9040 		return 0;
9041 	}
9042 	if (istart > softc->ipf_ticks) {
9043 		if (softc->ipf_ticks - interval < interval)
9044 			istart = interval;
9045 		else
9046 			istart = (softc->ipf_ticks / interval) * interval;
9047 	}
9048 
9049 	iend = softc->ipf_ticks - interval;
9050 
9051 	while ((*activep * 100 / size) > low) {
9052 		u_long try;
9053 
9054 		try = softc->ipf_ticks - istart;
9055 
9056 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9057 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9058 				if (try < tqe->tqe_touched)
9059 					break;
9060 				tqn = tqe->tqe_next;
9061 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9062 					removed++;
9063 			}
9064 		}
9065 
9066 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9067 			ifqnext = ifq->ifq_next;
9068 
9069 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9070 				if (try < tqe->tqe_touched)
9071 					break;
9072 				tqn = tqe->tqe_next;
9073 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9074 					removed++;
9075 			}
9076 		}
9077 
9078 		if (try >= iend) {
9079 			if (interval == IPF_TTLVAL(43200)) {
9080 				interval = IPF_TTLVAL(1800);
9081 			} else if (interval == IPF_TTLVAL(1800)) {
9082 				interval = IPF_TTLVAL(30);
9083 			} else {
9084 				break;
9085 			}
9086 			if (interval >= softc->ipf_ticks)
9087 				break;
9088 
9089 			iend = softc->ipf_ticks - interval;
9090 		}
9091 		istart -= interval;
9092 	}
9093 
9094 	return removed;
9095 }
9096 
9097 
9098 /* ------------------------------------------------------------------------ */
9099 /* Function:    ipf_deliverlocal                                            */
9100 /* Returns:     int - 1 = local address, 0 = non-local address              */
9101 /* Parameters:  softc(I)     - pointer to soft context main structure       */
9102 /*              ipversion(I) - IP protocol version (4 or 6)                 */
9103 /*              ifp(I)       - network interface pointer                    */
9104 /*              ipaddr(I)    - IPv4/6 destination address                   */
9105 /*                                                                          */
9106 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
9107 /* the network interface represented by ifp.                                */
9108 /* ------------------------------------------------------------------------ */
9109 int
ipf_deliverlocal(softc,ipversion,ifp,ipaddr)9110 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9111 	ipf_main_softc_t *softc;
9112 	int ipversion;
9113 	void *ifp;
9114 	i6addr_t *ipaddr;
9115 {
9116 	i6addr_t addr;
9117 	int islocal = 0;
9118 
9119 	if (ipversion == 4) {
9120 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9121 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
9122 				islocal = 1;
9123 		}
9124 
9125 #ifdef USE_INET6
9126 	} else if (ipversion == 6) {
9127 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9128 			if (IP6_EQ(&addr, ipaddr))
9129 				islocal = 1;
9130 		}
9131 #endif
9132 	}
9133 
9134 	return islocal;
9135 }
9136 
9137 
9138 /* ------------------------------------------------------------------------ */
9139 /* Function:    ipf_settimeout                                              */
9140 /* Returns:     int - 0 = success, -1 = failure                             */
9141 /* Parameters:  softc(I) - pointer to soft context main structure           */
9142 /*              t(I)     - pointer to tuneable array entry                  */
9143 /*              p(I)     - pointer to values passed in to apply             */
9144 /*                                                                          */
9145 /* This function is called to set the timeout values for each distinct      */
9146 /* queue timeout that is available.  When called, it calls into both the    */
9147 /* state and NAT code, telling them to update their timeout queues.         */
9148 /* ------------------------------------------------------------------------ */
9149 static int
ipf_settimeout(softc,t,p)9150 ipf_settimeout(softc, t, p)
9151 	struct ipf_main_softc_s *softc;
9152 	ipftuneable_t *t;
9153 	ipftuneval_t *p;
9154 {
9155 
9156 	/*
9157 	 * ipf_interror should be set by the functions called here, not
9158 	 * by this function - it's just a middle man.
9159 	 */
9160 	if (ipf_state_settimeout(softc, t, p) == -1)
9161 		return -1;
9162 	if (ipf_nat_settimeout(softc, t, p) == -1)
9163 		return -1;
9164 	return 0;
9165 }
9166 
9167 
9168 /* ------------------------------------------------------------------------ */
9169 /* Function:    ipf_apply_timeout                                           */
9170 /* Returns:     int - 0 = success, -1 = failure                             */
9171 /* Parameters:  head(I)    - pointer to tuneable array entry                */
9172 /*              seconds(I) - pointer to values passed in to apply           */
9173 /*                                                                          */
9174 /* This function applies a timeout of "seconds" to the timeout queue that   */
9175 /* is pointed to by "head".  All entries on this list have an expiration    */
9176 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
9177 /* function should only be called when the delta is non-zero, the task is   */
9178 /* to walk the entire list and apply the change.  The sort order will not   */
9179 /* change.  The only catch is that this is O(n) across the list, so if the  */
9180 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9181 /* could take a relatively long time to work through them all.              */
9182 /* ------------------------------------------------------------------------ */
9183 void
ipf_apply_timeout(head,seconds)9184 ipf_apply_timeout(head, seconds)
9185 	ipftq_t *head;
9186 	u_int seconds;
9187 {
9188 	u_int oldtimeout, newtimeout;
9189 	ipftqent_t *tqe;
9190 	int delta;
9191 
9192 	MUTEX_ENTER(&head->ifq_lock);
9193 	oldtimeout = head->ifq_ttl;
9194 	newtimeout = IPF_TTLVAL(seconds);
9195 	delta = oldtimeout - newtimeout;
9196 
9197 	head->ifq_ttl = newtimeout;
9198 
9199 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9200 		tqe->tqe_die += delta;
9201 	}
9202 	MUTEX_EXIT(&head->ifq_lock);
9203 }
9204 
9205 
9206 /* ------------------------------------------------------------------------ */
9207 /* Function:   ipf_settimeout_tcp                                           */
9208 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
9209 /* Parameters: t(I)   - pointer to tuneable to change                       */
9210 /*             p(I)   - pointer to new timeout information                  */
9211 /*             tab(I) - pointer to table of TCP queues                      */
9212 /*                                                                          */
9213 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
9214 /* updates all of the entries on the relevant timeout queue by calling      */
9215 /* ipf_apply_timeout().                                                     */
9216 /* ------------------------------------------------------------------------ */
9217 int
ipf_settimeout_tcp(t,p,tab)9218 ipf_settimeout_tcp(t, p, tab)
9219 	ipftuneable_t *t;
9220 	ipftuneval_t *p;
9221 	ipftq_t *tab;
9222 {
9223 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9224 	    !strcmp(t->ipft_name, "tcp_established")) {
9225 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9226 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9227 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9228 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9229 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9230 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9231 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9232 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9233 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9234 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
9235 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9236 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9237 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9238 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
9239 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9240 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9241 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9242 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9243 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9244 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
9245 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9246 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9247 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9248 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9249 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9250 	} else {
9251 		/*
9252 		 * ipf_interror isn't set here because it should be set
9253 		 * by whatever called this function.
9254 		 */
9255 		return -1;
9256 	}
9257 	return 0;
9258 }
9259 
9260 
9261 /* ------------------------------------------------------------------------ */
9262 /* Function:   ipf_main_soft_create                                         */
9263 /* Returns:    NULL = failure, else success                                 */
9264 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9265 /*                                                                          */
9266 /* Create the foundation soft context structure. In circumstances where it  */
9267 /* is not required to dynamically allocate the context, a pointer can be    */
9268 /* passed in (rather than NULL) to a structure to be initialised.           */
9269 /* The main thing of interest is that a number of locks are initialised     */
9270 /* here instead of in the where might be expected - in the relevant create  */
9271 /* function elsewhere.  This is done because the current locking design has */
9272 /* some areas where these locks are used outside of their module.           */
9273 /* Possibly the most important exercise that is done here is setting of all */
9274 /* the timeout values, allowing them to be changed before init().           */
9275 /* ------------------------------------------------------------------------ */
9276 void *
ipf_main_soft_create(arg)9277 ipf_main_soft_create(arg)
9278 	void *arg;
9279 {
9280 	ipf_main_softc_t *softc;
9281 
9282 	if (arg == NULL) {
9283 		KMALLOC(softc, ipf_main_softc_t *);
9284 		if (softc == NULL)
9285 			return NULL;
9286 	} else {
9287 		softc = arg;
9288 	}
9289 
9290 	bzero((char *)softc, sizeof(*softc));
9291 
9292 	/*
9293 	 * This serves as a flag as to whether or not the softc should be
9294 	 * free'd when _destroy is called.
9295 	 */
9296 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9297 
9298 	softc->ipf_tuners = ipf_tune_array_copy(softc,
9299 						sizeof(ipf_main_tuneables),
9300 						ipf_main_tuneables);
9301 	if (softc->ipf_tuners == NULL) {
9302 		ipf_main_soft_destroy(softc);
9303 		return NULL;
9304 	}
9305 
9306 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9307 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9308 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9309 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9310 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9311 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9312 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9313 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9314 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9315 
9316 	softc->ipf_token_head = NULL;
9317 	softc->ipf_token_tail = &softc->ipf_token_head;
9318 
9319 	softc->ipf_tcpidletimeout = FIVE_DAYS;
9320 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9321 	softc->ipf_tcplastack = IPF_TTLVAL(30);
9322 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9323 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9324 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9325 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9326 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9327 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9328 	softc->ipf_udptimeout = IPF_TTLVAL(120);
9329 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9330 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9331 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9332 	softc->ipf_iptimeout = IPF_TTLVAL(60);
9333 
9334 #if defined(IPFILTER_DEFAULT_BLOCK)
9335 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9336 #else
9337 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9338 #endif
9339 	softc->ipf_minttl = 4;
9340 	softc->ipf_icmpminfragmtu = 68;
9341 	softc->ipf_flags = IPF_LOGGING;
9342 
9343 	return softc;
9344 }
9345 
9346 /* ------------------------------------------------------------------------ */
9347 /* Function:   ipf_main_soft_init                                           */
9348 /* Returns:    0 = success, -1 = failure                                    */
9349 /* Parameters: softc(I) - pointer to soft context main structure            */
9350 /*                                                                          */
9351 /* A null-op function that exists as a placeholder so that the flow in      */
9352 /* other functions is obvious.                                              */
9353 /* ------------------------------------------------------------------------ */
9354 /*ARGSUSED*/
9355 int
ipf_main_soft_init(softc)9356 ipf_main_soft_init(softc)
9357 	ipf_main_softc_t *softc;
9358 {
9359 	return 0;
9360 }
9361 
9362 
9363 /* ------------------------------------------------------------------------ */
9364 /* Function:   ipf_main_soft_destroy                                        */
9365 /* Returns:    void                                                         */
9366 /* Parameters: softc(I) - pointer to soft context main structure            */
9367 /*                                                                          */
9368 /* Undo everything that we did in ipf_main_soft_create.                     */
9369 /*                                                                          */
9370 /* The most important check that needs to be made here is whether or not    */
9371 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9372 /* value is stored in ipf_dynamic_main.                                     */
9373 /* ------------------------------------------------------------------------ */
9374 /*ARGSUSED*/
9375 void
ipf_main_soft_destroy(softc)9376 ipf_main_soft_destroy(softc)
9377 	ipf_main_softc_t *softc;
9378 {
9379 
9380 	RW_DESTROY(&softc->ipf_frag);
9381 	RW_DESTROY(&softc->ipf_poolrw);
9382 	RW_DESTROY(&softc->ipf_nat);
9383 	RW_DESTROY(&softc->ipf_state);
9384 	RW_DESTROY(&softc->ipf_tokens);
9385 	RW_DESTROY(&softc->ipf_mutex);
9386 	RW_DESTROY(&softc->ipf_global);
9387 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9388 	MUTEX_DESTROY(&softc->ipf_rw);
9389 
9390 	if (softc->ipf_tuners != NULL) {
9391 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9392 	}
9393 	if (softc->ipf_dynamic_softc == 1) {
9394 		KFREE(softc);
9395 	}
9396 }
9397 
9398 
9399 /* ------------------------------------------------------------------------ */
9400 /* Function:   ipf_main_soft_fini                                           */
9401 /* Returns:    0 = success, -1 = failure                                    */
9402 /* Parameters: softc(I) - pointer to soft context main structure            */
9403 /*                                                                          */
9404 /* Clean out the rules which have been added since _init was last called,   */
9405 /* the only dynamic part of the mainline.                                   */
9406 /* ------------------------------------------------------------------------ */
9407 int
ipf_main_soft_fini(softc)9408 ipf_main_soft_fini(softc)
9409 	ipf_main_softc_t *softc;
9410 {
9411 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9412 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9413 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9414 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9415 
9416 	return 0;
9417 }
9418 
9419 
9420 /* ------------------------------------------------------------------------ */
9421 /* Function:   ipf_main_load                                                */
9422 /* Returns:    0 = success, -1 = failure                                    */
9423 /* Parameters: none                                                         */
9424 /*                                                                          */
9425 /* Handle global initialisation that needs to be done for the base part of  */
9426 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9427 /* arrays that get used by the state/NAT code.                              */
9428 /* ------------------------------------------------------------------------ */
9429 int
ipf_main_load()9430 ipf_main_load()
9431 {
9432 	int i;
9433 
9434 	/* fill icmp reply type table */
9435 	for (i = 0; i <= ICMP_MAXTYPE; i++)
9436 		icmpreplytype4[i] = -1;
9437 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9438 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9439 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9440 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9441 
9442 #ifdef  USE_INET6
9443 	/* fill icmp reply type table */
9444 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9445 		icmpreplytype6[i] = -1;
9446 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9447 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9448 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9449 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9450 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9451 #endif
9452 
9453 	return 0;
9454 }
9455 
9456 
9457 /* ------------------------------------------------------------------------ */
9458 /* Function:   ipf_main_unload                                              */
9459 /* Returns:    0 = success, -1 = failure                                    */
9460 /* Parameters: none                                                         */
9461 /*                                                                          */
9462 /* A null-op function that exists as a placeholder so that the flow in      */
9463 /* other functions is obvious.                                              */
9464 /* ------------------------------------------------------------------------ */
9465 int
ipf_main_unload()9466 ipf_main_unload()
9467 {
9468 	return 0;
9469 }
9470 
9471 
9472 /* ------------------------------------------------------------------------ */
9473 /* Function:   ipf_load_all                                                 */
9474 /* Returns:    0 = success, -1 = failure                                    */
9475 /* Parameters: none                                                         */
9476 /*                                                                          */
9477 /* Work through all of the subsystems inside IPFilter and call the load     */
9478 /* function for each in an order that won't lead to a crash :)              */
9479 /* ------------------------------------------------------------------------ */
9480 int
ipf_load_all()9481 ipf_load_all()
9482 {
9483 	if (ipf_main_load() == -1)
9484 		return -1;
9485 
9486 	if (ipf_state_main_load() == -1)
9487 		return -1;
9488 
9489 	if (ipf_nat_main_load() == -1)
9490 		return -1;
9491 
9492 	if (ipf_frag_main_load() == -1)
9493 		return -1;
9494 
9495 	if (ipf_auth_main_load() == -1)
9496 		return -1;
9497 
9498 	if (ipf_proxy_main_load() == -1)
9499 		return -1;
9500 
9501 	return 0;
9502 }
9503 
9504 
9505 /* ------------------------------------------------------------------------ */
9506 /* Function:   ipf_unload_all                                               */
9507 /* Returns:    0 = success, -1 = failure                                    */
9508 /* Parameters: none                                                         */
9509 /*                                                                          */
9510 /* Work through all of the subsystems inside IPFilter and call the unload   */
9511 /* function for each in an order that won't lead to a crash :)              */
9512 /* ------------------------------------------------------------------------ */
9513 int
ipf_unload_all()9514 ipf_unload_all()
9515 {
9516 	if (ipf_proxy_main_unload() == -1)
9517 		return -1;
9518 
9519 	if (ipf_auth_main_unload() == -1)
9520 		return -1;
9521 
9522 	if (ipf_frag_main_unload() == -1)
9523 		return -1;
9524 
9525 	if (ipf_nat_main_unload() == -1)
9526 		return -1;
9527 
9528 	if (ipf_state_main_unload() == -1)
9529 		return -1;
9530 
9531 	if (ipf_main_unload() == -1)
9532 		return -1;
9533 
9534 	return 0;
9535 }
9536 
9537 
9538 /* ------------------------------------------------------------------------ */
9539 /* Function:   ipf_create_all                                               */
9540 /* Returns:    NULL = failure, else success                                 */
9541 /* Parameters: arg(I) - pointer to soft context main structure              */
9542 /*                                                                          */
9543 /* Work through all of the subsystems inside IPFilter and call the create   */
9544 /* function for each in an order that won't lead to a crash :)              */
9545 /* ------------------------------------------------------------------------ */
9546 ipf_main_softc_t *
ipf_create_all(arg)9547 ipf_create_all(arg)
9548 	void *arg;
9549 {
9550 	ipf_main_softc_t *softc;
9551 
9552 	softc = ipf_main_soft_create(arg);
9553 	if (softc == NULL)
9554 		return NULL;
9555 
9556 #ifdef IPFILTER_LOG
9557 	softc->ipf_log_soft = ipf_log_soft_create(softc);
9558 	if (softc->ipf_log_soft == NULL) {
9559 		ipf_destroy_all(softc);
9560 		return NULL;
9561 	}
9562 #endif
9563 
9564 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9565 	if (softc->ipf_lookup_soft == NULL) {
9566 		ipf_destroy_all(softc);
9567 		return NULL;
9568 	}
9569 
9570 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9571 	if (softc->ipf_sync_soft == NULL) {
9572 		ipf_destroy_all(softc);
9573 		return NULL;
9574 	}
9575 
9576 	softc->ipf_state_soft = ipf_state_soft_create(softc);
9577 	if (softc->ipf_state_soft == NULL) {
9578 		ipf_destroy_all(softc);
9579 		return NULL;
9580 	}
9581 
9582 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9583 	if (softc->ipf_nat_soft == NULL) {
9584 		ipf_destroy_all(softc);
9585 		return NULL;
9586 	}
9587 
9588 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9589 	if (softc->ipf_frag_soft == NULL) {
9590 		ipf_destroy_all(softc);
9591 		return NULL;
9592 	}
9593 
9594 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9595 	if (softc->ipf_auth_soft == NULL) {
9596 		ipf_destroy_all(softc);
9597 		return NULL;
9598 	}
9599 
9600 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9601 	if (softc->ipf_proxy_soft == NULL) {
9602 		ipf_destroy_all(softc);
9603 		return NULL;
9604 	}
9605 
9606 	return softc;
9607 }
9608 
9609 
9610 /* ------------------------------------------------------------------------ */
9611 /* Function:   ipf_destroy_all                                              */
9612 /* Returns:    void                                                         */
9613 /* Parameters: softc(I) - pointer to soft context main structure            */
9614 /*                                                                          */
9615 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9616 /* function for each in an order that won't lead to a crash :)              */
9617 /*                                                                          */
9618 /* Every one of these functions is expected to succeed, so there is no      */
9619 /* checking of return values.                                               */
9620 /* ------------------------------------------------------------------------ */
9621 void
ipf_destroy_all(softc)9622 ipf_destroy_all(softc)
9623 	ipf_main_softc_t *softc;
9624 {
9625 
9626 	if (softc->ipf_state_soft != NULL) {
9627 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9628 		softc->ipf_state_soft = NULL;
9629 	}
9630 
9631 	if (softc->ipf_nat_soft != NULL) {
9632 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9633 		softc->ipf_nat_soft = NULL;
9634 	}
9635 
9636 	if (softc->ipf_frag_soft != NULL) {
9637 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9638 		softc->ipf_frag_soft = NULL;
9639 	}
9640 
9641 	if (softc->ipf_auth_soft != NULL) {
9642 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9643 		softc->ipf_auth_soft = NULL;
9644 	}
9645 
9646 	if (softc->ipf_proxy_soft != NULL) {
9647 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9648 		softc->ipf_proxy_soft = NULL;
9649 	}
9650 
9651 	if (softc->ipf_sync_soft != NULL) {
9652 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9653 		softc->ipf_sync_soft = NULL;
9654 	}
9655 
9656 	if (softc->ipf_lookup_soft != NULL) {
9657 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9658 		softc->ipf_lookup_soft = NULL;
9659 	}
9660 
9661 #ifdef IPFILTER_LOG
9662 	if (softc->ipf_log_soft != NULL) {
9663 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9664 		softc->ipf_log_soft = NULL;
9665 	}
9666 #endif
9667 
9668 	ipf_main_soft_destroy(softc);
9669 }
9670 
9671 
9672 /* ------------------------------------------------------------------------ */
9673 /* Function:   ipf_init_all                                                 */
9674 /* Returns:    0 = success, -1 = failure                                    */
9675 /* Parameters: softc(I) - pointer to soft context main structure            */
9676 /*                                                                          */
9677 /* Work through all of the subsystems inside IPFilter and call the init     */
9678 /* function for each in an order that won't lead to a crash :)              */
9679 /* ------------------------------------------------------------------------ */
9680 int
ipf_init_all(softc)9681 ipf_init_all(softc)
9682 	ipf_main_softc_t *softc;
9683 {
9684 
9685 	if (ipf_main_soft_init(softc) == -1)
9686 		return -1;
9687 
9688 #ifdef IPFILTER_LOG
9689 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9690 		return -1;
9691 #endif
9692 
9693 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9694 		return -1;
9695 
9696 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9697 		return -1;
9698 
9699 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9700 		return -1;
9701 
9702 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9703 		return -1;
9704 
9705 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9706 		return -1;
9707 
9708 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9709 		return -1;
9710 
9711 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9712 		return -1;
9713 
9714 	return 0;
9715 }
9716 
9717 
9718 /* ------------------------------------------------------------------------ */
9719 /* Function:   ipf_fini_all                                                 */
9720 /* Returns:    0 = success, -1 = failure                                    */
9721 /* Parameters: softc(I) - pointer to soft context main structure            */
9722 /*                                                                          */
9723 /* Work through all of the subsystems inside IPFilter and call the fini     */
9724 /* function for each in an order that won't lead to a crash :)              */
9725 /* ------------------------------------------------------------------------ */
9726 int
ipf_fini_all(softc)9727 ipf_fini_all(softc)
9728 	ipf_main_softc_t *softc;
9729 {
9730 
9731 	ipf_token_flush(softc);
9732 
9733 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9734 		return -1;
9735 
9736 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9737 		return -1;
9738 
9739 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9740 		return -1;
9741 
9742 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9743 		return -1;
9744 
9745 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9746 		return -1;
9747 
9748 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9749 		return -1;
9750 
9751 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9752 		return -1;
9753 
9754 #ifdef IPFILTER_LOG
9755 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9756 		return -1;
9757 #endif
9758 
9759 	if (ipf_main_soft_fini(softc) == -1)
9760 		return -1;
9761 
9762 	return 0;
9763 }
9764 
9765 
9766 /* ------------------------------------------------------------------------ */
9767 /* Function:    ipf_rule_expire                                             */
9768 /* Returns:     Nil                                                         */
9769 /* Parameters:  softc(I) - pointer to soft context main structure           */
9770 /*                                                                          */
9771 /* At present this function exists just to support temporary addition of    */
9772 /* firewall rules. Both inactive and active lists are scanned for items to  */
9773 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9774 /* loaded in.                                                               */
9775 /* ------------------------------------------------------------------------ */
9776 void
ipf_rule_expire(softc)9777 ipf_rule_expire(softc)
9778 	ipf_main_softc_t *softc;
9779 {
9780 	frentry_t *fr;
9781 
9782 	if ((softc->ipf_rule_explist[0] == NULL) &&
9783 	    (softc->ipf_rule_explist[1] == NULL))
9784 		return;
9785 
9786 	WRITE_ENTER(&softc->ipf_mutex);
9787 
9788 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9789 		/*
9790 		 * Because the list is kept sorted on insertion, the fist
9791 		 * one that dies in the future means no more work to do.
9792 		 */
9793 		if (fr->fr_die > softc->ipf_ticks)
9794 			break;
9795 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9796 	}
9797 
9798 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9799 		/*
9800 		 * Because the list is kept sorted on insertion, the fist
9801 		 * one that dies in the future means no more work to do.
9802 		 */
9803 		if (fr->fr_die > softc->ipf_ticks)
9804 			break;
9805 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9806 	}
9807 
9808 	RWLOCK_EXIT(&softc->ipf_mutex);
9809 }
9810 
9811 
9812 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9813 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9814 				      i6addr_t *));
9815 
9816 host_node_t RBI_ZERO(ipf_rb);
9817 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9818 
9819 
9820 /* ------------------------------------------------------------------------ */
9821 /* Function:    ipf_ht_node_cmp                                             */
9822 /* Returns:     int   - 0 == nodes are the same, ..                         */
9823 /* Parameters:  k1(I) - pointer to first key to compare                     */
9824 /*              k2(I) - pointer to second key to compare                    */
9825 /*                                                                          */
9826 /* The "key" for the node is a combination of two fields: the address       */
9827 /* family and the address itself.                                           */
9828 /*                                                                          */
9829 /* Because we're not actually interpreting the address data, it isn't       */
9830 /* necessary to convert them to/from network/host byte order. The mask is   */
9831 /* just used to remove bits that aren't significant - it doesn't matter     */
9832 /* where they are, as long as they're always in the same place.             */
9833 /*                                                                          */
9834 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9835 /* this is where individual ones will differ the most - but not true for    */
9836 /* for /48's, etc.                                                          */
9837 /* ------------------------------------------------------------------------ */
9838 static int
9839 ipf_ht_node_cmp(k1, k2)
9840 	struct host_node_s *k1, *k2;
9841 {
9842 	int i;
9843 
9844 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9845 	if (i != 0)
9846 		return i;
9847 
9848 	if (k1->hn_addr.adf_family == AF_INET)
9849 		return (k2->hn_addr.adf_addr.in4.s_addr -
9850 			k1->hn_addr.adf_addr.in4.s_addr);
9851 
9852 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9853 	if (i != 0)
9854 		return i;
9855 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9856 	if (i != 0)
9857 		return i;
9858 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9859 	if (i != 0)
9860 		return i;
9861 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9862 	return i;
9863 }
9864 
9865 
9866 /* ------------------------------------------------------------------------ */
9867 /* Function:    ipf_ht_node_make_key                                        */
9868 /* Returns:     Nil                                                         */
9869 /* parameters:  htp(I)    - pointer to address tracking structure           */
9870 /*              key(I)    - where to store masked address for lookup        */
9871 /*              family(I) - protocol family of address                      */
9872 /*              addr(I)   - pointer to network address                      */
9873 /*                                                                          */
9874 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9875 /* copy the address passed in into the key structure whilst masking out the */
9876 /* bits that we don't want.                                                 */
9877 /*                                                                          */
9878 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9879 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9880 /* have to be wary of that and not allow 32-128 to happen.                  */
9881 /* ------------------------------------------------------------------------ */
9882 static void
ipf_ht_node_make_key(htp,key,family,addr)9883 ipf_ht_node_make_key(htp, key, family, addr)
9884 	host_track_t *htp;
9885 	host_node_t *key;
9886 	int family;
9887 	i6addr_t *addr;
9888 {
9889 	key->hn_addr.adf_family = family;
9890 	if (family == AF_INET) {
9891 		u_32_t mask;
9892 		int bits;
9893 
9894 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9895 		bits = htp->ht_netmask;
9896 		if (bits >= 32) {
9897 			mask = 0xffffffff;
9898 		} else {
9899 			mask = htonl(0xffffffff << (32 - bits));
9900 		}
9901 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9902 #ifdef USE_INET6
9903 	} else {
9904 		int bits = htp->ht_netmask;
9905 
9906 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9907 		if (bits > 96) {
9908 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9909 					     htonl(0xffffffff << (128 - bits));
9910 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9911 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9912 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9913 		} else if (bits > 64) {
9914 			key->hn_addr.adf_addr.i6[3] = 0;
9915 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9916 					     htonl(0xffffffff << (96 - bits));
9917 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9918 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9919 		} else if (bits > 32) {
9920 			key->hn_addr.adf_addr.i6[3] = 0;
9921 			key->hn_addr.adf_addr.i6[2] = 0;
9922 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9923 					     htonl(0xffffffff << (64 - bits));
9924 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9925 		} else {
9926 			key->hn_addr.adf_addr.i6[3] = 0;
9927 			key->hn_addr.adf_addr.i6[2] = 0;
9928 			key->hn_addr.adf_addr.i6[1] = 0;
9929 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9930 					     htonl(0xffffffff << (32 - bits));
9931 		}
9932 #endif
9933 	}
9934 }
9935 
9936 
9937 /* ------------------------------------------------------------------------ */
9938 /* Function:    ipf_ht_node_add                                             */
9939 /* Returns:     int       - 0 == success,  -1 == failure                    */
9940 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9941 /*              htp(I)    - pointer to address tracking structure           */
9942 /*              family(I) - protocol family of address                      */
9943 /*              addr(I)   - pointer to network address                      */
9944 /*                                                                          */
9945 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9946 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9947 /*                                                                          */
9948 /* After preparing the key with the address information to find, look in    */
9949 /* the red-black tree to see if the address is known. A successful call to  */
9950 /* this function can mean one of two things: a new node was added to the    */
9951 /* tree or a matching node exists and we're able to bump up its activity.   */
9952 /* ------------------------------------------------------------------------ */
9953 int
ipf_ht_node_add(softc,htp,family,addr)9954 ipf_ht_node_add(softc, htp, family, addr)
9955 	ipf_main_softc_t *softc;
9956 	host_track_t *htp;
9957 	int family;
9958 	i6addr_t *addr;
9959 {
9960 	host_node_t *h;
9961 	host_node_t k;
9962 
9963 	ipf_ht_node_make_key(htp, &k, family, addr);
9964 
9965 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9966 	if (h == NULL) {
9967 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9968 			return -1;
9969 		KMALLOC(h, host_node_t *);
9970 		if (h == NULL) {
9971 			DT(ipf_rb_no_mem);
9972 			LBUMP(ipf_rb_no_mem);
9973 			return -1;
9974 		}
9975 
9976 		/*
9977 		 * If there was a macro to initialise the RB node then that
9978 		 * would get used here, but there isn't...
9979 		 */
9980 		bzero((char *)h, sizeof(*h));
9981 		h->hn_addr = k.hn_addr;
9982 		h->hn_addr.adf_family = k.hn_addr.adf_family;
9983 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9984 		htp->ht_cur_nodes++;
9985 	} else {
9986 		if ((htp->ht_max_per_node != 0) &&
9987 		    (h->hn_active >= htp->ht_max_per_node)) {
9988 			DT(ipf_rb_node_max);
9989 			LBUMP(ipf_rb_node_max);
9990 			return -1;
9991 		}
9992 	}
9993 
9994 	h->hn_active++;
9995 
9996 	return 0;
9997 }
9998 
9999 
10000 /* ------------------------------------------------------------------------ */
10001 /* Function:    ipf_ht_node_del                                             */
10002 /* Returns:     int       - 0 == success,  -1 == failure                    */
10003 /* parameters:  htp(I)    - pointer to address tracking structure           */
10004 /*              family(I) - protocol family of address                      */
10005 /*              addr(I)   - pointer to network address                      */
10006 /*                                                                          */
10007 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
10008 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
10009 /*                                                                          */
10010 /* Try and find the address passed in amongst the leavese on this tree to   */
10011 /* be friend. If found then drop the active account for that node drops by  */
10012 /* one. If that count reaches 0, it is time to free it all up.              */
10013 /* ------------------------------------------------------------------------ */
10014 int
ipf_ht_node_del(htp,family,addr)10015 ipf_ht_node_del(htp, family, addr)
10016 	host_track_t *htp;
10017 	int family;
10018 	i6addr_t *addr;
10019 {
10020 	host_node_t *h;
10021 	host_node_t k;
10022 
10023 	ipf_ht_node_make_key(htp, &k, family, addr);
10024 
10025 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
10026 	if (h == NULL) {
10027 		return -1;
10028 	} else {
10029 		h->hn_active--;
10030 		if (h->hn_active == 0) {
10031 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10032 			htp->ht_cur_nodes--;
10033 			KFREE(h);
10034 		}
10035 	}
10036 
10037 	return 0;
10038 }
10039 
10040 
10041 /* ------------------------------------------------------------------------ */
10042 /* Function:    ipf_rb_ht_init                                              */
10043 /* Returns:     Nil                                                         */
10044 /* Parameters:  head(I) - pointer to host tracking structure                */
10045 /*                                                                          */
10046 /* Initialise the host tracking structure to be ready for use above.        */
10047 /* ------------------------------------------------------------------------ */
10048 void
ipf_rb_ht_init(head)10049 ipf_rb_ht_init(head)
10050 	host_track_t *head;
10051 {
10052 	RBI_INIT(ipf_rb, &head->ht_root);
10053 }
10054 
10055 
10056 /* ------------------------------------------------------------------------ */
10057 /* Function:    ipf_rb_ht_freenode                                          */
10058 /* Returns:     Nil                                                         */
10059 /* Parameters:  head(I) - pointer to host tracking structure                */
10060 /*              arg(I)  - additional argument from walk caller              */
10061 /*                                                                          */
10062 /* Free an actual host_node_t structure.                                    */
10063 /* ------------------------------------------------------------------------ */
10064 void
ipf_rb_ht_freenode(node,arg)10065 ipf_rb_ht_freenode(node, arg)
10066 	host_node_t *node;
10067 	void *arg;
10068 {
10069 	KFREE(node);
10070 }
10071 
10072 
10073 /* ------------------------------------------------------------------------ */
10074 /* Function:    ipf_rb_ht_flush                                             */
10075 /* Returns:     Nil                                                         */
10076 /* Parameters:  head(I) - pointer to host tracking structure                */
10077 /*                                                                          */
10078 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10079 /* and free'ing each one.                                                   */
10080 /* ------------------------------------------------------------------------ */
10081 void
ipf_rb_ht_flush(head)10082 ipf_rb_ht_flush(head)
10083 	host_track_t *head;
10084 {
10085 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10086 }
10087 
10088 
10089 /* ------------------------------------------------------------------------ */
10090 /* Function:    ipf_slowtimer                                               */
10091 /* Returns:     Nil                                                         */
10092 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10093 /*                                                                          */
10094 /* Slowly expire held state for fragments.  Timeouts are set * in           */
10095 /* expectation of this being called twice per second.                       */
10096 /* ------------------------------------------------------------------------ */
10097 void
ipf_slowtimer(softc)10098 ipf_slowtimer(softc)
10099 	ipf_main_softc_t *softc;
10100 {
10101 
10102 	ipf_token_expire(softc);
10103 	ipf_frag_expire(softc);
10104 	ipf_state_expire(softc);
10105 	ipf_nat_expire(softc);
10106 	ipf_auth_expire(softc);
10107 	ipf_lookup_expire(softc);
10108 	ipf_rule_expire(softc);
10109 	ipf_sync_expire(softc);
10110 	softc->ipf_ticks++;
10111 }
10112 
10113 
10114 /* ------------------------------------------------------------------------ */
10115 /* Function:    ipf_inet_mask_add                                           */
10116 /* Returns:     Nil                                                         */
10117 /* Parameters:  bits(I) - pointer to nat context information                */
10118 /*              mtab(I) - pointer to mask hash table structure              */
10119 /*                                                                          */
10120 /* When called, bits represents the mask of a new NAT rule that has just    */
10121 /* been added. This function inserts a bitmask into the array of masks to   */
10122 /* search when searching for a matching NAT rule for a packet.              */
10123 /* Prevention of duplicate masks is achieved by checking the use count for  */
10124 /* a given netmask.                                                         */
10125 /* ------------------------------------------------------------------------ */
10126 void
ipf_inet_mask_add(bits,mtab)10127 ipf_inet_mask_add(bits, mtab)
10128 	int bits;
10129 	ipf_v4_masktab_t *mtab;
10130 {
10131 	u_32_t mask;
10132 	int i, j;
10133 
10134 	mtab->imt4_masks[bits]++;
10135 	if (mtab->imt4_masks[bits] > 1)
10136 		return;
10137 
10138 	if (bits == 0)
10139 		mask = 0;
10140 	else
10141 		mask = 0xffffffff << (32 - bits);
10142 
10143 	for (i = 0; i < 33; i++) {
10144 		if (ntohl(mtab->imt4_active[i]) < mask) {
10145 			for (j = 32; j > i; j--)
10146 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10147 			mtab->imt4_active[i] = htonl(mask);
10148 			break;
10149 		}
10150 	}
10151 	mtab->imt4_max++;
10152 }
10153 
10154 
10155 /* ------------------------------------------------------------------------ */
10156 /* Function:    ipf_inet_mask_del                                           */
10157 /* Returns:     Nil                                                         */
10158 /* Parameters:  bits(I) - number of bits set in the netmask                 */
10159 /*              mtab(I) - pointer to mask hash table structure              */
10160 /*                                                                          */
10161 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
10162 /* netmasks stored inside of mtab.                                          */
10163 /* ------------------------------------------------------------------------ */
10164 void
ipf_inet_mask_del(bits,mtab)10165 ipf_inet_mask_del(bits, mtab)
10166 	int bits;
10167 	ipf_v4_masktab_t *mtab;
10168 {
10169 	u_32_t mask;
10170 	int i, j;
10171 
10172 	mtab->imt4_masks[bits]--;
10173 	if (mtab->imt4_masks[bits] > 0)
10174 		return;
10175 
10176 	mask = htonl(0xffffffff << (32 - bits));
10177 	for (i = 0; i < 33; i++) {
10178 		if (mtab->imt4_active[i] == mask) {
10179 			for (j = i + 1; j < 33; j++)
10180 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10181 			break;
10182 		}
10183 	}
10184 	mtab->imt4_max--;
10185 	ASSERT(mtab->imt4_max >= 0);
10186 }
10187 
10188 
10189 #ifdef USE_INET6
10190 /* ------------------------------------------------------------------------ */
10191 /* Function:    ipf_inet6_mask_add                                          */
10192 /* Returns:     Nil                                                         */
10193 /* Parameters:  bits(I) - number of bits set in mask                        */
10194 /*              mask(I) - pointer to mask to add                            */
10195 /*              mtab(I) - pointer to mask hash table structure              */
10196 /*                                                                          */
10197 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10198 /* has just been added. This function inserts a bitmask into the array of   */
10199 /* masks to search when searching for a matching NAT rule for a packet.     */
10200 /* Prevention of duplicate masks is achieved by checking the use count for  */
10201 /* a given netmask.                                                         */
10202 /* ------------------------------------------------------------------------ */
10203 void
ipf_inet6_mask_add(bits,mask,mtab)10204 ipf_inet6_mask_add(bits, mask, mtab)
10205 	int bits;
10206 	i6addr_t *mask;
10207 	ipf_v6_masktab_t *mtab;
10208 {
10209 	i6addr_t zero;
10210 	int i, j;
10211 
10212 	mtab->imt6_masks[bits]++;
10213 	if (mtab->imt6_masks[bits] > 1)
10214 		return;
10215 
10216 	if (bits == 0) {
10217 		mask = &zero;
10218 		zero.i6[0] = 0;
10219 		zero.i6[1] = 0;
10220 		zero.i6[2] = 0;
10221 		zero.i6[3] = 0;
10222 	}
10223 
10224 	for (i = 0; i < 129; i++) {
10225 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
10226 			for (j = 128; j > i; j--)
10227 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10228 			mtab->imt6_active[i] = *mask;
10229 			break;
10230 		}
10231 	}
10232 	mtab->imt6_max++;
10233 }
10234 
10235 
10236 /* ------------------------------------------------------------------------ */
10237 /* Function:    ipf_inet6_mask_del                                          */
10238 /* Returns:     Nil                                                         */
10239 /* Parameters:  bits(I) - number of bits set in mask                        */
10240 /*              mask(I) - pointer to mask to remove                         */
10241 /*              mtab(I) - pointer to mask hash table structure              */
10242 /*                                                                          */
10243 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
10244 /* netmasks stored inside of mtab.                                          */
10245 /* ------------------------------------------------------------------------ */
10246 void
ipf_inet6_mask_del(bits,mask,mtab)10247 ipf_inet6_mask_del(bits, mask, mtab)
10248 	int bits;
10249 	i6addr_t *mask;
10250 	ipf_v6_masktab_t *mtab;
10251 {
10252 	i6addr_t zero;
10253 	int i, j;
10254 
10255 	mtab->imt6_masks[bits]--;
10256 	if (mtab->imt6_masks[bits] > 0)
10257 		return;
10258 
10259 	if (bits == 0)
10260 		mask = &zero;
10261 	zero.i6[0] = 0;
10262 	zero.i6[1] = 0;
10263 	zero.i6[2] = 0;
10264 	zero.i6[3] = 0;
10265 
10266 	for (i = 0; i < 129; i++) {
10267 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10268 			for (j = i + 1; j < 129; j++) {
10269 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10270 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10271 					break;
10272 			}
10273 			break;
10274 		}
10275 	}
10276 	mtab->imt6_max--;
10277 	ASSERT(mtab->imt6_max >= 0);
10278 }
10279 #endif
10280