xref: /netbsd/sys/external/bsd/ipf/netinet/fil.c (revision 547f654f)
1 /*	$NetBSD: fil.c,v 1.37 2023/06/24 05:16:15 msaitoh Exp $	*/
2 
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $
9  *
10  */
11 #if defined(KERNEL) || defined(_KERNEL)
12 # undef KERNEL
13 # undef _KERNEL
14 # define        KERNEL	1
15 # define        _KERNEL	1
16 #endif
17 #include <sys/errno.h>
18 #include <sys/types.h>
19 #include <sys/param.h>
20 #include <sys/time.h>
21 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
22     (__FreeBSD_version >= 220000)
23 # if (__FreeBSD_version >= 400000)
24 #  if !defined(IPFILTER_LKM)
25 #   include "opt_inet6.h"
26 #  endif
27 #  if (__FreeBSD_version == 400019)
28 #   define CSUM_DELAY_DATA
29 #  endif
30 # endif
31 # include <sys/filio.h>
32 #else
33 # include <sys/ioctl.h>
34 #endif
35 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
36 # include <sys/filio.h>
37 #endif
38 #if !defined(_AIX51)
39 # include <sys/fcntl.h>
40 #endif
41 #if defined(_KERNEL)
42 # include <sys/systm.h>
43 # include <sys/file.h>
44 #else
45 # include <stdio.h>
46 # include <string.h>
47 # include <stdlib.h>
48 # include <stddef.h>
49 # include <sys/file.h>
50 # define _KERNEL
51 # ifdef __OpenBSD__
52 struct file;
53 # endif
54 # include <sys/uio.h>
55 # undef _KERNEL
56 #endif
57 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
58     !defined(linux)
59 # include <sys/mbuf.h>
60 #else
61 # if !defined(linux)
62 #  include <sys/byteorder.h>
63 # endif
64 # if (SOLARIS2 < 5) && defined(sun)
65 #  include <sys/dditypes.h>
66 # endif
67 #endif
68 #ifdef __hpux
69 # define _NET_ROUTE_INCLUDED
70 #endif
71 #if !defined(linux)
72 # include <sys/protosw.h>
73 #endif
74 #include <sys/socket.h>
75 #include <net/if.h>
76 #ifdef sun
77 # include <net/af.h>
78 #endif
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
83 # include <sys/hashing.h>
84 # include <netinet/in_var.h>
85 #endif
86 #include <netinet/tcp.h>
87 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
88 # include <netinet/udp.h>
89 # include <netinet/ip_icmp.h>
90 #endif
91 #ifdef __hpux
92 # undef _NET_ROUTE_INCLUDED
93 #endif
94 #ifdef __osf__
95 # undef _RADIX_H_
96 #endif
97 #include "netinet/ip_compat.h"
98 #ifdef	USE_INET6
99 # include <netinet/icmp6.h>
100 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
101 #  include <netinet6/in6_var.h>
102 # endif
103 #endif
104 #include "netinet/ip_fil.h"
105 #include "netinet/ip_nat.h"
106 #include "netinet/ip_frag.h"
107 #include "netinet/ip_state.h"
108 #include "netinet/ip_proxy.h"
109 #include "netinet/ip_auth.h"
110 #ifdef IPFILTER_SCAN
111 # include "netinet/ip_scan.h"
112 #endif
113 #include "netinet/ip_sync.h"
114 #include "netinet/ip_lookup.h"
115 #include "netinet/ip_pool.h"
116 #include "netinet/ip_htable.h"
117 #ifdef IPFILTER_COMPILED
118 # include "netinet/ip_rules.h"
119 #endif
120 #if defined(IPFILTER_BPF) && defined(_KERNEL)
121 # include <net/bpf.h>
122 #endif
123 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
124 # include <sys/malloc.h>
125 #endif
126 #include "netinet/ipl.h"
127 
128 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
129 # include <sys/callout.h>
130 extern struct callout ipf_slowtimer_ch;
131 #endif
132 #if defined(__OpenBSD__)
133 # include <sys/timeout.h>
134 extern struct timeout ipf_slowtimer_ch;
135 #endif
136 #if defined(__NetBSD__)
137 #include <netinet/in_offload.h>
138 #endif
139 /* END OF INCLUDES */
140 
141 #if !defined(lint)
142 #if defined(__NetBSD__)
143 #include <sys/cdefs.h>
144 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.37 2023/06/24 05:16:15 msaitoh Exp $");
145 #else
146 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
147 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
148 #endif
149 #endif
150 
151 #ifndef	_KERNEL
152 # include "ipf.h"
153 # include "ipt.h"
154 extern	int	opts;
155 extern	int	blockreason;
156 #endif /* _KERNEL */
157 
158 #define FASTROUTE_RECURSION
159 
160 #define	LBUMP(x)	softc->x++
161 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
162 
163 static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
164 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
165 static	u_32_t		ipf_checkripso(u_char *);
166 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
167 #ifdef	IPFILTER_LOG
168 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
169 #endif
170 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
171 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
172 static	ipfunc_t	ipf_findfunc(ipfunc_t);
173 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
174 					i6addr_t *, i6addr_t *);
175 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
176 static	int		ipf_fr_matcharray(fr_info_t *, int *);
177 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
178 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
179 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
180 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
181 				    ipfgeniter_t *);
182 static	void		ipf_getstat(ipf_main_softc_t *,
183 				    struct friostat *, int);
184 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
185 static	void		ipf_group_free(frgroup_t *);
186 static	int		ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
187 static	int		ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
188 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
189 					frentry_t *, int);
190 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
191 static	INLINE int	ipf_pr_ah(fr_info_t *);
192 static	INLINE void	ipf_pr_esp(fr_info_t *);
193 static	INLINE void	ipf_pr_gre(fr_info_t *);
194 static	INLINE void	ipf_pr_udp(fr_info_t *);
195 static	INLINE void	ipf_pr_tcp(fr_info_t *);
196 static	INLINE void	ipf_pr_icmp(fr_info_t *);
197 static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
198 static	INLINE void	ipf_pr_short(fr_info_t *, int);
199 static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
200 static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
201 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
202 					int, int);
203 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
204 					       frentry_t *, int);
205 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
206 static	void		ipf_token_flush(ipf_main_softc_t *);
207 static	void		ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
208 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *, const char *);
209 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
210 					       void **);
211 static	int		ipf_updateipid(fr_info_t *);
212 static	int		ipf_settimeout(struct ipf_main_softc_s *,
213 				       struct ipftuneable *, ipftuneval_t *);
214 
215 
216 /*
217  * bit values for identifying presence of individual IP options
218  * All of these tables should be ordered by increasing key value on the left
219  * hand side to allow for binary searching of the array and include a trailer
220  * with a 0 for the bitmask for linear searches to easily find the end with.
221  */
222 static const	struct	optlist	ipopts[20] = {
223 	{ IPOPT_NOP,	0x000001 },
224 	{ IPOPT_RR,	0x000002 },
225 	{ IPOPT_ZSU,	0x000004 },
226 	{ IPOPT_MTUP,	0x000008 },
227 	{ IPOPT_MTUR,	0x000010 },
228 	{ IPOPT_ENCODE,	0x000020 },
229 	{ IPOPT_TS,	0x000040 },
230 	{ IPOPT_TR,	0x000080 },
231 	{ IPOPT_SECURITY, 0x000100 },
232 	{ IPOPT_LSRR,	0x000200 },
233 	{ IPOPT_E_SEC,	0x000400 },
234 	{ IPOPT_CIPSO,	0x000800 },
235 	{ IPOPT_SATID,	0x001000 },
236 	{ IPOPT_SSRR,	0x002000 },
237 	{ IPOPT_ADDEXT,	0x004000 },
238 	{ IPOPT_VISA,	0x008000 },
239 	{ IPOPT_IMITD,	0x010000 },
240 	{ IPOPT_EIP,	0x020000 },
241 	{ IPOPT_FINN,	0x040000 },
242 	{ 0,		0x000000 }
243 };
244 
245 #ifdef USE_INET6
246 static const struct optlist ip6exthdr[] = {
247 	{ IPPROTO_HOPOPTS,		0x000001 },
248 	{ IPPROTO_IPV6,			0x000002 },
249 	{ IPPROTO_ROUTING,		0x000004 },
250 	{ IPPROTO_FRAGMENT,		0x000008 },
251 	{ IPPROTO_ESP,			0x000010 },
252 	{ IPPROTO_AH,			0x000020 },
253 	{ IPPROTO_NONE,			0x000040 },
254 	{ IPPROTO_DSTOPTS,		0x000080 },
255 	{ IPPROTO_MOBILITY,		0x000100 },
256 	{ 0,				0 }
257 };
258 #endif
259 
260 /*
261  * bit values for identifying presence of individual IP security options
262  */
263 static const	struct	optlist	secopt[8] = {
264 	{ IPSO_CLASS_RES4,	0x01 },
265 	{ IPSO_CLASS_TOPS,	0x02 },
266 	{ IPSO_CLASS_SECR,	0x04 },
267 	{ IPSO_CLASS_RES3,	0x08 },
268 	{ IPSO_CLASS_CONF,	0x10 },
269 	{ IPSO_CLASS_UNCL,	0x20 },
270 	{ IPSO_CLASS_RES2,	0x40 },
271 	{ IPSO_CLASS_RES1,	0x80 }
272 };
273 
274 char	ipfilter_version[] = IPL_VERSION;
275 
276 int	ipf_features = 0
277 #ifdef	IPFILTER_LKM
278 		| IPF_FEAT_LKM
279 #endif
280 #ifdef	IPFILTER_LOG
281 		| IPF_FEAT_LOG
282 #endif
283 		| IPF_FEAT_LOOKUP
284 #ifdef	IPFILTER_BPF
285 		| IPF_FEAT_BPF
286 #endif
287 #ifdef	IPFILTER_COMPILED
288 		| IPF_FEAT_COMPILED
289 #endif
290 #ifdef	IPFILTER_CKSUM
291 		| IPF_FEAT_CKSUM
292 #endif
293 		| IPF_FEAT_SYNC
294 #ifdef	IPFILTER_SCAN
295 		| IPF_FEAT_SCAN
296 #endif
297 #ifdef	USE_INET6
298 		| IPF_FEAT_IPV6
299 #endif
300 	;
301 
302 
303 /*
304  * Table of functions available for use with call rules.
305  */
306 static ipfunc_resolve_t ipf_availfuncs[] = {
307 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
308 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
309 	{ "",	       NULL,	      NULL,	      NULL }
310 };
311 
312 static const ipftuneable_t ipf_main_tuneables[] = {
313 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
314 		"ipf_flags",		0,	0xffffffff,
315 		stsizeof(ipf_main_softc_t, ipf_flags),
316 		0,			NULL,	NULL },
317 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
318 		"active",		0,	0,
319 		stsizeof(ipf_main_softc_t, ipf_active),
320 		IPFT_RDONLY,		NULL,	NULL },
321 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
322 		"control_forwarding",	0, 1,
323 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
324 		0,			NULL,	NULL },
325 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
326 		"update_ipid",		0,	1,
327 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
328 		0,			NULL,	NULL },
329 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
330 		"chksrc",		0,	1,
331 		stsizeof(ipf_main_softc_t, ipf_chksrc),
332 		0,			NULL,	NULL },
333 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
334 		"min_ttl",		0,	1,
335 		stsizeof(ipf_main_softc_t, ipf_minttl),
336 		0,			NULL,	NULL },
337 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
338 		"icmp_minfragmtu",	0,	1,
339 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
340 		0,			NULL,	NULL },
341 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
342 		"default_pass",		0,	0xffffffff,
343 		stsizeof(ipf_main_softc_t, ipf_pass),
344 		0,			NULL,	NULL },
345 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
346 		"tcp_idle_timeout",	1,	0x7fffffff,
347 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
348 		0,			NULL,	ipf_settimeout },
349 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
350 		"tcp_close_wait",	1,	0x7fffffff,
351 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
352 		0,			NULL,	ipf_settimeout },
353 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
354 		"tcp_last_ack",		1,	0x7fffffff,
355 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
356 		0,			NULL,	ipf_settimeout },
357 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
358 		"tcp_timeout",		1,	0x7fffffff,
359 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
360 		0,			NULL,	ipf_settimeout },
361 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
362 		"tcp_syn_sent",		1,	0x7fffffff,
363 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
364 		0,			NULL,	ipf_settimeout },
365 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
366 		"tcp_syn_received",	1,	0x7fffffff,
367 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
368 		0,			NULL,	ipf_settimeout },
369 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
370 		"tcp_closed",		1,	0x7fffffff,
371 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
372 		0,			NULL,	ipf_settimeout },
373 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
374 		"tcp_half_closed",	1,	0x7fffffff,
375 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
376 		0,			NULL,	ipf_settimeout },
377 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
378 		"tcp_time_wait",	1,	0x7fffffff,
379 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
380 		0,			NULL,	ipf_settimeout },
381 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
382 		"udp_timeout",		1,	0x7fffffff,
383 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
384 		0,			NULL,	ipf_settimeout },
385 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
386 		"udp_ack_timeout",	1,	0x7fffffff,
387 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
388 		0,			NULL,	ipf_settimeout },
389 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
390 		"icmp_timeout",		1,	0x7fffffff,
391 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
392 		0,			NULL,	ipf_settimeout },
393 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
394 		"icmp_ack_timeout",	1,	0x7fffffff,
395 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
396 		0,			NULL,	ipf_settimeout },
397 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
398 		"ip_timeout",		1,	0x7fffffff,
399 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
400 		0,			NULL,	ipf_settimeout },
401 #if defined(INSTANCES) && defined(_KERNEL)
402 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
403 		"intercept_loopback",	0,	1,
404 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
405 		0,			NULL,	ipf_set_loopback },
406 #endif
407 	{ { 0 },
408 		NULL,			0,	0,
409 		0,
410 		0,			NULL,	NULL }
411 };
412 
413 
414 /*
415  * The next section of code is a a collection of small routines that set
416  * fields in the fr_info_t structure passed based on properties of the
417  * current packet.  There are different routines for the same protocol
418  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
419  * will "special" inspection for setup, is now more easily done by adding
420  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
421  * adding more code to a growing switch statement.
422  */
423 #ifdef USE_INET6
424 static	INLINE int	ipf_pr_ah6(fr_info_t *);
425 static	INLINE void	ipf_pr_esp6(fr_info_t *);
426 static	INLINE void	ipf_pr_gre6(fr_info_t *);
427 static	INLINE void	ipf_pr_udp6(fr_info_t *);
428 static	INLINE void	ipf_pr_tcp6(fr_info_t *);
429 static	INLINE void	ipf_pr_icmp6(fr_info_t *);
430 static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
431 static	INLINE void	ipf_pr_short6(fr_info_t *, int);
432 static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
433 static	INLINE int	ipf_pr_mobility6(fr_info_t *);
434 static	INLINE int	ipf_pr_routing6(fr_info_t *);
435 static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
436 static	INLINE int	ipf_pr_fragment6(fr_info_t *);
437 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
438 
439 
440 /* ------------------------------------------------------------------------ */
441 /* Function:    ipf_pr_short6                                               */
442 /* Returns:     void                                                        */
443 /* Parameters:  fin(I)  - pointer to packet information                     */
444 /*              xmin(I) - minimum header size                               */
445 /*                                                                          */
446 /* IPv6 Only                                                                */
447 /* This is function enforces the 'is a packet too short to be legit' rule   */
448 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
449 /* for ipf_pr_short() for more details.                                     */
450 /* ------------------------------------------------------------------------ */
451 static INLINE void
ipf_pr_short6(fr_info_t * fin,int xmin)452 ipf_pr_short6(fr_info_t *fin, int xmin)
453 {
454 
455 	if (fin->fin_dlen < xmin)
456 		fin->fin_flx |= FI_SHORT;
457 }
458 
459 
460 /* ------------------------------------------------------------------------ */
461 /* Function:    ipf_pr_ipv6hdr                                              */
462 /* Returns:     void                                                        */
463 /* Parameters:  fin(I) - pointer to packet information                      */
464 /*                                                                          */
465 /* IPv6 Only                                                                */
466 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
467 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
468 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
469 /* of that possibility arising.                                             */
470 /* ------------------------------------------------------------------------ */
471 static INLINE void
ipf_pr_ipv6hdr(fr_info_t * fin)472 ipf_pr_ipv6hdr(fr_info_t *fin)
473 {
474 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
475 	int p, go = 1, i, hdrcount;
476 	fr_ip_t *fi = &fin->fin_fi;
477 
478 	fin->fin_off = 0;
479 
480 	fi->fi_tos = 0;
481 	fi->fi_optmsk = 0;
482 	fi->fi_secmsk = 0;
483 	fi->fi_auth = 0;
484 
485 	p = ip6->ip6_nxt;
486 	fin->fin_crc = p;
487 	fi->fi_ttl = ip6->ip6_hlim;
488 	fi->fi_src.in6 = ip6->ip6_src;
489 	fin->fin_crc += fi->fi_src.i6[0];
490 	fin->fin_crc += fi->fi_src.i6[1];
491 	fin->fin_crc += fi->fi_src.i6[2];
492 	fin->fin_crc += fi->fi_src.i6[3];
493 	fi->fi_dst.in6 = ip6->ip6_dst;
494 	fin->fin_crc += fi->fi_dst.i6[0];
495 	fin->fin_crc += fi->fi_dst.i6[1];
496 	fin->fin_crc += fi->fi_dst.i6[2];
497 	fin->fin_crc += fi->fi_dst.i6[3];
498 	fin->fin_id = 0;
499 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
500 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
501 
502 	hdrcount = 0;
503 	while (go && !(fin->fin_flx & FI_SHORT)) {
504 		switch (p)
505 		{
506 		case IPPROTO_UDP :
507 			ipf_pr_udp6(fin);
508 			go = 0;
509 			break;
510 
511 		case IPPROTO_TCP :
512 			ipf_pr_tcp6(fin);
513 			go = 0;
514 			break;
515 
516 		case IPPROTO_ICMPV6 :
517 			ipf_pr_icmp6(fin);
518 			go = 0;
519 			break;
520 
521 		case IPPROTO_GRE :
522 			ipf_pr_gre6(fin);
523 			go = 0;
524 			break;
525 
526 		case IPPROTO_HOPOPTS :
527 			p = ipf_pr_hopopts6(fin);
528 			break;
529 
530 		case IPPROTO_MOBILITY :
531 			p = ipf_pr_mobility6(fin);
532 			break;
533 
534 		case IPPROTO_DSTOPTS :
535 			p = ipf_pr_dstopts6(fin);
536 			break;
537 
538 		case IPPROTO_ROUTING :
539 			p = ipf_pr_routing6(fin);
540 			break;
541 
542 		case IPPROTO_AH :
543 			p = ipf_pr_ah6(fin);
544 			break;
545 
546 		case IPPROTO_ESP :
547 			ipf_pr_esp6(fin);
548 			go = 0;
549 			break;
550 
551 		case IPPROTO_IPV6 :
552 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
553 				if (ip6exthdr[i].ol_val == p) {
554 					fin->fin_flx |= ip6exthdr[i].ol_bit;
555 					break;
556 				}
557 			go = 0;
558 			break;
559 
560 		case IPPROTO_NONE :
561 			go = 0;
562 			break;
563 
564 		case IPPROTO_FRAGMENT :
565 			p = ipf_pr_fragment6(fin);
566 			/*
567 			 * Given that the only fragments we want to let through
568 			 * (where fin_off != 0) are those where the non-first
569 			 * fragments only have data, we can safely stop looking
570 			 * at headers if this is a non-leading fragment.
571 			 */
572 			if (fin->fin_off != 0)
573 				go = 0;
574 			break;
575 
576 		default :
577 			go = 0;
578 			break;
579 		}
580 		hdrcount++;
581 
582 		/*
583 		 * It is important to note that at this point, for the
584 		 * extension headers (go != 0), the entire header may not have
585 		 * been pulled up when the code gets to this point.  This is
586 		 * only done for "go != 0" because the other header handlers
587 		 * will all pullup their complete header.  The other indicator
588 		 * of an incomplete packet is that this was just an extension
589 		 * header.
590 		 */
591 		if ((go != 0) && (p != IPPROTO_NONE) &&
592 		    (ipf_pr_pullup(fin, 0) == -1)) {
593 			p = IPPROTO_NONE;
594 			break;
595 		}
596 	}
597 
598 	/*
599 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
600 	 * and destroy whatever packet was here.  The caller of this function
601 	 * expects us to return if there is a problem with ipf_pullup.
602 	 */
603 	if (fin->fin_m == NULL) {
604 		ipf_main_softc_t *softc = fin->fin_main_soft;
605 
606 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
607 		return;
608 	}
609 
610 	fi->fi_p = p;
611 
612 	/*
613 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
614 	 * "go != 0" implies the above loop hasn't arrived at a layer 4 header.
615 	 */
616 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
617 		ipf_main_softc_t *softc = fin->fin_main_soft;
618 
619 		fin->fin_flx |= FI_BAD;
620 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
621 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
622 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
623 	}
624 }
625 
626 
627 /* ------------------------------------------------------------------------ */
628 /* Function:    ipf_pr_ipv6exthdr                                           */
629 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
630 /*                                 or NULL if there is a prolblem.          */
631 /* Parameters:  fin(I)      - pointer to packet information                 */
632 /*              multiple(I) - flag indicating yes/no if multiple occurances */
633 /*                            of this extension header are allowed.         */
634 /*              proto(I)    - protocol number for this extension header     */
635 /*                                                                          */
636 /* IPv6 Only                                                                */
637 /* This function embodies a number of common checks that all IPv6 extension */
638 /* headers must be subjected to.  For example, making sure the packet is    */
639 /* big enough for it to be in, checking if it is repeated and setting a     */
640 /* flag to indicate its presence.                                           */
641 /* ------------------------------------------------------------------------ */
642 static INLINE struct ip6_ext *
ipf_pr_ipv6exthdr(fr_info_t * fin,int multiple,int proto)643 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
644 {
645 	ipf_main_softc_t *softc = fin->fin_main_soft;
646 	struct ip6_ext *hdr;
647 	u_short shift;
648 	int i;
649 
650 	fin->fin_flx |= FI_V6EXTHDR;
651 
652 				/* 8 is default length of extension hdr */
653 	if ((fin->fin_dlen - 8) < 0) {
654 		fin->fin_flx |= FI_SHORT;
655 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
656 		return NULL;
657 	}
658 
659 	if (ipf_pr_pullup(fin, 8) == -1) {
660 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
661 		return NULL;
662 	}
663 
664 	hdr = fin->fin_dp;
665 	switch (proto)
666 	{
667 	case IPPROTO_FRAGMENT :
668 		shift = 8;
669 		break;
670 	default :
671 		shift = 8 + (hdr->ip6e_len << 3);
672 		break;
673 	}
674 
675 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
676 		fin->fin_flx |= FI_BAD;
677 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
678 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
679 		return NULL;
680 	}
681 
682 	fin->fin_dp = (char *)fin->fin_dp + shift;
683 	fin->fin_dlen -= shift;
684 
685 	/*
686 	 * If we have seen a fragment header, do not set any flags to indicate
687 	 * the presence of this extension header as it has no impact on the
688 	 * end result until after it has been defragmented.
689 	 */
690 	if (fin->fin_flx & FI_FRAG)
691 		return hdr;
692 
693 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
694 		if (ip6exthdr[i].ol_val == proto) {
695 			/*
696 			 * Most IPv6 extension headers are only allowed once.
697 			 */
698 			if ((multiple == 0) &&
699 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
700 				fin->fin_flx |= FI_BAD;
701 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
702 			} else
703 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
704 			break;
705 		}
706 
707 	return hdr;
708 }
709 
710 
711 /* ------------------------------------------------------------------------ */
712 /* Function:    ipf_pr_hopopts6                                             */
713 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
714 /* Parameters:  fin(I) - pointer to packet information                      */
715 /*                                                                          */
716 /* IPv6 Only                                                                */
717 /* This is function checks pending hop by hop options extension header      */
718 /* ------------------------------------------------------------------------ */
719 static INLINE int
ipf_pr_hopopts6(fr_info_t * fin)720 ipf_pr_hopopts6(fr_info_t *fin)
721 {
722 	struct ip6_ext *hdr;
723 
724 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
725 	if (hdr == NULL)
726 		return IPPROTO_NONE;
727 	return hdr->ip6e_nxt;
728 }
729 
730 
731 /* ------------------------------------------------------------------------ */
732 /* Function:    ipf_pr_mobility6                                            */
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 the IPv6 mobility extension header               */
738 /* ------------------------------------------------------------------------ */
739 static INLINE int
ipf_pr_mobility6(fr_info_t * fin)740 ipf_pr_mobility6(fr_info_t *fin)
741 {
742 	struct ip6_ext *hdr;
743 
744 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
745 	if (hdr == NULL)
746 		return IPPROTO_NONE;
747 	return hdr->ip6e_nxt;
748 }
749 
750 
751 /* ------------------------------------------------------------------------ */
752 /* Function:    ipf_pr_routing6                                             */
753 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
754 /* Parameters:  fin(I) - pointer to packet information                      */
755 /*                                                                          */
756 /* IPv6 Only                                                                */
757 /* This is function checks pending routing extension header                 */
758 /* ------------------------------------------------------------------------ */
759 static INLINE int
ipf_pr_routing6(fr_info_t * fin)760 ipf_pr_routing6(fr_info_t *fin)
761 {
762 	struct ip6_routing *hdr;
763 
764 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
765 	if (hdr == NULL)
766 		return IPPROTO_NONE;
767 
768 	switch (hdr->ip6r_type)
769 	{
770 	case 0 :
771 		/*
772 		 * Nasty extension header length?
773 		 */
774 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
775 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
776 			ipf_main_softc_t *softc = fin->fin_main_soft;
777 
778 			fin->fin_flx |= FI_BAD;
779 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
780 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
781 			return IPPROTO_NONE;
782 		}
783 		break;
784 
785 	default :
786 		break;
787 	}
788 
789 	return hdr->ip6r_nxt;
790 }
791 
792 
793 /* ------------------------------------------------------------------------ */
794 /* Function:    ipf_pr_fragment6                                            */
795 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
796 /* Parameters:  fin(I) - pointer to packet information                      */
797 /*                                                                          */
798 /* IPv6 Only                                                                */
799 /* Examine the IPv6 fragment header and extract fragment offset information.*/
800 /*                                                                          */
801 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
802 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
803 /* packets with a fragment header can fit into.  They are as follows:       */
804 /*                                                                          */
805 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
806 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
807 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
808 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
809 /* 5.  [IPV6][0-n EH][FH][data]                                             */
810 /*                                                                          */
811 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
812 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
813 /*                                                                          */
814 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
815 /* scenario in which they happen is in extreme circumstances that are most  */
816 /* likely to be an indication of an attack rather than normal traffic.      */
817 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
818 /* are two rules that can be used to guard against type 3 packets: L4       */
819 /* headers must always be in a packet that has the offset field set to 0    */
820 /* and no packet is allowed to overlay that where offset = 0.               */
821 /* ------------------------------------------------------------------------ */
822 static INLINE int
ipf_pr_fragment6(fr_info_t * fin)823 ipf_pr_fragment6(fr_info_t *fin)
824 {
825 	ipf_main_softc_t *softc = fin->fin_main_soft;
826 	struct ip6_frag *frag;
827 
828 	fin->fin_flx |= FI_FRAG;
829 
830 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
831 	if (frag == NULL) {
832 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
833 		return IPPROTO_NONE;
834 	}
835 
836 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
837 		/*
838 		 * Any fragment that isn't the last fragment must have its
839 		 * length as a multiple of 8.
840 		 */
841 		if ((fin->fin_plen & 7) != 0) {
842 			fin->fin_flx |= FI_BAD;
843 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
844 		}
845 	}
846 
847 	fin->fin_fraghdr = frag;
848 	fin->fin_id = frag->ip6f_ident;
849 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
850 	if (fin->fin_off != 0)
851 		fin->fin_flx |= FI_FRAGBODY;
852 
853 	/*
854 	 * Jumbograms aren't handled, so the max. length is 64k
855 	 */
856 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
857 		  fin->fin_flx |= FI_BAD;
858 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
859 	}
860 
861 	/*
862 	 * We don't know where the transport layer header (or whatever is next
863 	 * is), as it could be behind destination options (amongst others) so
864 	 * return the fragment header as the type of packet this is.  Note that
865 	 * this effectively disables the fragment cache for > 1 protocol at a
866 	 * time.
867 	 */
868 	return frag->ip6f_nxt;
869 }
870 
871 
872 /* ------------------------------------------------------------------------ */
873 /* Function:    ipf_pr_dstopts6                                             */
874 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
875 /* Parameters:  fin(I) - pointer to packet information                      */
876 /*                                                                          */
877 /* IPv6 Only                                                                */
878 /* This is function checks pending destination options extension header     */
879 /* ------------------------------------------------------------------------ */
880 static INLINE int
ipf_pr_dstopts6(fr_info_t * fin)881 ipf_pr_dstopts6(fr_info_t *fin)
882 {
883 	ipf_main_softc_t *softc = fin->fin_main_soft;
884 	struct ip6_ext *hdr;
885 
886 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
887 	if (hdr == NULL) {
888 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
889 		return IPPROTO_NONE;
890 	}
891 	return hdr->ip6e_nxt;
892 }
893 
894 
895 /* ------------------------------------------------------------------------ */
896 /* Function:    ipf_pr_icmp6                                                */
897 /* Returns:     void                                                        */
898 /* Parameters:  fin(I) - pointer to packet information                      */
899 /*                                                                          */
900 /* IPv6 Only                                                                */
901 /* This routine is mainly concerned with determining the minimum valid size */
902 /* for an ICMPv6 packet.                                                    */
903 /* ------------------------------------------------------------------------ */
904 static INLINE void
ipf_pr_icmp6(fr_info_t * fin)905 ipf_pr_icmp6(fr_info_t *fin)
906 {
907 	int minicmpsz = sizeof(struct icmp6_hdr);
908 	struct icmp6_hdr *icmp6;
909 
910 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
911 		ipf_main_softc_t *softc = fin->fin_main_soft;
912 
913 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
914 		return;
915 	}
916 
917 	if (fin->fin_dlen > 1) {
918 		ip6_t *ip6;
919 
920 		icmp6 = fin->fin_dp;
921 
922 		fin->fin_data[0] = *(u_short *)icmp6;
923 
924 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
925 			fin->fin_flx |= FI_ICMPQUERY;
926 
927 		switch (icmp6->icmp6_type)
928 		{
929 		case ICMP6_ECHO_REPLY :
930 		case ICMP6_ECHO_REQUEST :
931 			if (fin->fin_dlen >= 6)
932 				fin->fin_data[1] = icmp6->icmp6_id;
933 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
934 			break;
935 
936 		case ICMP6_DST_UNREACH :
937 		case ICMP6_PACKET_TOO_BIG :
938 		case ICMP6_TIME_EXCEEDED :
939 		case ICMP6_PARAM_PROB :
940 			fin->fin_flx |= FI_ICMPERR;
941 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
942 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
943 				break;
944 
945 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
946 				if (ipf_coalesce(fin) != 1)
947 					return;
948 			}
949 
950 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
951 				return;
952 
953 			/*
954 			 * If the destination of this packet doesn't match the
955 			 * source of the original packet then this packet is
956 			 * not correct.
957 			 */
958 			icmp6 = fin->fin_dp;
959 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
960 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
961 				    &ip6->ip6_src)) {
962 				fin->fin_flx |= FI_BAD;
963 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
964 			}
965 			break;
966 		default :
967 			break;
968 		}
969 	}
970 
971 	ipf_pr_short6(fin, minicmpsz);
972 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
973 		u_char p = fin->fin_p;
974 
975 		fin->fin_p = IPPROTO_ICMPV6;
976 		ipf_checkv6sum(fin);
977 		fin->fin_p = p;
978 	}
979 }
980 
981 
982 /* ------------------------------------------------------------------------ */
983 /* Function:    ipf_pr_udp6                                                 */
984 /* Returns:     void                                                        */
985 /* Parameters:  fin(I) - pointer to packet information                      */
986 /*                                                                          */
987 /* IPv6 Only                                                                */
988 /* Analyse the packet for IPv6/UDP properties.                              */
989 /* Is not expected to be called for fragmented packets.                     */
990 /* ------------------------------------------------------------------------ */
991 static INLINE void
ipf_pr_udp6(fr_info_t * fin)992 ipf_pr_udp6(fr_info_t *fin)
993 {
994 
995 	if (ipf_pr_udpcommon(fin) == 0) {
996 		u_char p = fin->fin_p;
997 
998 		fin->fin_p = IPPROTO_UDP;
999 		ipf_checkv6sum(fin);
1000 		fin->fin_p = p;
1001 	}
1002 }
1003 
1004 
1005 /* ------------------------------------------------------------------------ */
1006 /* Function:    ipf_pr_tcp6                                                 */
1007 /* Returns:     void                                                        */
1008 /* Parameters:  fin(I) - pointer to packet information                      */
1009 /*                                                                          */
1010 /* IPv6 Only                                                                */
1011 /* Analyse the packet for IPv6/TCP properties.                              */
1012 /* Is not expected to be called for fragmented packets.                     */
1013 /* ------------------------------------------------------------------------ */
1014 static INLINE void
ipf_pr_tcp6(fr_info_t * fin)1015 ipf_pr_tcp6(fr_info_t *fin)
1016 {
1017 
1018 	if (ipf_pr_tcpcommon(fin) == 0) {
1019 		u_char p = fin->fin_p;
1020 
1021 		fin->fin_p = IPPROTO_TCP;
1022 		ipf_checkv6sum(fin);
1023 		fin->fin_p = p;
1024 	}
1025 }
1026 
1027 
1028 /* ------------------------------------------------------------------------ */
1029 /* Function:    ipf_pr_esp6                                                 */
1030 /* Returns:     void                                                        */
1031 /* Parameters:  fin(I) - pointer to packet information                      */
1032 /*                                                                          */
1033 /* IPv6 Only                                                                */
1034 /* Analyse the packet for ESP properties.                                   */
1035 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1036 /* even though the newer ESP packets must also have a sequence number that  */
1037 /* is 32bits as well, it is not possible(?) to determine the version from a */
1038 /* simple packet header.                                                    */
1039 /* ------------------------------------------------------------------------ */
1040 static INLINE void
ipf_pr_esp6(fr_info_t * fin)1041 ipf_pr_esp6(fr_info_t *fin)
1042 {
1043 
1044 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1045 		ipf_main_softc_t *softc = fin->fin_main_soft;
1046 
1047 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1048 		return;
1049 	}
1050 }
1051 
1052 
1053 /* ------------------------------------------------------------------------ */
1054 /* Function:    ipf_pr_ah6                                                  */
1055 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1056 /* Parameters:  fin(I) - pointer to packet information                      */
1057 /*                                                                          */
1058 /* IPv6 Only                                                                */
1059 /* Analyse the packet for AH properties.                                    */
1060 /* The minimum length is taken to be the combination of all fields in the   */
1061 /* header being present and no authentication data (null algorithm used.)   */
1062 /* ------------------------------------------------------------------------ */
1063 static INLINE int
ipf_pr_ah6(fr_info_t * fin)1064 ipf_pr_ah6(fr_info_t *fin)
1065 {
1066 	authhdr_t *ah;
1067 
1068 	fin->fin_flx |= FI_AH;
1069 
1070 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1071 	if (ah == NULL) {
1072 		ipf_main_softc_t *softc = fin->fin_main_soft;
1073 
1074 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1075 		return IPPROTO_NONE;
1076 	}
1077 
1078 	ipf_pr_short6(fin, sizeof(*ah));
1079 
1080 	/*
1081 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1082 	 * enough data to satisfy ah_next (the very first one.)
1083 	 */
1084 	return ah->ah_next;
1085 }
1086 
1087 
1088 /* ------------------------------------------------------------------------ */
1089 /* Function:    ipf_pr_gre6                                                 */
1090 /* Returns:     void                                                        */
1091 /* Parameters:  fin(I) - pointer to packet information                      */
1092 /*                                                                          */
1093 /* Analyse the packet for GRE properties.                                   */
1094 /* ------------------------------------------------------------------------ */
1095 static INLINE void
ipf_pr_gre6(fr_info_t * fin)1096 ipf_pr_gre6(fr_info_t *fin)
1097 {
1098 	grehdr_t *gre;
1099 
1100 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1101 		ipf_main_softc_t *softc = fin->fin_main_soft;
1102 
1103 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1104 		return;
1105 	}
1106 
1107 	gre = fin->fin_dp;
1108 	if (GRE_REV(gre->gr_flags) == 1)
1109 		fin->fin_data[0] = gre->gr_call;
1110 }
1111 #endif	/* USE_INET6 */
1112 
1113 
1114 /* ------------------------------------------------------------------------ */
1115 /* Function:    ipf_pr_pullup                                               */
1116 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1117 /* Parameters:  fin(I)  - pointer to packet information                     */
1118 /*              plen(I) - length (excluding L3 header) to pullup            */
1119 /*                                                                          */
1120 /* Short inline function to cut down on code duplication to perform a call  */
1121 /* to ipf_pullup to ensure there is the required amount of data,            */
1122 /* consecutively in the packet buffer.                                      */
1123 /*                                                                          */
1124 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1125 /* points to the first byte after the complete layer 3 header, which will   */
1126 /* include all of the known extension headers for IPv6 or options for IPv4. */
1127 /*                                                                          */
1128 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1129 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1130 /* - fin_ip) to what is passed through.                                     */
1131 /* ------------------------------------------------------------------------ */
1132 int
ipf_pr_pullup(fr_info_t * fin,int plen)1133 ipf_pr_pullup(fr_info_t *fin, int plen)
1134 {
1135 	ipf_main_softc_t *softc = fin->fin_main_soft;
1136 
1137 	if (fin->fin_m != NULL) {
1138 		if (fin->fin_dp != NULL)
1139 			plen += (char *)fin->fin_dp -
1140 				((char *)fin->fin_ip + fin->fin_hlen);
1141 		plen += fin->fin_hlen;
1142 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1143 #if defined(_KERNEL)
1144 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1145 				DT1(ipf_pullup_fail, fr_info_t *, fin);
1146 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1147 				fin->fin_reason = FRB_PULLUP;
1148 				fin->fin_flx |= FI_BAD;
1149 				return -1;
1150 			}
1151 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1152 #else
1153 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1154 			/*
1155 			 * Fake ipf_pullup failing
1156 			 */
1157 			fin->fin_reason = FRB_PULLUP;
1158 			*fin->fin_mp = NULL;
1159 			fin->fin_m = NULL;
1160 			fin->fin_ip = NULL;
1161 			fin->fin_flx |= FI_BAD;
1162 			return -1;
1163 #endif
1164 		}
1165 	}
1166 	return 0;
1167 }
1168 
1169 
1170 /* ------------------------------------------------------------------------ */
1171 /* Function:    ipf_pr_short                                                */
1172 /* Returns:     void                                                        */
1173 /* Parameters:  fin(I)  - pointer to packet information                     */
1174 /*              xmin(I) - minimum header size                               */
1175 /*                                                                          */
1176 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1177 /* applying here is that the packet must not be fragmented within the layer */
1178 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1179 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1180 /* entire layer 4 header must be present (min).                             */
1181 /* ------------------------------------------------------------------------ */
1182 static INLINE void
ipf_pr_short(fr_info_t * fin,int xmin)1183 ipf_pr_short(fr_info_t *fin, int xmin)
1184 {
1185 
1186 	if (fin->fin_off == 0) {
1187 		if (fin->fin_dlen < xmin)
1188 			fin->fin_flx |= FI_SHORT;
1189 	} else if (fin->fin_off < xmin) {
1190 		fin->fin_flx |= FI_SHORT;
1191 	}
1192 }
1193 
1194 
1195 /* ------------------------------------------------------------------------ */
1196 /* Function:    ipf_pr_icmp                                                 */
1197 /* Returns:     void                                                        */
1198 /* Parameters:  fin(I) - pointer to packet information                      */
1199 /*                                                                          */
1200 /* IPv4 Only                                                                */
1201 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1202 /* except extrememly bad packets, both type and code will be present.       */
1203 /* The expected minimum size of an ICMP packet is very much dependent on    */
1204 /* the type of it.                                                          */
1205 /*                                                                          */
1206 /* XXX - other ICMP sanity checks?                                          */
1207 /* ------------------------------------------------------------------------ */
1208 static INLINE void
ipf_pr_icmp(fr_info_t * fin)1209 ipf_pr_icmp(fr_info_t *fin)
1210 {
1211 	ipf_main_softc_t *softc = fin->fin_main_soft;
1212 	int minicmpsz = sizeof(struct icmp);
1213 	icmphdr_t *icmp;
1214 	ip_t *oip;
1215 
1216 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1217 
1218 	if (fin->fin_off != 0) {
1219 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1220 		return;
1221 	}
1222 
1223 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1224 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1225 		return;
1226 	}
1227 
1228 	icmp = fin->fin_dp;
1229 
1230 	fin->fin_data[0] = *(u_short *)icmp;
1231 	fin->fin_data[1] = icmp->icmp_id;
1232 
1233 	switch (icmp->icmp_type)
1234 	{
1235 	case ICMP_ECHOREPLY :
1236 	case ICMP_ECHO :
1237 	/* Router discovery messaes - RFC 1256 */
1238 	case ICMP_ROUTERADVERT :
1239 	case ICMP_ROUTERSOLICIT :
1240 		fin->fin_flx |= FI_ICMPQUERY;
1241 		minicmpsz = ICMP_MINLEN;
1242 		break;
1243 	/*
1244 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1245 	 * 3 * timestamp(3 * 4)
1246 	 */
1247 	case ICMP_TSTAMP :
1248 	case ICMP_TSTAMPREPLY :
1249 		fin->fin_flx |= FI_ICMPQUERY;
1250 		minicmpsz = 20;
1251 		break;
1252 	/*
1253 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1254 	 * mask(4)
1255 	 */
1256 	case ICMP_IREQ :
1257 	case ICMP_IREQREPLY :
1258 	case ICMP_MASKREQ :
1259 	case ICMP_MASKREPLY :
1260 		fin->fin_flx |= FI_ICMPQUERY;
1261 		minicmpsz = 12;
1262 		break;
1263 	/*
1264 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1265 	 */
1266 	case ICMP_UNREACH :
1267 #ifdef icmp_nextmtu
1268 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1269 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1270 				fin->fin_flx |= FI_BAD;
1271 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1272 			}
1273 		}
1274 #endif
1275 		/* FALLTHROUGH */
1276 	case ICMP_SOURCEQUENCH :
1277 	case ICMP_REDIRECT :
1278 	case ICMP_TIMXCEED :
1279 	case ICMP_PARAMPROB :
1280 		fin->fin_flx |= FI_ICMPERR;
1281 		if (ipf_coalesce(fin) != 1) {
1282 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1283 			return;
1284 		}
1285 
1286 		/*
1287 		 * ICMP error packets should not be generated for IP
1288 		 * packets that are a fragment that isn't the first
1289 		 * fragment.
1290 		 */
1291 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1292 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1293 			fin->fin_flx |= FI_BAD;
1294 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1295 		}
1296 
1297 		/*
1298 		 * If the destination of this packet doesn't match the
1299 		 * source of the original packet then this packet is
1300 		 * not correct.
1301 		 */
1302 		if (oip->ip_src.s_addr != fin->fin_daddr) {
1303 			fin->fin_flx |= FI_BAD;
1304 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1305 		}
1306 		break;
1307 	default :
1308 		break;
1309 	}
1310 
1311 	ipf_pr_short(fin, minicmpsz);
1312 
1313 	ipf_checkv4sum(fin);
1314 }
1315 
1316 
1317 /* ------------------------------------------------------------------------ */
1318 /* Function:    ipf_pr_tcpcommon                                            */
1319 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1320 /* Parameters:  fin(I) - pointer to packet information                      */
1321 /*                                                                          */
1322 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1323 /* and make some checks with how they interact with other fields.           */
1324 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1325 /* valid and mark the packet as bad if not.                                 */
1326 /* ------------------------------------------------------------------------ */
1327 static INLINE int
ipf_pr_tcpcommon(fr_info_t * fin)1328 ipf_pr_tcpcommon(fr_info_t *fin)
1329 {
1330 	ipf_main_softc_t *softc = fin->fin_main_soft;
1331 	int flags, tlen;
1332 	tcphdr_t *tcp;
1333 
1334 	fin->fin_flx |= FI_TCPUDP;
1335 	if (fin->fin_off != 0) {
1336 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1337 		return 0;
1338 	}
1339 
1340 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1341 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1342 		return -1;
1343 	}
1344 
1345 	tcp = fin->fin_dp;
1346 	if (fin->fin_dlen > 3) {
1347 		fin->fin_sport = ntohs(tcp->th_sport);
1348 		fin->fin_dport = ntohs(tcp->th_dport);
1349 	}
1350 
1351 	if ((fin->fin_flx & FI_SHORT) != 0) {
1352 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1353 		return 1;
1354 	}
1355 
1356 	/*
1357 	 * Use of the TCP data offset *must* result in a value that is at
1358 	 * least the same size as the TCP header.
1359 	 */
1360 	tlen = TCP_OFF(tcp) << 2;
1361 	if (tlen < sizeof(tcphdr_t)) {
1362 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1363 		fin->fin_flx |= FI_BAD;
1364 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1365 		return 1;
1366 	}
1367 
1368 	flags = tcp->th_flags;
1369 	fin->fin_tcpf = tcp->th_flags;
1370 
1371 	/*
1372 	 * If the urgent flag is set, then the urgent pointer must
1373 	 * also be set and vice versa.  Good TCP packets do not have
1374 	 * just one of these set.
1375 	 */
1376 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1377 		fin->fin_flx |= FI_BAD;
1378 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1379 #if 0
1380 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1381 		/*
1382 		 * Ignore this case (#if 0) as it shows up in "real"
1383 		 * traffic with bogus values in the urgent pointer field.
1384 		 */
1385 		fin->fin_flx |= FI_BAD;
1386 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1387 #endif
1388 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1389 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1390 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1391 		fin->fin_flx |= FI_BAD;
1392 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1393 #if 1
1394 	} else if (((flags & TH_SYN) != 0) &&
1395 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1396 		/*
1397 		 * SYN with URG and PUSH set is not for normal TCP but it is
1398 		 * possible(?) with T/TCP...but who uses T/TCP?
1399 		 */
1400 		fin->fin_flx |= FI_BAD;
1401 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1402 #endif
1403 	} else if (!(flags & TH_ACK)) {
1404 		/*
1405 		 * If the ack bit isn't set, then either the SYN or
1406 		 * RST bit must be set.  If the SYN bit is set, then
1407 		 * we expect the ACK field to be 0.  If the ACK is
1408 		 * not set and if URG, PSH or FIN are set, consdier
1409 		 * that to indicate a bad TCP packet.
1410 		 */
1411 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1412 			/*
1413 			 * Cisco PIX sets the ACK field to a random value.
1414 			 * In light of this, do not set FI_BAD until a patch
1415 			 * is available from Cisco to ensure that
1416 			 * interoperability between existing systems is
1417 			 * achieved.
1418 			 */
1419 			/*fin->fin_flx |= FI_BAD*/;
1420 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1421 		} else if (!(flags & (TH_RST|TH_SYN))) {
1422 			fin->fin_flx |= FI_BAD;
1423 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1424 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1425 			fin->fin_flx |= FI_BAD;
1426 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1427 		}
1428 	}
1429 	if (fin->fin_flx & FI_BAD) {
1430 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1431 		return 1;
1432 	}
1433 
1434 	/*
1435 	 * At this point, it's not exactly clear what is to be gained by
1436 	 * marking up which TCP options are and are not present.  The one we
1437 	 * are most interested in is the TCP window scale.  This is only in
1438 	 * a SYN packet [RFC1323] so we don't need this here...?
1439 	 * Now if we were to analyse the header for passive fingerprinting,
1440 	 * then that might add some weight to adding this...
1441 	 */
1442 	if (tlen == sizeof(tcphdr_t)) {
1443 		return 0;
1444 	}
1445 
1446 	if (ipf_pr_pullup(fin, tlen) == -1) {
1447 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1448 		return -1;
1449 	}
1450 
1451 #if 0
1452 	tcp = fin->fin_dp;
1453 	ip = fin->fin_ip;
1454 	s = (u_char *)(tcp + 1);
1455 	off = IP_HL(ip) << 2;
1456 # ifdef _KERNEL
1457 	if (fin->fin_mp != NULL) {
1458 		mb_t *m = *fin->fin_mp;
1459 
1460 		if (off + tlen > M_LEN(m))
1461 			return;
1462 	}
1463 # endif
1464 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1465 		opt = *s;
1466 		if (opt == '\0')
1467 			break;
1468 		else if (opt == TCPOPT_NOP)
1469 			ol = 1;
1470 		else {
1471 			if (tlen < 2)
1472 				break;
1473 			ol = (int)*(s + 1);
1474 			if (ol < 2 || ol > tlen)
1475 				break;
1476 		}
1477 
1478 		for (i = 9, mv = 4; mv >= 0; ) {
1479 			op = ipopts + i;
1480 			if (opt == (u_char)op->ol_val) {
1481 				optmsk |= op->ol_bit;
1482 				break;
1483 			}
1484 		}
1485 		tlen -= ol;
1486 		s += ol;
1487 	}
1488 #endif /* 0 */
1489 
1490 	return 0;
1491 }
1492 
1493 
1494 
1495 /* ------------------------------------------------------------------------ */
1496 /* Function:    ipf_pr_udpcommon                                            */
1497 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1498 /* Parameters:  fin(I) - pointer to packet information                      */
1499 /*                                                                          */
1500 /* Extract the UDP source and destination ports, if present.  If compiled   */
1501 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1502 /* ------------------------------------------------------------------------ */
1503 static INLINE int
ipf_pr_udpcommon(fr_info_t * fin)1504 ipf_pr_udpcommon(fr_info_t *fin)
1505 {
1506 	udphdr_t *udp;
1507 
1508 	fin->fin_flx |= FI_TCPUDP;
1509 
1510 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1511 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1512 			ipf_main_softc_t *softc = fin->fin_main_soft;
1513 
1514 			fin->fin_flx |= FI_SHORT;
1515 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1516 			return 1;
1517 		}
1518 
1519 		udp = fin->fin_dp;
1520 
1521 		fin->fin_sport = ntohs(udp->uh_sport);
1522 		fin->fin_dport = ntohs(udp->uh_dport);
1523 	}
1524 
1525 	return 0;
1526 }
1527 
1528 
1529 /* ------------------------------------------------------------------------ */
1530 /* Function:    ipf_pr_tcp                                                  */
1531 /* Returns:     void                                                        */
1532 /* Parameters:  fin(I) - pointer to packet information                      */
1533 /*                                                                          */
1534 /* IPv4 Only                                                                */
1535 /* Analyse the packet for IPv4/TCP properties.                              */
1536 /* ------------------------------------------------------------------------ */
1537 static INLINE void
ipf_pr_tcp(fr_info_t * fin)1538 ipf_pr_tcp(fr_info_t *fin)
1539 {
1540 
1541 	ipf_pr_short(fin, sizeof(tcphdr_t));
1542 
1543 	if (ipf_pr_tcpcommon(fin) == 0)
1544 		ipf_checkv4sum(fin);
1545 }
1546 
1547 
1548 /* ------------------------------------------------------------------------ */
1549 /* Function:    ipf_pr_udp                                                  */
1550 /* Returns:     void                                                        */
1551 /* Parameters:  fin(I) - pointer to packet information                      */
1552 /*                                                                          */
1553 /* IPv4 Only                                                                */
1554 /* Analyse the packet for IPv4/UDP properties.                              */
1555 /* ------------------------------------------------------------------------ */
1556 static INLINE void
ipf_pr_udp(fr_info_t * fin)1557 ipf_pr_udp(fr_info_t *fin)
1558 {
1559 
1560 	ipf_pr_short(fin, sizeof(udphdr_t));
1561 
1562 	if (ipf_pr_udpcommon(fin) == 0)
1563 		ipf_checkv4sum(fin);
1564 }
1565 
1566 
1567 /* ------------------------------------------------------------------------ */
1568 /* Function:    ipf_pr_esp                                                  */
1569 /* Returns:     void                                                        */
1570 /* Parameters:  fin(I) - pointer to packet information                      */
1571 /*                                                                          */
1572 /* Analyse the packet for ESP properties.                                   */
1573 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1574 /* even though the newer ESP packets must also have a sequence number that  */
1575 /* is 32bits as well, it is not possible(?) to determine the version from a */
1576 /* simple packet header.                                                    */
1577 /* ------------------------------------------------------------------------ */
1578 static INLINE void
ipf_pr_esp(fr_info_t * fin)1579 ipf_pr_esp(fr_info_t *fin)
1580 {
1581 
1582 	if (fin->fin_off == 0) {
1583 		ipf_pr_short(fin, 8);
1584 		if (ipf_pr_pullup(fin, 8) == -1) {
1585 			ipf_main_softc_t *softc = fin->fin_main_soft;
1586 
1587 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1588 		}
1589 	}
1590 }
1591 
1592 
1593 /* ------------------------------------------------------------------------ */
1594 /* Function:    ipf_pr_ah                                                   */
1595 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1596 /* Parameters:  fin(I) - pointer to packet information                      */
1597 /*                                                                          */
1598 /* Analyse the packet for AH properties.                                    */
1599 /* The minimum length is taken to be the combination of all fields in the   */
1600 /* header being present and no authentication data (null algorithm used.)   */
1601 /* ------------------------------------------------------------------------ */
1602 static INLINE int
ipf_pr_ah(fr_info_t * fin)1603 ipf_pr_ah(fr_info_t *fin)
1604 {
1605 	ipf_main_softc_t *softc = fin->fin_main_soft;
1606 	authhdr_t *ah;
1607 	int len;
1608 
1609 	fin->fin_flx |= FI_AH;
1610 	ipf_pr_short(fin, sizeof(*ah));
1611 
1612 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1613 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1614 		return IPPROTO_NONE;
1615 	}
1616 
1617 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1618 		DT(fr_v4_ah_pullup_1);
1619 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1620 		return IPPROTO_NONE;
1621 	}
1622 
1623 	ah = (authhdr_t *)fin->fin_dp;
1624 
1625 	len = (ah->ah_plen + 2) << 2;
1626 	ipf_pr_short(fin, len);
1627 	if (ipf_pr_pullup(fin, len) == -1) {
1628 		DT(fr_v4_ah_pullup_2);
1629 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1630 		return IPPROTO_NONE;
1631 	}
1632 
1633 	/*
1634 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1635 	 * header.
1636 	 */
1637 	fin->fin_dp = (char *)fin->fin_dp + len;
1638 	fin->fin_dlen -= len;
1639 	return ah->ah_next;
1640 }
1641 
1642 
1643 /* ------------------------------------------------------------------------ */
1644 /* Function:    ipf_pr_gre                                                  */
1645 /* Returns:     void                                                        */
1646 /* Parameters:  fin(I) - pointer to packet information                      */
1647 /*                                                                          */
1648 /* Analyse the packet for GRE properties.                                   */
1649 /* ------------------------------------------------------------------------ */
1650 static INLINE void
ipf_pr_gre(fr_info_t * fin)1651 ipf_pr_gre(fr_info_t *fin)
1652 {
1653 	ipf_main_softc_t *softc = fin->fin_main_soft;
1654 	grehdr_t *gre;
1655 
1656 	ipf_pr_short(fin, sizeof(grehdr_t));
1657 
1658 	if (fin->fin_off != 0) {
1659 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1660 		return;
1661 	}
1662 
1663 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1664 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1665 		return;
1666 	}
1667 
1668 	gre = fin->fin_dp;
1669 	if (GRE_REV(gre->gr_flags) == 1)
1670 		fin->fin_data[0] = gre->gr_call;
1671 }
1672 
1673 
1674 /* ------------------------------------------------------------------------ */
1675 /* Function:    ipf_pr_ipv4hdr                                              */
1676 /* Returns:     void                                                        */
1677 /* Parameters:  fin(I) - pointer to packet information                      */
1678 /*                                                                          */
1679 /* IPv4 Only                                                                */
1680 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1681 /* Check all options present and flag their presence if any exist.          */
1682 /* ------------------------------------------------------------------------ */
1683 static INLINE void
ipf_pr_ipv4hdr(fr_info_t * fin)1684 ipf_pr_ipv4hdr(fr_info_t *fin)
1685 {
1686 	u_short optmsk = 0, secmsk = 0, auth = 0;
1687 	int hlen, ol, mv, p, i;
1688 	const struct optlist *op;
1689 	u_char *s, opt;
1690 	u_short off;
1691 	fr_ip_t *fi;
1692 	ip_t *ip;
1693 
1694 	fi = &fin->fin_fi;
1695 	hlen = fin->fin_hlen;
1696 
1697 	ip = fin->fin_ip;
1698 	p = ip->ip_p;
1699 	fi->fi_p = p;
1700 	fin->fin_crc = p;
1701 	fi->fi_tos = ip->ip_tos;
1702 	fin->fin_id = ntohs(ip->ip_id);
1703 	off = ntohs(ip->ip_off);
1704 
1705 	/* Get both TTL and protocol */
1706 	fi->fi_p = ip->ip_p;
1707 	fi->fi_ttl = ip->ip_ttl;
1708 
1709 	/* Zero out bits not used in IPv6 address */
1710 	fi->fi_src.i6[1] = 0;
1711 	fi->fi_src.i6[2] = 0;
1712 	fi->fi_src.i6[3] = 0;
1713 	fi->fi_dst.i6[1] = 0;
1714 	fi->fi_dst.i6[2] = 0;
1715 	fi->fi_dst.i6[3] = 0;
1716 
1717 	fi->fi_saddr = ip->ip_src.s_addr;
1718 	fin->fin_crc += fi->fi_saddr;
1719 	fi->fi_daddr = ip->ip_dst.s_addr;
1720 	fin->fin_crc += fi->fi_daddr;
1721 	if (IN_CLASSD(fi->fi_daddr))
1722 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1723 
1724 	/*
1725 	 * set packet attribute flags based on the offset and
1726 	 * calculate the byte offset that it represents.
1727 	 */
1728 	off &= IP_MF|IP_OFFMASK;
1729 	if (off != 0) {
1730 		int morefrag = off & IP_MF;
1731 		fi->fi_flx |= FI_FRAG;
1732 		off &= IP_OFFMASK;
1733 		if (off != 0) {
1734 			if (off == 1 && p == IPPROTO_TCP) {
1735 				fin->fin_flx |= FI_SHORT;       /* RFC 3128 */
1736 				DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1737 			}
1738 
1739 			fin->fin_flx |= FI_FRAGBODY;
1740 			off <<= 3;
1741 			if ((off + fin->fin_dlen > 65535) ||
1742 			    (fin->fin_dlen == 0) ||
1743 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1744 				/*
1745 				 * The length of the packet, starting at its
1746 				 * offset cannot exceed 65535 (0xffff) as the
1747 				 * length of an IP packet is only 16 bits.
1748 				 *
1749 				 * Any fragment that isn't the last fragment
1750 				 * must have a length greater than 0 and it
1751 				 * must be an even multiple of 8.
1752 				 */
1753 				fi->fi_flx |= FI_BAD;
1754 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1755 			}
1756 		}
1757 	}
1758 	fin->fin_off = off;
1759 
1760 	/*
1761 	 * Call per-protocol setup and checking
1762 	 */
1763 	if (p == IPPROTO_AH) {
1764 		/*
1765 		 * Treat AH differently because we expect there to be another
1766 		 * layer 4 header after it.
1767 		 */
1768 		p = ipf_pr_ah(fin);
1769 	}
1770 
1771 	switch (p)
1772 	{
1773 	case IPPROTO_UDP :
1774 		ipf_pr_udp(fin);
1775 		break;
1776 	case IPPROTO_TCP :
1777 		ipf_pr_tcp(fin);
1778 		break;
1779 	case IPPROTO_ICMP :
1780 		ipf_pr_icmp(fin);
1781 		break;
1782 	case IPPROTO_ESP :
1783 		ipf_pr_esp(fin);
1784 		break;
1785 	case IPPROTO_GRE :
1786 		ipf_pr_gre(fin);
1787 		break;
1788 	}
1789 
1790 	ip = fin->fin_ip;
1791 	if (ip == NULL)
1792 		return;
1793 
1794 	/*
1795 	 * If it is a standard IP header (no options), set the flag fields
1796 	 * which relate to options to 0.
1797 	 */
1798 	if (hlen == sizeof(*ip)) {
1799 		fi->fi_optmsk = 0;
1800 		fi->fi_secmsk = 0;
1801 		fi->fi_auth = 0;
1802 		return;
1803 	}
1804 
1805 	/*
1806 	 * So the IP header has some IP options attached.  Walk the entire
1807 	 * list of options present with this packet and set flags to indicate
1808 	 * which ones are here and which ones are not.  For the somewhat out
1809 	 * of date and obscure security classification options, set a flag to
1810 	 * represent which classification is present.
1811 	 */
1812 	fi->fi_flx |= FI_OPTIONS;
1813 
1814 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1815 		opt = *s;
1816 		if (opt == '\0')
1817 			break;
1818 		else if (opt == IPOPT_NOP)
1819 			ol = 1;
1820 		else {
1821 			if (hlen < 2)
1822 				break;
1823 			ol = (int)*(s + 1);
1824 			if (ol < 2 || ol > hlen)
1825 				break;
1826 		}
1827 		for (i = 9, mv = 4; mv >= 0; ) {
1828 			op = ipopts + i;
1829 
1830 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1831 				u_32_t doi;
1832 
1833 				switch (opt)
1834 				{
1835 				case IPOPT_SECURITY :
1836 					if (optmsk & op->ol_bit) {
1837 						fin->fin_flx |= FI_BAD;
1838 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1839 					} else {
1840 						doi = ipf_checkripso(s);
1841 						secmsk = doi >> 16;
1842 						auth = doi & 0xffff;
1843 					}
1844 					break;
1845 
1846 				case IPOPT_CIPSO :
1847 
1848 					if (optmsk & op->ol_bit) {
1849 						fin->fin_flx |= FI_BAD;
1850 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1851 					} else {
1852 						doi = ipf_checkcipso(fin,
1853 								     s, ol);
1854 						secmsk = doi >> 16;
1855 						auth = doi & 0xffff;
1856 					}
1857 					break;
1858 				}
1859 				optmsk |= op->ol_bit;
1860 			}
1861 
1862 			if (opt < op->ol_val)
1863 				i -= mv;
1864 			else
1865 				i += mv;
1866 			mv--;
1867 		}
1868 		hlen -= ol;
1869 		s += ol;
1870 	}
1871 
1872 	/*
1873 	 *
1874 	 */
1875 	if (auth && !(auth & 0x0100))
1876 		auth &= 0xff00;
1877 	fi->fi_optmsk = optmsk;
1878 	fi->fi_secmsk = secmsk;
1879 	fi->fi_auth = auth;
1880 }
1881 
1882 
1883 /* ------------------------------------------------------------------------ */
1884 /* Function:    ipf_checkripso                                              */
1885 /* Returns:     void                                                        */
1886 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1887 /*                                                                          */
1888 /* ------------------------------------------------------------------------ */
1889 static u_32_t
ipf_checkripso(u_char * s)1890 ipf_checkripso(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(fr_info_t * fin,u_char * s,int ol)1934 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1935 {
1936 	ipf_main_softc_t *softc = fin->fin_main_soft;
1937 	fr_ip_t *fi;
1938 	u_32_t doi;
1939 	u_char *t, tag, tlen, sensitivity;
1940 	int len;
1941 
1942 	if (ol < 6 || ol > 40) {
1943 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1944 		fin->fin_flx |= FI_BAD;
1945 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1946 		return 0;
1947 	}
1948 
1949 	fi = &fin->fin_fi;
1950 	fi->fi_sensitivity = 0;
1951 	/*
1952 	 * The DOI field MUST be there.
1953 	 */
1954 	bcopy(s + 2, &doi, sizeof(doi));
1955 
1956 	t = (u_char *)s + 6;
1957 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1958 		tag = *t;
1959 		tlen = *(t + 1);
1960 		if (tlen > len || tlen < 4 || tlen > 34) {
1961 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1962 			fin->fin_flx |= FI_BAD;
1963 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1964 			return 0;
1965 		}
1966 
1967 		sensitivity = 0;
1968 		/*
1969 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1970 		 * draft (16 July 1992) that has expired.
1971 		 */
1972 		if (tag == 0) {
1973 			fin->fin_flx |= FI_BAD;
1974 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1975 			continue;
1976 		} else if (tag == 1) {
1977 			if (*(t + 2) != 0) {
1978 				fin->fin_flx |= FI_BAD;
1979 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1980 				continue;
1981 			}
1982 			sensitivity = *(t + 3);
1983 			/* Category bitmap for categories 0-239 */
1984 
1985 		} else if (tag == 4) {
1986 			if (*(t + 2) != 0) {
1987 				fin->fin_flx |= FI_BAD;
1988 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1989 				continue;
1990 			}
1991 			sensitivity = *(t + 3);
1992 			/* Enumerated categories, 16bits each, upto 15 */
1993 
1994 		} else if (tag == 5) {
1995 			if (*(t + 2) != 0) {
1996 				fin->fin_flx |= FI_BAD;
1997 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1998 				continue;
1999 			}
2000 			sensitivity = *(t + 3);
2001 			/* Range of categories (2*16bits), up to 7 pairs */
2002 
2003 		} else if (tag > 127) {
2004 			/* Custom defined DOI */
2005 			;
2006 		} else {
2007 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2008 			fin->fin_flx |= FI_BAD;
2009 			continue;
2010 		}
2011 
2012 		if (sensitivity > fi->fi_sensitivity)
2013 			fi->fi_sensitivity = sensitivity;
2014 	}
2015 
2016 	return doi;
2017 }
2018 
2019 
2020 /* ------------------------------------------------------------------------ */
2021 /* Function:    ipf_makefrip                                                */
2022 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2023 /* Parameters:  hlen(I) - length of IP packet header                        */
2024 /*              ip(I)   - pointer to the IP header                          */
2025 /*              fin(IO) - pointer to packet information                     */
2026 /*                                                                          */
2027 /* Compact the IP header into a structure which contains just the info.     */
2028 /* which is useful for comparing IP headers with and store this information */
2029 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2030 /* this function will be called with either an IPv4 or IPv6 packet.         */
2031 /* ------------------------------------------------------------------------ */
2032 int
ipf_makefrip(int hlen,ip_t * ip,fr_info_t * fin)2033 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
2034 {
2035 	ipf_main_softc_t *softc = fin->fin_main_soft;
2036 	int v;
2037 
2038 	fin->fin_depth = 0;
2039 	fin->fin_hlen = (u_short)hlen;
2040 	fin->fin_ip = ip;
2041 	fin->fin_rule = 0xffffffff;
2042 	fin->fin_group[0] = -1;
2043 	fin->fin_group[1] = '\0';
2044 	fin->fin_dp = (char *)ip + hlen;
2045 
2046 	v = fin->fin_v;
2047 	if (v == 4) {
2048 		fin->fin_plen = ntohs(ip->ip_len);
2049 		fin->fin_dlen = fin->fin_plen - hlen;
2050 		ipf_pr_ipv4hdr(fin);
2051 #ifdef	USE_INET6
2052 	} else if (v == 6) {
2053 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2054 		fin->fin_dlen = fin->fin_plen;
2055 		fin->fin_plen += hlen;
2056 
2057 		ipf_pr_ipv6hdr(fin);
2058 #endif
2059 	}
2060 	if (fin->fin_ip == NULL) {
2061 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2062 		return -1;
2063 	}
2064 	return 0;
2065 }
2066 
2067 
2068 /* ------------------------------------------------------------------------ */
2069 /* Function:    ipf_portcheck                                               */
2070 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2071 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2072 /*              pop(I) - port number to evaluate                            */
2073 /*                                                                          */
2074 /* Perform a comparison of a port number against some other(s), using a     */
2075 /* structure with compare information stored in it.                         */
2076 /* ------------------------------------------------------------------------ */
2077 static INLINE int
ipf_portcheck(frpcmp_t * frp,u_32_t pop)2078 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2079 {
2080 	int err = 1;
2081 	u_32_t po;
2082 
2083 	po = frp->frp_port;
2084 
2085 	/*
2086 	 * Do opposite test to that required and continue if that succeeds.
2087 	 */
2088 	switch (frp->frp_cmp)
2089 	{
2090 	case FR_EQUAL :
2091 		if (pop != po) /* EQUAL */
2092 			err = 0;
2093 		break;
2094 	case FR_NEQUAL :
2095 		if (pop == po) /* NOTEQUAL */
2096 			err = 0;
2097 		break;
2098 	case FR_LESST :
2099 		if (pop >= po) /* LESSTHAN */
2100 			err = 0;
2101 		break;
2102 	case FR_GREATERT :
2103 		if (pop <= po) /* GREATERTHAN */
2104 			err = 0;
2105 		break;
2106 	case FR_LESSTE :
2107 		if (pop > po) /* LT or EQ */
2108 			err = 0;
2109 		break;
2110 	case FR_GREATERTE :
2111 		if (pop < po) /* GT or EQ */
2112 			err = 0;
2113 		break;
2114 	case FR_OUTRANGE :
2115 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2116 			err = 0;
2117 		break;
2118 	case FR_INRANGE :
2119 		if (pop <= po || pop >= frp->frp_top) /* In range */
2120 			err = 0;
2121 		break;
2122 	case FR_INCRANGE :
2123 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2124 			err = 0;
2125 		break;
2126 	default :
2127 		break;
2128 	}
2129 	return err;
2130 }
2131 
2132 
2133 /* ------------------------------------------------------------------------ */
2134 /* Function:    ipf_tcpudpchk                                               */
2135 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2136 /* Parameters:  fda(I) - pointer to packet information                      */
2137 /*              ft(I)  - pointer to structure with comparison data          */
2138 /*                                                                          */
2139 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2140 /* structure containing information that we want to match against.          */
2141 /* ------------------------------------------------------------------------ */
2142 int
ipf_tcpudpchk(fr_ip_t * fi,frtuc_t * ft)2143 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2144 {
2145 	int err = 1;
2146 
2147 	/*
2148 	 * Both ports should *always* be in the first fragment.
2149 	 * So far, I cannot find any cases where they can not be.
2150 	 *
2151 	 * compare destination ports
2152 	 */
2153 	if (ft->ftu_dcmp)
2154 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2155 
2156 	/*
2157 	 * compare source ports
2158 	 */
2159 	if (err && ft->ftu_scmp)
2160 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2161 
2162 	/*
2163 	 * If we don't have all the TCP/UDP header, then how can we
2164 	 * expect to do any sort of match on it ?  If we were looking for
2165 	 * TCP flags, then NO match.  If not, then match (which should
2166 	 * satisfy the "short" class too).
2167 	 */
2168 	if (err && (fi->fi_p == IPPROTO_TCP)) {
2169 		if (fi->fi_flx & FI_SHORT)
2170 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2171 		/*
2172 		 * Match the flags ?  If not, abort this match.
2173 		 */
2174 		if (ft->ftu_tcpfm &&
2175 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2176 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2177 				 ft->ftu_tcpfm, ft->ftu_tcpf));
2178 			err = 0;
2179 		}
2180 	}
2181 	return err;
2182 }
2183 
2184 
2185 /* ------------------------------------------------------------------------ */
2186 /* Function:    ipf_check_ipf                                               */
2187 /* Returns:     int - 0 == match, else no match                             */
2188 /* Parameters:  fin(I)     - pointer to packet information                  */
2189 /*              fr(I)      - pointer to filter rule                         */
2190 /*              portcmp(I) - flag indicating whether to attempt matching on */
2191 /*                           TCP/UDP port data.                             */
2192 /*                                                                          */
2193 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2194 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2195 /* this function.                                                           */
2196 /* ------------------------------------------------------------------------ */
2197 static INLINE int
ipf_check_ipf(fr_info_t * fin,frentry_t * fr,int portcmp)2198 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2199 {
2200 	u_32_t	*ld, *lm, *lip;
2201 	fripf_t *fri;
2202 	fr_ip_t *fi;
2203 	int i;
2204 
2205 	fi = &fin->fin_fi;
2206 	fri = fr->fr_ipf;
2207 	lip = (u_32_t *)fi;
2208 	lm = (u_32_t *)&fri->fri_mip;
2209 	ld = (u_32_t *)&fri->fri_ip;
2210 
2211 	/*
2212 	 * first 32 bits to check coversion:
2213 	 * IP version, TOS, TTL, protocol
2214 	 */
2215 	i = ((*lip & *lm) != *ld);
2216 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2217 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2218 	if (i)
2219 		return 1;
2220 
2221 	/*
2222 	 * Next 32 bits is a constructed bitmask indicating which IP options
2223 	 * are present (if any) in this packet.
2224 	 */
2225 	lip++, lm++, ld++;
2226 	i = ((*lip & *lm) != *ld);
2227 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2228 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2229 	if (i != 0)
2230 		return 1;
2231 
2232 	lip++, lm++, ld++;
2233 	/*
2234 	 * Unrolled loops (4 each, for 32 bits) for address checks.
2235 	 */
2236 	/*
2237 	 * Check the source address.
2238 	 */
2239 	if (fr->fr_satype == FRI_LOOKUP) {
2240 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2241 				      fi->fi_v, lip, fin->fin_plen);
2242 		if (i == -1)
2243 			return 1;
2244 		lip += 3;
2245 		lm += 3;
2246 		ld += 3;
2247 	} else {
2248 		i = ((*lip & *lm) != *ld);
2249 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2250 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2251 		if (fi->fi_v == 6) {
2252 			lip++, lm++, ld++;
2253 			i |= ((*lip & *lm) != *ld);
2254 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2255 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2256 			lip++, lm++, ld++;
2257 			i |= ((*lip & *lm) != *ld);
2258 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2259 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2260 			lip++, lm++, ld++;
2261 			i |= ((*lip & *lm) != *ld);
2262 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2263 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2264 		} else {
2265 			lip += 3;
2266 			lm += 3;
2267 			ld += 3;
2268 		}
2269 	}
2270 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2271 	if (i != 0)
2272 		return 1;
2273 
2274 	/*
2275 	 * Check the destination address.
2276 	 */
2277 	lip++, lm++, ld++;
2278 	if (fr->fr_datype == FRI_LOOKUP) {
2279 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2280 				      fi->fi_v, lip, fin->fin_plen);
2281 		if (i == -1)
2282 			return 1;
2283 		lip += 3;
2284 		lm += 3;
2285 		ld += 3;
2286 	} else {
2287 		i = ((*lip & *lm) != *ld);
2288 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2289 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2290 		if (fi->fi_v == 6) {
2291 			lip++, lm++, ld++;
2292 			i |= ((*lip & *lm) != *ld);
2293 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2294 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2295 			lip++, lm++, ld++;
2296 			i |= ((*lip & *lm) != *ld);
2297 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2298 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2299 			lip++, lm++, ld++;
2300 			i |= ((*lip & *lm) != *ld);
2301 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2302 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2303 		} else {
2304 			lip += 3;
2305 			lm += 3;
2306 			ld += 3;
2307 		}
2308 	}
2309 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2310 	if (i != 0)
2311 		return 1;
2312 	/*
2313 	 * IP addresses matched.  The next 32bits contains:
2314 	 * mast of old IP header security & authentication bits.
2315 	 */
2316 	lip++, lm++, ld++;
2317 	i = (*ld - (*lip & *lm));
2318 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2319 
2320 	/*
2321 	 * Next we have 32 bits of packet flags.
2322 	 */
2323 	lip++, lm++, ld++;
2324 	i |= (*ld - (*lip & *lm));
2325 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2326 
2327 	if (i == 0) {
2328 		/*
2329 		 * If a fragment, then only the first has what we're
2330 		 * looking for here...
2331 		 */
2332 		if (portcmp) {
2333 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2334 				i = 1;
2335 		} else {
2336 			if (fr->fr_dcmp || fr->fr_scmp ||
2337 			    fr->fr_tcpf || fr->fr_tcpfm)
2338 				i = 1;
2339 			if (fr->fr_icmpm || fr->fr_icmp) {
2340 				if (((fi->fi_p != IPPROTO_ICMP) &&
2341 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2342 				    fin->fin_off || (fin->fin_dlen < 2))
2343 					i = 1;
2344 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2345 					 fr->fr_icmp) {
2346 					FR_DEBUG(("i. %#x & %#x != %#x\n",
2347 						 fin->fin_data[0],
2348 						 fr->fr_icmpm, fr->fr_icmp));
2349 					i = 1;
2350 				}
2351 			}
2352 		}
2353 	}
2354 	return i;
2355 }
2356 
2357 
2358 /* ------------------------------------------------------------------------ */
2359 /* Function:    ipf_scanlist                                                */
2360 /* Returns:     int - result flags of scanning filter list                  */
2361 /* Parameters:  fin(I) - pointer to packet information                      */
2362 /*              pass(I) - default result to return for filtering            */
2363 /*                                                                          */
2364 /* Check the input/output list of rules for a match to the current packet.  */
2365 /* If a match is found, the value of fr_flags from the rule becomes the     */
2366 /* return value and fin->fin_fr points to the matched rule.                 */
2367 /*                                                                          */
2368 /* This function may be called recursively upto 16 times (limit inbuilt.)   */
2369 /* When unwinding, it should finish up with fin_depth as 0.                 */
2370 /*                                                                          */
2371 /* Could be per interface, but this gets real nasty when you don't have,    */
2372 /* or can't easily change, the kernel source code to .                      */
2373 /* ------------------------------------------------------------------------ */
2374 int
ipf_scanlist(fr_info_t * fin,u_32_t pass)2375 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2376 {
2377 	ipf_main_softc_t *softc = fin->fin_main_soft;
2378 	int rulen, portcmp, off, skip;
2379 	struct frentry *fr, *fnext;
2380 	u_32_t passt, passo;
2381 
2382 	/*
2383 	 * Do not allow nesting deeper than 16 levels.
2384 	 */
2385 	if (fin->fin_depth >= 16)
2386 		return pass;
2387 
2388 	fr = fin->fin_fr;
2389 
2390 	/*
2391 	 * If there are no rules in this list, return now.
2392 	 */
2393 	if (fr == NULL)
2394 		return pass;
2395 
2396 	skip = 0;
2397 	portcmp = 0;
2398 	fin->fin_depth++;
2399 	fin->fin_fr = NULL;
2400 	off = fin->fin_off;
2401 
2402 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2403 		portcmp = 1;
2404 
2405 	for (rulen = 0; fr; fr = fnext, rulen++) {
2406 		fnext = fr->fr_next;
2407 		if (skip != 0) {
2408 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2409 			skip--;
2410 			continue;
2411 		}
2412 
2413 		/*
2414 		 * In all checks below, a null (zero) value in the
2415 		 * filter struture is taken to mean a wildcard.
2416 		 *
2417 		 * check that we are working for the right interface
2418 		 */
2419 #ifdef	_KERNEL
2420 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2421 			continue;
2422 #else
2423 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2424 			printf("\n");
2425 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2426 				  FR_ISPASS(pass) ? 'p' :
2427 				  FR_ISACCOUNT(pass) ? 'A' :
2428 				  FR_ISAUTH(pass) ? 'a' :
2429 				  (pass & FR_NOMATCH) ? 'n' :'b'));
2430 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2431 			continue;
2432 		FR_VERBOSE((":i"));
2433 #endif
2434 
2435 		switch (fr->fr_type)
2436 		{
2437 		case FR_T_IPF :
2438 		case FR_T_IPF_BUILTIN :
2439 			if (ipf_check_ipf(fin, fr, portcmp))
2440 				continue;
2441 			break;
2442 #if defined(IPFILTER_BPF)
2443 		case FR_T_BPFOPC :
2444 		case FR_T_BPFOPC_BUILTIN :
2445 		    {
2446 			u_char *mc;
2447 			int wlen;
2448 
2449 			if (*fin->fin_mp == NULL)
2450 				continue;
2451 			if (fin->fin_family != fr->fr_family)
2452 				continue;
2453 			mc = (u_char *)fin->fin_m;
2454 			wlen = fin->fin_dlen + fin->fin_hlen;
2455 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2456 				continue;
2457 			break;
2458 		    }
2459 #endif
2460 		case FR_T_CALLFUNC_BUILTIN :
2461 		    {
2462 			frentry_t *f;
2463 
2464 			f = (*fr->fr_func)(fin, &pass);
2465 			if (f != NULL)
2466 				fr = f;
2467 			else
2468 				continue;
2469 			break;
2470 		    }
2471 
2472 		case FR_T_IPFEXPR :
2473 		case FR_T_IPFEXPR_BUILTIN :
2474 			if (fin->fin_family != fr->fr_family)
2475 				continue;
2476 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2477 				continue;
2478 			break;
2479 
2480 		default :
2481 			break;
2482 		}
2483 
2484 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2485 			if (fin->fin_nattag == NULL)
2486 				continue;
2487 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2488 				continue;
2489 		}
2490 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2491 
2492 		passt = fr->fr_flags;
2493 
2494 		/*
2495 		 * If the rule is a "call now" rule, then call the function
2496 		 * in the rule, if it exists and use the results from that.
2497 		 * If the function pointer is bad, just make like we ignore
2498 		 * it, except for increasing the hit counter.
2499 		 */
2500 		if ((passt & FR_CALLNOW) != 0) {
2501 			frentry_t *frs;
2502 
2503 			ATOMIC_INC64(fr->fr_hits);
2504 			if ((fr->fr_func == NULL) ||
2505 			    (fr->fr_func == (ipfunc_t)-1))
2506 				continue;
2507 
2508 			frs = fin->fin_fr;
2509 			fin->fin_fr = fr;
2510 			fr = (*fr->fr_func)(fin, &passt);
2511 			if (fr == NULL) {
2512 				fin->fin_fr = frs;
2513 				continue;
2514 			}
2515 			passt = fr->fr_flags;
2516 		}
2517 		fin->fin_fr = fr;
2518 
2519 #ifdef  IPFILTER_LOG
2520 		/*
2521 		 * Just log this packet...
2522 		 */
2523 		if ((passt & FR_LOGMASK) == FR_LOG) {
2524 			if (ipf_log_pkt(fin, passt) == -1) {
2525 				if (passt & FR_LOGORBLOCK) {
2526 					DT(frb_logfail);
2527 					passt &= ~FR_CMDMASK;
2528 					passt |= FR_BLOCK|FR_QUICK;
2529 					fin->fin_reason = FRB_LOGFAIL;
2530 				}
2531 			}
2532 		}
2533 #endif /* IPFILTER_LOG */
2534 
2535 		MUTEX_ENTER(&fr->fr_lock);
2536 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2537 		fr->fr_hits++;
2538 		MUTEX_EXIT(&fr->fr_lock);
2539 		fin->fin_rule = rulen;
2540 
2541 		passo = pass;
2542 		if (FR_ISSKIP(passt)) {
2543 			skip = fr->fr_arg;
2544 			continue;
2545 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2546 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2547 			pass = passt;
2548 		}
2549 
2550 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2551 			fin->fin_icode = fr->fr_icode;
2552 
2553 		if (fr->fr_group != -1) {
2554 			(void) strncpy(fin->fin_group,
2555 				       FR_NAME(fr, fr_group),
2556 				       strlen(FR_NAME(fr, fr_group)));
2557 		} else {
2558 			fin->fin_group[0] = '\0';
2559 		}
2560 
2561 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2562 
2563 		if (fr->fr_grphead != NULL) {
2564 			fin->fin_fr = fr->fr_grphead->fg_start;
2565 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2566 
2567 			if (FR_ISDECAPS(passt))
2568 				passt = ipf_decaps(fin, pass, fr->fr_icode);
2569 			else
2570 				passt = ipf_scanlist(fin, pass);
2571 
2572 			if (fin->fin_fr == NULL) {
2573 				fin->fin_rule = rulen;
2574 				if (fr->fr_group != -1)
2575 					(void) strncpy(fin->fin_group,
2576 						       fr->fr_names +
2577 						       fr->fr_group,
2578 						       strlen(fr->fr_names +
2579 							      fr->fr_group));
2580 				fin->fin_fr = fr;
2581 				passt = pass;
2582 			}
2583 			pass = passt;
2584 		}
2585 
2586 		if (pass & FR_QUICK) {
2587 			/*
2588 			 * Finally, if we've asked to track state for this
2589 			 * packet, set it up.  Add state for "quick" rules
2590 			 * here so that if the action fails we can consider
2591 			 * the rule to "not match" and keep on processing
2592 			 * filter rules.
2593 			 */
2594 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2595 			    !(fin->fin_flx & FI_STATE)) {
2596 				int out = fin->fin_out;
2597 
2598 				fin->fin_fr = fr;
2599 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2600 					LBUMPD(ipf_stats[out], fr_ads);
2601 				} else {
2602 					LBUMPD(ipf_stats[out], fr_bads);
2603 					pass = passo;
2604 					continue;
2605 				}
2606 			}
2607 			break;
2608 		}
2609 	}
2610 	fin->fin_depth--;
2611 	return pass;
2612 }
2613 
2614 
2615 /* ------------------------------------------------------------------------ */
2616 /* Function:    ipf_acctpkt                                                 */
2617 /* Returns:     frentry_t* - always returns NULL                            */
2618 /* Parameters:  fin(I) - pointer to packet information                      */
2619 /*              passp(IO) - pointer to current/new filter decision (unused) */
2620 /*                                                                          */
2621 /* Checks a packet against accounting rules, if there are any for the given */
2622 /* IP protocol version.                                                     */
2623 /*                                                                          */
2624 /* N.B.: this function returns NULL to match the prototype used by other    */
2625 /* functions called from the IPFilter "mainline" in ipf_check().            */
2626 /* ------------------------------------------------------------------------ */
2627 frentry_t *
ipf_acctpkt(fr_info_t * fin,u_32_t * passp)2628 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
2629 {
2630 	ipf_main_softc_t *softc = fin->fin_main_soft;
2631 	char group[FR_GROUPLEN];
2632 	frentry_t *fr, *frsave;
2633 	u_32_t pass, rulen;
2634 
2635 	passp = passp;
2636 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2637 
2638 	if (fr != NULL) {
2639 		frsave = fin->fin_fr;
2640 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2641 		rulen = fin->fin_rule;
2642 		fin->fin_fr = fr;
2643 		pass = ipf_scanlist(fin, FR_NOMATCH);
2644 		if (FR_ISACCOUNT(pass)) {
2645 			LBUMPD(ipf_stats[0], fr_acct);
2646 		}
2647 		fin->fin_fr = frsave;
2648 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2649 		fin->fin_rule = rulen;
2650 	}
2651 	return NULL;
2652 }
2653 
2654 
2655 /* ------------------------------------------------------------------------ */
2656 /* Function:    ipf_firewall                                                */
2657 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2658 /*                           were found, returns NULL.                      */
2659 /* Parameters:  fin(I) - pointer to packet information                      */
2660 /*              passp(IO) - pointer to current/new filter decision (unused) */
2661 /*                                                                          */
2662 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2663 /* there are any matches.  The first check is to see if a match can be seen */
2664 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2665 /* matching rule is found, take any appropriate actions as defined by the   */
2666 /* rule - except logging.                                                   */
2667 /* ------------------------------------------------------------------------ */
2668 static frentry_t *
ipf_firewall(fr_info_t * fin,u_32_t * passp)2669 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2670 {
2671 	ipf_main_softc_t *softc = fin->fin_main_soft;
2672 	frentry_t *fr;
2673 	u_32_t pass;
2674 	int out;
2675 
2676 	out = fin->fin_out;
2677 	pass = *passp;
2678 
2679 	/*
2680 	 * This rule cache will only affect packets that are not being
2681 	 * statefully filtered.
2682 	 */
2683 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2684 	if (fin->fin_fr != NULL)
2685 		pass = ipf_scanlist(fin, softc->ipf_pass);
2686 
2687 	if ((pass & FR_NOMATCH)) {
2688 		LBUMPD(ipf_stats[out], fr_nom);
2689 	}
2690 	fr = fin->fin_fr;
2691 
2692 	/*
2693 	 * Apply packets per second rate-limiting to a rule as required.
2694 	 */
2695 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2696 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2697 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2698 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2699 		pass |= FR_BLOCK;
2700 		LBUMPD(ipf_stats[out], fr_ppshit);
2701 		fin->fin_reason = FRB_PPSRATE;
2702 	}
2703 
2704 	/*
2705 	 * If we fail to add a packet to the authorization queue, then we
2706 	 * drop the packet later.  However, if it was added then pretend
2707 	 * we've dropped it already.
2708 	 */
2709 	if (FR_ISAUTH(pass)) {
2710 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2711 			DT1(frb_authnew, fr_info_t *, fin);
2712 			fin->fin_m = *fin->fin_mp = NULL;
2713 			fin->fin_reason = FRB_AUTHNEW;
2714 			fin->fin_error = 0;
2715 		} else {
2716 			IPFERROR(1);
2717 			fin->fin_error = ENOSPC;
2718 		}
2719 	}
2720 
2721 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2722 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2723 		(void) (*fr->fr_func)(fin, &pass);
2724 
2725 	/*
2726 	 * If a rule is a pre-auth rule, check again in the list of rules
2727 	 * loaded for authenticated use.  It does not particulary matter
2728 	 * if this search fails because a "preauth" result, from a rule,
2729 	 * is treated as "not a pass", hence the packet is blocked.
2730 	 */
2731 	if (FR_ISPREAUTH(pass)) {
2732 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2733 	}
2734 
2735 	/*
2736 	 * If the rule has "keep frag" and the packet is actually a fragment,
2737 	 * then create a fragment state entry.
2738 	 */
2739 	if (pass & FR_KEEPFRAG) {
2740 		if (fin->fin_flx & FI_FRAG) {
2741 			if (ipf_frag_new(softc, fin, pass) == -1) {
2742 				LBUMP(ipf_stats[out].fr_bnfr);
2743 			} else {
2744 				LBUMP(ipf_stats[out].fr_nfr);
2745 			}
2746 		} else {
2747 			LBUMP(ipf_stats[out].fr_cfr);
2748 		}
2749 	}
2750 
2751 	fr = fin->fin_fr;
2752 	*passp = pass;
2753 
2754 	return fr;
2755 }
2756 
2757 
2758 /* ------------------------------------------------------------------------ */
2759 /* Function:    ipf_check                                                   */
2760 /* Returns:     int -  0 == packet allowed through,                         */
2761 /*              User space:                                                 */
2762 /*                    -1 == packet blocked                                  */
2763 /*                     1 == packet not matched                              */
2764 /*                    -2 == requires authentication                         */
2765 /*              Kernel:                                                     */
2766 /*                   > 0 == filter error # for packet                       */
2767 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2768 /*             hlen(I) - length of header                                   */
2769 /*             ifp(I)  - pointer to interface this packet is on             */
2770 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2771 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2772 /*                       IP packet.                                         */
2773 /* Solaris & HP-UX ONLY :                                                   */
2774 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2775 /*                       interface & direction.                             */
2776 /*                                                                          */
2777 /* ipf_check() is the master function for all IPFilter packet processing.   */
2778 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2779 /* authorisation (or pre-authorisation), presence of related state info.,   */
2780 /* generating log entries, IP packet accounting, routing of packets as      */
2781 /* directed by firewall rules and of course whether or not to allow the     */
2782 /* packet to be further processed by the kernel.                            */
2783 /*                                                                          */
2784 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2785 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2786 /* by "mp" changed to a new buffer.                                         */
2787 /* ------------------------------------------------------------------------ */
2788 int
ipf_check(void * ctx,ip_t * ip,int hlen,void * ifp,int out,void * qif,mb_t ** mp)2789 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
2790 #if defined(_KERNEL) && defined(MENTAT)
2791     void *qif,
2792 #endif
2793     mb_t **mp)
2794 {
2795 	/*
2796 	 * The above really sucks, but short of writing a diff
2797 	 */
2798 	ipf_main_softc_t *softc = ctx;
2799 	fr_info_t frinfo;
2800 	fr_info_t *fin = &frinfo;
2801 	u_32_t pass = softc->ipf_pass;
2802 	frentry_t *fr = NULL;
2803 	int v = IP_V(ip);
2804 	mb_t *mc = NULL;
2805 	mb_t *m;
2806 	/*
2807 	 * The first part of ipf_check() deals with making sure that what goes
2808 	 * into the filtering engine makes some sense.  Information about the
2809 	 * the packet is distilled, collected into a fr_info_t structure and
2810 	 * the an attempt to ensure the buffer the packet is in is big enough
2811 	 * to hold all the required packet headers.
2812 	 */
2813 #ifdef	_KERNEL
2814 # ifdef MENTAT
2815 	qpktinfo_t *qpi = qif;
2816 
2817 #  ifdef __sparc
2818 	if ((u_int)ip & 0x3)
2819 		return 2;
2820 #  endif
2821 # else
2822 	SPL_INT(s);
2823 # endif
2824 
2825 	if (softc->ipf_running <= 0) {
2826 		return 0;
2827 	}
2828 
2829 	bzero((char *)fin, sizeof(*fin));
2830 
2831 # ifdef MENTAT
2832 	if (qpi->qpi_flags & QF_BROADCAST)
2833 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2834 	if (qpi->qpi_flags & QF_MULTICAST)
2835 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2836 	m = qpi->qpi_m;
2837 	fin->fin_qfm = m;
2838 	fin->fin_qpi = qpi;
2839 # else /* MENTAT */
2840 
2841 	m = *mp;
2842 
2843 #  if defined(M_MCAST)
2844 	if ((m->m_flags & M_MCAST) != 0)
2845 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2846 #  endif
2847 #  if defined(M_MLOOP)
2848 	if ((m->m_flags & M_MLOOP) != 0)
2849 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2850 #  endif
2851 #  if defined(M_BCAST)
2852 	if ((m->m_flags & M_BCAST) != 0)
2853 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2854 #  endif
2855 #  ifdef M_CANFASTFWD
2856 	/*
2857 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2858 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2859 	 * XXX get a "can-fast-forward" filter rule.
2860 	 */
2861 	m->m_flags &= ~M_CANFASTFWD;
2862 #  endif /* M_CANFASTFWD */
2863 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2864 				   (__FreeBSD_version < 501108))
2865 	/*
2866 	 * disable delayed checksums.
2867 	 */
2868 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2869 		in_undefer_cksum_tcpudp(m);
2870 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2871 	}
2872 #  endif /* CSUM_DELAY_DATA */
2873 # endif /* MENTAT */
2874 #else
2875 	bzero((char *)fin, sizeof(*fin));
2876 	m = *mp;
2877 # if defined(M_MCAST)
2878 	if ((m->m_flags & M_MCAST) != 0)
2879 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2880 # endif
2881 # if defined(M_MLOOP)
2882 	if ((m->m_flags & M_MLOOP) != 0)
2883 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2884 # endif
2885 # if defined(M_BCAST)
2886 	if ((m->m_flags & M_BCAST) != 0)
2887 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2888 # endif
2889 #endif /* _KERNEL */
2890 
2891 	fin->fin_v = v;
2892 	fin->fin_m = m;
2893 	fin->fin_ip = ip;
2894 	fin->fin_mp = mp;
2895 	fin->fin_out = out;
2896 	fin->fin_ifp = ifp;
2897 	fin->fin_error = ENETUNREACH;
2898 	fin->fin_hlen = (u_short)hlen;
2899 	fin->fin_dp = (char *)ip + hlen;
2900 	fin->fin_main_soft = softc;
2901 
2902 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2903 
2904 	SPL_NET(s);
2905 
2906 #ifdef	USE_INET6
2907 	if (v == 6) {
2908 		LBUMP(ipf_stats[out].fr_ipv6);
2909 		/*
2910 		 * Jumbo grams are quite likely too big for internal buffer
2911 		 * structures to handle comfortably, for now, so just drop
2912 		 * them.
2913 		 */
2914 		if (((ip6_t *)ip)->ip6_plen == 0) {
2915 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2916 			pass = FR_BLOCK|FR_NOMATCH;
2917 			fin->fin_reason = FRB_JUMBO;
2918 			goto finished;
2919 		}
2920 		fin->fin_family = AF_INET6;
2921 	} else
2922 #endif
2923 	{
2924 		fin->fin_family = AF_INET;
2925 	}
2926 
2927 	if (ipf_makefrip(hlen, ip, fin) == -1) {
2928 		DT1(frb_makefrip, fr_info_t *, fin);
2929 		pass = FR_BLOCK|FR_NOMATCH;
2930 		fin->fin_reason = FRB_MAKEFRIP;
2931 		goto finished;
2932 	}
2933 
2934 	/*
2935 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2936 	 * becomes NULL and so we have no packet to free.
2937 	 */
2938 	if (*fin->fin_mp == NULL)
2939 		goto finished;
2940 
2941 	if (!out) {
2942 		if (v == 4) {
2943 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2944 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2945 				fin->fin_flx |= FI_BADSRC;
2946 			}
2947 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2948 				LBUMPD(ipf_stats[0], fr_v4_badttl);
2949 				fin->fin_flx |= FI_LOWTTL;
2950 			}
2951 		}
2952 #ifdef USE_INET6
2953 		else  if (v == 6) {
2954 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2955 				LBUMPD(ipf_stats[0], fr_v6_badttl);
2956 				fin->fin_flx |= FI_LOWTTL;
2957 			}
2958 		}
2959 #endif
2960 	}
2961 
2962 	if (fin->fin_flx & FI_SHORT) {
2963 		LBUMPD(ipf_stats[out], fr_short);
2964 	}
2965 
2966 	READ_ENTER(&softc->ipf_mutex);
2967 
2968 	if (!out) {
2969 		switch (fin->fin_v)
2970 		{
2971 		case 4 :
2972 			if (ipf_nat_checkin(fin, &pass) == -1) {
2973 				goto filterdone;
2974 			}
2975 			break;
2976 #ifdef USE_INET6
2977 		case 6 :
2978 			if (ipf_nat6_checkin(fin, &pass) == -1) {
2979 				goto filterdone;
2980 			}
2981 			break;
2982 #endif
2983 		default :
2984 			break;
2985 		}
2986 	}
2987 	/*
2988 	 * Check auth now.
2989 	 * If a packet is found in the auth table, then skip checking
2990 	 * the access lists for permission but we do need to consider
2991 	 * the result as if it were from the ACL's.  In addition, being
2992 	 * found in the auth table means it has been seen before, so do
2993 	 * not pass it through accounting (again), lest it be counted twice.
2994 	 */
2995 	fr = ipf_auth_check(fin, &pass);
2996 	if (!out && (fr == NULL))
2997 		(void) ipf_acctpkt(fin, NULL);
2998 
2999 	if (fr == NULL) {
3000 		if ((fin->fin_flx & FI_FRAG) != 0)
3001 			fr = ipf_frag_known(fin, &pass);
3002 
3003 		if (fr == NULL)
3004 			fr = ipf_state_check(fin, &pass);
3005 	}
3006 
3007 	if ((pass & FR_NOMATCH) || (fr == NULL))
3008 		fr = ipf_firewall(fin, &pass);
3009 
3010 	/*
3011 	 * If we've asked to track state for this packet, set it up.
3012 	 * Here rather than ipf_firewall because ipf_checkauth may decide
3013 	 * to return a packet for "keep state"
3014 	 */
3015 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3016 	    !(fin->fin_flx & FI_STATE)) {
3017 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3018 			LBUMP(ipf_stats[out].fr_ads);
3019 		} else {
3020 			LBUMP(ipf_stats[out].fr_bads);
3021 			if (FR_ISPASS(pass)) {
3022 				DT(frb_stateadd);
3023 				pass &= ~FR_CMDMASK;
3024 				pass |= FR_BLOCK;
3025 				fin->fin_reason = FRB_STATEADD;
3026 			}
3027 		}
3028 	}
3029 
3030 	fin->fin_fr = fr;
3031 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3032 		fin->fin_dif = &fr->fr_dif;
3033 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3034 	}
3035 
3036 	/*
3037 	 * Only count/translate packets which will be passed on, out the
3038 	 * interface.
3039 	 */
3040 	if (out && FR_ISPASS(pass)) {
3041 		(void) ipf_acctpkt(fin, NULL);
3042 
3043 		switch (fin->fin_v)
3044 		{
3045 		case 4 :
3046 			if (ipf_nat_checkout(fin, &pass) == -1) {
3047 				;
3048 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3049 				if (ipf_updateipid(fin) == -1) {
3050 					DT(frb_updateipid);
3051 					LBUMP(ipf_stats[1].fr_ipud);
3052 					pass &= ~FR_CMDMASK;
3053 					pass |= FR_BLOCK;
3054 					fin->fin_reason = FRB_UPDATEIPID;
3055 				} else {
3056 					LBUMP(ipf_stats[0].fr_ipud);
3057 				}
3058 			}
3059 			break;
3060 #ifdef USE_INET6
3061 		case 6 :
3062 			(void) ipf_nat6_checkout(fin, &pass);
3063 			break;
3064 #endif
3065 		default :
3066 			break;
3067 		}
3068 	}
3069 
3070 filterdone:
3071 #ifdef	IPFILTER_LOG
3072 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3073 		(void) ipf_dolog(fin, &pass);
3074 	}
3075 #endif
3076 
3077 	/*
3078 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3079 	 * will work when called from inside of fr_fastroute.  Although
3080 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3081 	 * impact on code execution.
3082 	 */
3083 	fin->fin_flx &= ~FI_STATE;
3084 
3085 #if defined(FASTROUTE_RECURSION)
3086 	/*
3087 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3088 	 * a packet below can sometimes cause a recursive call into IPFilter.
3089 	 * On those platforms where that does happen, we need to hang onto
3090 	 * the filter rule just in case someone decides to remove or flush it
3091 	 * in the meantime.
3092 	 */
3093 	if (fr != NULL) {
3094 		MUTEX_ENTER(&fr->fr_lock);
3095 		fr->fr_ref++;
3096 		MUTEX_EXIT(&fr->fr_lock);
3097 	}
3098 
3099 	RWLOCK_EXIT(&softc->ipf_mutex);
3100 #endif
3101 
3102 	if ((pass & FR_RETMASK) != 0) {
3103 		/*
3104 		 * Should we return an ICMP packet to indicate error
3105 		 * status passing through the packet filter ?
3106 		 * WARNING: ICMP error packets AND TCP RST packets should
3107 		 * ONLY be sent in repsonse to incoming packets.  Sending
3108 		 * them in response to outbound packets can result in a
3109 		 * panic on some operating systems.
3110 		 */
3111 		if (!out) {
3112 			if (pass & FR_RETICMP) {
3113 				int dst;
3114 
3115 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3116 					dst = 1;
3117 				else
3118 					dst = 0;
3119 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3120 							 dst);
3121 				LBUMP(ipf_stats[0].fr_ret);
3122 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3123 				   !(fin->fin_flx & FI_SHORT)) {
3124 				if (((fin->fin_flx & FI_OOW) != 0) ||
3125 				    (ipf_send_reset(fin) == 0)) {
3126 					LBUMP(ipf_stats[1].fr_ret);
3127 				}
3128 			}
3129 
3130 			/*
3131 			 * When using return-* with auth rules, the auth code
3132 			 * takes over disposing of this packet.
3133 			 */
3134 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3135 				DT1(frb_authcapture, fr_info_t *, fin);
3136 				fin->fin_m = *fin->fin_mp = NULL;
3137 				fin->fin_reason = FRB_AUTHCAPTURE;
3138 				m = NULL;
3139 			}
3140 		} else {
3141 			if (pass & FR_RETRST) {
3142 				fin->fin_error = ECONNRESET;
3143 			}
3144 		}
3145 	}
3146 
3147 	/*
3148 	 * After the above so that ICMP unreachables and TCP RSTs get
3149 	 * created properly.
3150 	 */
3151 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3152 		ipf_nat_uncreate(fin);
3153 
3154 	/*
3155 	 * If we didn't drop off the bottom of the list of rules (and thus
3156 	 * the 'current' rule fr is not NULL), then we may have some extra
3157 	 * instructions about what to do with a packet.
3158 	 * Once we're finished return to our caller, freeing the packet if
3159 	 * we are dropping it.
3160 	 */
3161 	if (fr != NULL) {
3162 		frdest_t *fdp;
3163 
3164 		/*
3165 		 * Generate a duplicated packet first because ipf_fastroute
3166 		 * can lead to fin_m being free'd... not good.
3167 		 */
3168 		fdp = fin->fin_dif;
3169 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3170 		    (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
3171 			mc = M_COPY(fin->fin_m);
3172 			if (mc != NULL)
3173 				ipf_fastroute(mc, &mc, fin, fdp);
3174 		}
3175 
3176 		fdp = fin->fin_tif;
3177 		if (!out && (pass & FR_FASTROUTE)) {
3178 			/*
3179 			 * For fastroute rule, no destination interface defined
3180 			 * so pass NULL as the frdest_t parameter
3181 			 */
3182 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3183 			m = *mp = NULL;
3184 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3185 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3186 			/* this is for to rules: */
3187 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3188 			m = *mp = NULL;
3189 		}
3190 
3191 #if defined(FASTROUTE_RECURSION)
3192 		(void) ipf_derefrule(softc, &fr);
3193 #endif
3194 	}
3195 #if !defined(FASTROUTE_RECURSION)
3196 	RWLOCK_EXIT(&softc->ipf_mutex);
3197 #endif
3198 
3199 finished:
3200 	if (!FR_ISPASS(pass)) {
3201 		LBUMP(ipf_stats[out].fr_block);
3202 		if (*mp != NULL) {
3203 #ifdef _KERNEL
3204 			FREE_MB_T(*mp);
3205 #endif
3206 			m = *mp = NULL;
3207 		}
3208 	} else {
3209 		LBUMP(ipf_stats[out].fr_pass);
3210 #if defined(_KERNEL) && defined(__sgi)
3211 		if ((fin->fin_hbuf != NULL) &&
3212 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3213 			COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3214 		}
3215 #endif
3216 	}
3217 
3218 	SPL_X(s);
3219 
3220 	if (fin->fin_m == NULL && fin->fin_flx & FI_BAD &&
3221 	    fin->fin_reason == FRB_PULLUP) {
3222 		/* m_pullup() has freed the mbuf */
3223 		LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3224 		return (-1);
3225 	}
3226 
3227 #ifdef _KERNEL
3228 	if (FR_ISPASS(pass))
3229 		return 0;
3230 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3231 	return fin->fin_error;
3232 #else /* _KERNEL */
3233 	if (*mp != NULL)
3234 		(*mp)->mb_ifp = fin->fin_ifp;
3235 	blockreason = fin->fin_reason;
3236 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3237 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3238 		if ((pass & FR_NOMATCH) != 0)
3239 			return 1;
3240 
3241 	if ((pass & FR_RETMASK) != 0)
3242 		switch (pass & FR_RETMASK)
3243 		{
3244 		case FR_RETRST :
3245 			return 3;
3246 		case FR_RETICMP :
3247 			return 4;
3248 		case FR_FAKEICMP :
3249 			return 5;
3250 		}
3251 
3252 	switch (pass & FR_CMDMASK)
3253 	{
3254 	case FR_PASS :
3255 		return 0;
3256 	case FR_BLOCK :
3257 		return -1;
3258 	case FR_AUTH :
3259 		return -2;
3260 	case FR_ACCOUNT :
3261 		return -3;
3262 	case FR_PREAUTH :
3263 		return -4;
3264 	}
3265 	return 2;
3266 #endif /* _KERNEL */
3267 }
3268 
3269 
3270 #ifdef	IPFILTER_LOG
3271 /* ------------------------------------------------------------------------ */
3272 /* Function:    ipf_dolog                                                   */
3273 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3274 /* Parameters:  fin(I) - pointer to packet information                      */
3275 /*              passp(IO) - pointer to current/new filter decision (unused) */
3276 /*                                                                          */
3277 /* Checks flags set to see how a packet should be logged, if it is to be    */
3278 /* logged.  Adjust statistics based on its success or not.                  */
3279 /* ------------------------------------------------------------------------ */
3280 frentry_t *
ipf_dolog(fr_info_t * fin,u_32_t * passp)3281 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3282 {
3283 	ipf_main_softc_t *softc = fin->fin_main_soft;
3284 	u_32_t pass;
3285 	int out;
3286 
3287 	out = fin->fin_out;
3288 	pass = *passp;
3289 
3290 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3291 		pass |= FF_LOGNOMATCH;
3292 		LBUMPD(ipf_stats[out], fr_npkl);
3293 		goto logit;
3294 
3295 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3296 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3297 		if ((pass & FR_LOGMASK) != FR_LOGP)
3298 			pass |= FF_LOGPASS;
3299 		LBUMPD(ipf_stats[out], fr_ppkl);
3300 		goto logit;
3301 
3302 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3303 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3304 		if ((pass & FR_LOGMASK) != FR_LOGB)
3305 			pass |= FF_LOGBLOCK;
3306 		LBUMPD(ipf_stats[out], fr_bpkl);
3307 
3308 logit:
3309 		if (ipf_log_pkt(fin, pass) == -1) {
3310 			/*
3311 			 * If the "or-block" option has been used then
3312 			 * block the packet if we failed to log it.
3313 			 */
3314 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3315 				DT1(frb_logfail2, u_int, pass);
3316 				pass &= ~FR_CMDMASK;
3317 				pass |= FR_BLOCK;
3318 				fin->fin_reason = FRB_LOGFAIL2;
3319 			}
3320 		}
3321 		*passp = pass;
3322 	}
3323 
3324 	return fin->fin_fr;
3325 }
3326 #endif /* IPFILTER_LOG */
3327 
3328 
3329 /* ------------------------------------------------------------------------ */
3330 /* Function:    ipf_cksum                                                   */
3331 /* Returns:     u_short - IP header checksum                                */
3332 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3333 /*              len(I)  - length of buffer in bytes                         */
3334 /*                                                                          */
3335 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3336 /*                                                                          */
3337 /* N.B.: addr should be 16bit aligned.                                      */
3338 /* ------------------------------------------------------------------------ */
3339 u_short
ipf_cksum(u_short * addr,int len)3340 ipf_cksum(u_short *addr, int len)
3341 {
3342 	u_32_t sum = 0;
3343 
3344 	for (sum = 0; len > 1; len -= 2)
3345 		sum += *addr++;
3346 
3347 	/* mop up an odd byte, if necessary */
3348 	if (len == 1)
3349 		sum += *(u_char *)addr;
3350 
3351 	/*
3352 	 * add back carry outs from top 16 bits to low 16 bits
3353 	 */
3354 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3355 	sum += (sum >> 16);			/* add carry */
3356 	return (u_short)(~sum);
3357 }
3358 
3359 
3360 /* ------------------------------------------------------------------------ */
3361 /* Function:    fr_cksum                                                    */
3362 /* Returns:     u_short - layer 4 checksum                                  */
3363 /* Parameters:  fin(I)     - pointer to packet information                  */
3364 /*              ip(I)      - pointer to IP header                           */
3365 /*              l4proto(I) - protocol to caclulate checksum for             */
3366 /*              l4hdr(I)   - pointer to layer 4 header                      */
3367 /*                                                                          */
3368 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3369 /* in the IP header "ip" to seed it.                                        */
3370 /*                                                                          */
3371 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3372 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3373 /* odd sizes.                                                               */
3374 /*                                                                          */
3375 /* Expects ip_len and ip_off to be in network byte order when called.       */
3376 /* ------------------------------------------------------------------------ */
3377 u_short
fr_cksum(fr_info_t * fin,ip_t * ip,int l4proto,void * l4hdr)3378 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3379 {
3380 	u_short *sp, slen, sumsave, *csump;
3381 	u_int sum, sum2;
3382 	int hlen;
3383 	int off;
3384 #ifdef	USE_INET6
3385 	ip6_t *ip6;
3386 #endif
3387 
3388 	csump = NULL;
3389 	sumsave = 0;
3390 	sp = NULL;
3391 	slen = 0;
3392 	hlen = 0;
3393 	sum = 0;
3394 
3395 	sum = htons((u_short)l4proto);
3396 	/*
3397 	 * Add up IP Header portion
3398 	 */
3399 #ifdef	USE_INET6
3400 	if (IP_V(ip) == 4) {
3401 #endif
3402 		hlen = IP_HL(ip) << 2;
3403 		off = hlen;
3404 		sp = (u_short *)&ip->ip_src;
3405 		sum += *sp++;	/* ip_src */
3406 		sum += *sp++;
3407 		sum += *sp++;	/* ip_dst */
3408 		sum += *sp++;
3409 #ifdef	USE_INET6
3410 	} else if (IP_V(ip) == 6) {
3411 		ip6 = (ip6_t *)ip;
3412 		hlen = sizeof(*ip6);
3413 		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3414 		sp = (u_short *)&ip6->ip6_src;
3415 		sum += *sp++;	/* ip6_src */
3416 		sum += *sp++;
3417 		sum += *sp++;
3418 		sum += *sp++;
3419 		sum += *sp++;
3420 		sum += *sp++;
3421 		sum += *sp++;
3422 		sum += *sp++;
3423 		/* This needs to be routing header aware. */
3424 		sum += *sp++;	/* ip6_dst */
3425 		sum += *sp++;
3426 		sum += *sp++;
3427 		sum += *sp++;
3428 		sum += *sp++;
3429 		sum += *sp++;
3430 		sum += *sp++;
3431 		sum += *sp++;
3432 	} else {
3433 		return 0xffff;
3434 	}
3435 #endif
3436 	slen = fin->fin_plen - off;
3437 	sum += htons(slen);
3438 
3439 	switch (l4proto)
3440 	{
3441 	case IPPROTO_UDP :
3442 		csump = &((udphdr_t *)l4hdr)->uh_sum;
3443 		break;
3444 
3445 	case IPPROTO_TCP :
3446 		csump = &((tcphdr_t *)l4hdr)->th_sum;
3447 		break;
3448 	case IPPROTO_ICMP :
3449 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3450 		sum = 0;	/* Pseudo-checksum is not included */
3451 		break;
3452 #ifdef USE_INET6
3453 	case IPPROTO_ICMPV6 :
3454 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3455 		break;
3456 #endif
3457 	default :
3458 		break;
3459 	}
3460 
3461 	if (csump != NULL) {
3462 		sumsave = *csump;
3463 		*csump = 0;
3464 	}
3465 
3466 	sum2 = ipf_pcksum(fin, off, sum);
3467 	if (csump != NULL)
3468 		*csump = sumsave;
3469 	return sum2;
3470 }
3471 
3472 
3473 /* ------------------------------------------------------------------------ */
3474 /* Function:    ipf_findgroup                                               */
3475 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3476 /* Parameters:  softc(I) - pointer to soft context main structure           */
3477 /*              group(I) - group name to search for                         */
3478 /*              unit(I)  - device to which this group belongs               */
3479 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3480 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3481 /*                         to where to add the next (last) group or where   */
3482 /*                         to delete group from.                            */
3483 /*                                                                          */
3484 /* Search amongst the defined groups for a particular group number.         */
3485 /* ------------------------------------------------------------------------ */
3486 frgroup_t *
ipf_findgroup(ipf_main_softc_t * softc,char * group,minor_t unit,int set,frgroup_t *** fgpp)3487 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3488     frgroup_t ***fgpp)
3489 {
3490 	frgroup_t *fg, **fgp;
3491 
3492 	/*
3493 	 * Which list of groups to search in is dependent on which list of
3494 	 * rules are being operated on.
3495 	 */
3496 	fgp = &softc->ipf_groups[unit][set];
3497 
3498 	while ((fg = *fgp) != NULL) {
3499 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3500 			break;
3501 		else
3502 			fgp = &fg->fg_next;
3503 	}
3504 	if (fgpp != NULL)
3505 		*fgpp = fgp;
3506 	return fg;
3507 }
3508 
3509 
3510 /* ------------------------------------------------------------------------ */
3511 /* Function:    ipf_group_add                                               */
3512 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3513 /*                            != NULL == pointer to the group               */
3514 /* Parameters:  softc(I) - pointer to soft context main structure           */
3515 /*              num(I)   - group number to add                              */
3516 /*              head(I)  - rule pointer that is using this as the head      */
3517 /*              flags(I) - rule flags which describe the type of rule it is */
3518 /*              unit(I)  - device to which this group will belong to        */
3519 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3520 /* Write Locks: ipf_mutex                                                   */
3521 /*                                                                          */
3522 /* Add a new group head, or if it already exists, increase the reference    */
3523 /* count to it.                                                             */
3524 /* ------------------------------------------------------------------------ */
3525 frgroup_t *
ipf_group_add(ipf_main_softc_t * softc,char * group,void * head,u_32_t flags,minor_t unit,int set)3526 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3527     minor_t unit, int set)
3528 {
3529 	frgroup_t *fg, **fgp;
3530 	u_32_t gflags;
3531 
3532 	if (group == NULL)
3533 		return NULL;
3534 
3535 	if (unit == IPL_LOGIPF && *group == '\0')
3536 		return NULL;
3537 
3538 	fgp = NULL;
3539 	gflags = flags & FR_INOUT;
3540 
3541 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3542 	if (fg != NULL) {
3543 		if (fg->fg_head == NULL && head != NULL)
3544 			fg->fg_head = head;
3545 		if (fg->fg_flags == 0)
3546 			fg->fg_flags = gflags;
3547 		else if (gflags != fg->fg_flags)
3548 			return NULL;
3549 		fg->fg_ref++;
3550 		return fg;
3551 	}
3552 
3553 	KMALLOC(fg, frgroup_t *);
3554 	if (fg != NULL) {
3555 		fg->fg_head = head;
3556 		fg->fg_start = NULL;
3557 		fg->fg_next = *fgp;
3558 		bcopy(group, fg->fg_name, strlen(group) + 1);
3559 		fg->fg_flags = gflags;
3560 		fg->fg_ref = 1;
3561 		fg->fg_set = &softc->ipf_groups[unit][set];
3562 		*fgp = fg;
3563 	}
3564 	return fg;
3565 }
3566 
3567 
3568 /* ------------------------------------------------------------------------ */
3569 /* Function:    ipf_group_del                                               */
3570 /* Returns:     int      - number of rules deleted                          */
3571 /* Parameters:  softc(I) - pointer to soft context main structure           */
3572 /*              group(I) - group name to delete                             */
3573 /*              fr(I)    - filter rule from which group is referenced       */
3574 /* Write Locks: ipf_mutex                                                   */
3575 /*                                                                          */
3576 /* This function is called whenever a reference to a group is to be dropped */
3577 /* and thus its reference count needs to be lowered and the group free'd if */
3578 /* the reference count reaches zero. Passing in fr is really for the sole   */
3579 /* purpose of knowing when the head rule is being deleted.                  */
3580 /* ------------------------------------------------------------------------ */
3581 void
ipf_group_del(ipf_main_softc_t * softc,frgroup_t * group,frentry_t * fr)3582 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3583 {
3584 
3585 	if (group->fg_head == fr)
3586 		group->fg_head = NULL;
3587 
3588 	group->fg_ref--;
3589 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3590 		ipf_group_free(group);
3591 }
3592 
3593 
3594 /* ------------------------------------------------------------------------ */
3595 /* Function:    ipf_group_free                                              */
3596 /* Returns:     Nil                                                         */
3597 /* Parameters:  group(I) - pointer to filter rule group                     */
3598 /*                                                                          */
3599 /* Remove the group from the list of groups and free it.                    */
3600 /* ------------------------------------------------------------------------ */
3601 static void
ipf_group_free(frgroup_t * group)3602 ipf_group_free(frgroup_t *group)
3603 {
3604 	frgroup_t **gp;
3605 
3606 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3607 		if (*gp == group) {
3608 			*gp = group->fg_next;
3609 			break;
3610 		}
3611 	}
3612 	KFREE(group);
3613 }
3614 
3615 
3616 /* ------------------------------------------------------------------------ */
3617 /* Function:    ipf_group_flush                                             */
3618 /* Returns:     int      - number of rules flush from group                 */
3619 /* Parameters:  softc(I) - pointer to soft context main structure           */
3620 /* Parameters:  group(I) - pointer to filter rule group                     */
3621 /*                                                                          */
3622 /* Remove all of the rules that currently are listed under the given group. */
3623 /* ------------------------------------------------------------------------ */
3624 static int
ipf_group_flush(ipf_main_softc_t * softc,frgroup_t * group)3625 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3626 {
3627 	int gone = 0;
3628 
3629 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3630 
3631 	return gone;
3632 }
3633 
3634 
3635 /* ------------------------------------------------------------------------ */
3636 /* Function:    ipf_getrulen                                                */
3637 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3638 /* Parameters:  softc(I) - pointer to soft context main structure           */
3639 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3640 /*              flags(I) - which set of rules to find the rule in           */
3641 /*              group(I) - group name                                       */
3642 /*              n(I)     - rule number to find                              */
3643 /*                                                                          */
3644 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3645 /* group # g doesn't exist or there are less than n rules in the group.     */
3646 /* ------------------------------------------------------------------------ */
3647 frentry_t *
ipf_getrulen(ipf_main_softc_t * softc,int unit,char * group,u_32_t n)3648 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3649 {
3650 	frentry_t *fr;
3651 	frgroup_t *fg;
3652 
3653 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3654 	if (fg == NULL)
3655 		return NULL;
3656 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3657 		;
3658 	if (n != 0)
3659 		return NULL;
3660 	return fr;
3661 }
3662 
3663 
3664 /* ------------------------------------------------------------------------ */
3665 /* Function:    ipf_flushlist                                               */
3666 /* Returns:     int - >= 0 - number of flushed rules                        */
3667 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3668 /*              nfreedp(O) - pointer to int where flush count is stored     */
3669 /*              listp(I)   - pointer to list to flush pointer               */
3670 /* Write Locks: ipf_mutex                                                   */
3671 /*                                                                          */
3672 /* Recursively flush rules from the list, descending groups as they are     */
3673 /* encountered.  if a rule is the head of a group and it has lost all its   */
3674 /* group members, then also delete the group reference.  nfreedp is needed  */
3675 /* to store the accumulating count of rules removed, whereas the returned   */
3676 /* value is just the number removed from the current list.  The latter is   */
3677 /* needed to correctly adjust reference counts on rules that define groups. */
3678 /*                                                                          */
3679 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3680 /* ------------------------------------------------------------------------ */
3681 static int
ipf_flushlist(ipf_main_softc_t * softc,int * nfreedp,frentry_t ** listp)3682 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3683 {
3684 	int freed = 0;
3685 	frentry_t *fp;
3686 
3687 	while ((fp = *listp) != NULL) {
3688 		if ((fp->fr_type & FR_T_BUILTIN) ||
3689 		    !(fp->fr_flags & FR_COPIED)) {
3690 			listp = &fp->fr_next;
3691 			continue;
3692 		}
3693 		*listp = fp->fr_next;
3694 		if (fp->fr_next != NULL)
3695 			fp->fr_next->fr_pnext = fp->fr_pnext;
3696 		fp->fr_pnext = NULL;
3697 
3698 		if (fp->fr_grphead != NULL) {
3699 			freed += ipf_group_flush(softc, fp->fr_grphead);
3700 			fp->fr_names[fp->fr_grhead] = '\0';
3701 		}
3702 
3703 		if (fp->fr_icmpgrp != NULL) {
3704 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3705 			fp->fr_names[fp->fr_icmphead] = '\0';
3706 		}
3707 
3708 		if (fp->fr_srctrack.ht_max_nodes)
3709 			ipf_rb_ht_flush(&fp->fr_srctrack);
3710 
3711 		fp->fr_next = NULL;
3712 
3713 		ASSERT(fp->fr_ref > 0);
3714 		if (ipf_derefrule(softc, &fp) == 0)
3715 			freed++;
3716 	}
3717 	*nfreedp += freed;
3718 	return freed;
3719 }
3720 
3721 
3722 /* ------------------------------------------------------------------------ */
3723 /* Function:    ipf_flush                                                   */
3724 /* Returns:     int - >= 0 - number of flushed rules                        */
3725 /* Parameters:  softc(I) - pointer to soft context main structure           */
3726 /*              unit(I)  - device for which to flush rules                  */
3727 /*              flags(I) - which set of rules to flush                      */
3728 /*                                                                          */
3729 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3730 /* and IPv6) as defined by the value of flags.                              */
3731 /* ------------------------------------------------------------------------ */
3732 int
ipf_flush(ipf_main_softc_t * softc,minor_t unit,int flags)3733 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3734 {
3735 	int flushed = 0, set;
3736 
3737 	WRITE_ENTER(&softc->ipf_mutex);
3738 
3739 	set = softc->ipf_active;
3740 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3741 		set = 1 - set;
3742 
3743 	if (flags & FR_OUTQUE) {
3744 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3745 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3746 	}
3747 	if (flags & FR_INQUE) {
3748 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3749 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3750 	}
3751 
3752 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3753 				    flags & (FR_INQUE|FR_OUTQUE));
3754 
3755 	RWLOCK_EXIT(&softc->ipf_mutex);
3756 
3757 	if (unit == IPL_LOGIPF) {
3758 		int tmp;
3759 
3760 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3761 		if (tmp >= 0)
3762 			flushed += tmp;
3763 	}
3764 	return flushed;
3765 }
3766 
3767 
3768 /* ------------------------------------------------------------------------ */
3769 /* Function:    ipf_flush_groups                                            */
3770 /* Returns:     int - >= 0 - number of flushed rules                        */
3771 /* Parameters:  softc(I)  - soft context pointerto work with                */
3772 /*              grhead(I) - pointer to the start of the group list to flush */
3773 /*              flags(I)  - which set of rules to flush                     */
3774 /*                                                                          */
3775 /* Walk through all of the groups under the given group head and remove all */
3776 /* of those that match the flags passed in. The for loop here is bit more   */
3777 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3778 /* may end up removing not only the structure pointed to by "fg" but also   */
3779 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3780 /* removed from the group then it is necessary to start again.              */
3781 /* ------------------------------------------------------------------------ */
3782 static int
ipf_flush_groups(ipf_main_softc_t * softc,frgroup_t ** grhead,int flags)3783 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3784 {
3785 	frentry_t *fr, **frp;
3786 	frgroup_t *fg, **fgp;
3787 	int flushed = 0;
3788 	int removed = 0;
3789 
3790 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3791 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3792 			fg = fg->fg_next;
3793 		if (fg == NULL)
3794 			break;
3795 		removed = 0;
3796 		frp = &fg->fg_start;
3797 		while ((removed == 0) && ((fr = *frp) != NULL)) {
3798 			if ((fr->fr_flags & flags) == 0) {
3799 				frp = &fr->fr_next;
3800 			} else {
3801 				if (fr->fr_next != NULL)
3802 					fr->fr_next->fr_pnext = fr->fr_pnext;
3803 				*frp = fr->fr_next;
3804 				fr->fr_pnext = NULL;
3805 				fr->fr_next = NULL;
3806 				(void) ipf_derefrule(softc, &fr);
3807 				flushed++;
3808 				removed++;
3809 			}
3810 		}
3811 		if (removed == 0)
3812 			fgp = &fg->fg_next;
3813 	}
3814 	return flushed;
3815 }
3816 
3817 
3818 /* ------------------------------------------------------------------------ */
3819 /* Function:    memstr                                                      */
3820 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3821 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3822 /*              dst(I)  - pointer to byte sequence to search                */
3823 /*              slen(I) - match length                                      */
3824 /*              dlen(I) - length available to search in                     */
3825 /*                                                                          */
3826 /* Search dst for a sequence of bytes matching those at src and extend for  */
3827 /* slen bytes.                                                              */
3828 /* ------------------------------------------------------------------------ */
3829 char *
memstr(const char * src,char * dst,size_t slen,size_t dlen)3830 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3831 {
3832 	char *s = NULL;
3833 
3834 	while (dlen >= slen) {
3835 		if (memcmp(src, dst, slen) == 0) {
3836 			s = dst;
3837 			break;
3838 		}
3839 		dst++;
3840 		dlen--;
3841 	}
3842 	return s;
3843 }
3844 
3845 
3846 /* ------------------------------------------------------------------------ */
3847 /* Function:    ipf_fixskip                                                 */
3848 /* Returns:     Nil                                                         */
3849 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3850 /*              rp(I)        - rule added/removed with skip in it.          */
3851 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3852 /*                             depending on whether a rule was just added   */
3853 /*                             or removed.                                  */
3854 /*                                                                          */
3855 /* Adjust all the rules in a list which would have skip'd past the position */
3856 /* where we are inserting to skip to the right place given the change.      */
3857 /* ------------------------------------------------------------------------ */
3858 void
ipf_fixskip(frentry_t ** listp,frentry_t * rp,int addremove)3859 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3860 {
3861 	int rules, rn;
3862 	frentry_t *fp;
3863 
3864 	rules = 0;
3865 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3866 		rules++;
3867 
3868 	if (!fp)
3869 		return;
3870 
3871 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3872 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3873 			fp->fr_arg += addremove;
3874 }
3875 
3876 
3877 #ifdef	_KERNEL
3878 /* ------------------------------------------------------------------------ */
3879 /* Function:    count4bits                                                  */
3880 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3881 /* Parameters:  ip(I) - 32bit IP address                                    */
3882 /*                                                                          */
3883 /* IPv4 ONLY                                                                */
3884 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3885 /* consecutive 1's is different to that passed, return -1, else return #    */
3886 /* of bits.                                                                 */
3887 /* ------------------------------------------------------------------------ */
3888 int
count4bits(u_32_t ip)3889 count4bits(u_32_t ip)
3890 {
3891 	u_32_t	ipn;
3892 	int	cnt = 0, i, j;
3893 
3894 	ip = ipn = ntohl(ip);
3895 	for (i = 32; i; i--, ipn *= 2)
3896 		if (ipn & 0x80000000)
3897 			cnt++;
3898 		else
3899 			break;
3900 	ipn = 0;
3901 	for (i = 32, j = cnt; i; i--, j--) {
3902 		ipn *= 2;
3903 		if (j > 0)
3904 			ipn++;
3905 	}
3906 	if (ipn == ip)
3907 		return cnt;
3908 	return -1;
3909 }
3910 
3911 
3912 /* ------------------------------------------------------------------------ */
3913 /* Function:    count6bits                                                  */
3914 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3915 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3916 /*                                                                          */
3917 /* IPv6 ONLY                                                                */
3918 /* count consecutive 1's in bit mask.                                       */
3919 /* ------------------------------------------------------------------------ */
3920 # ifdef USE_INET6
3921 int
count6bits(u_32_t * msk)3922 count6bits(u_32_t *msk)
3923 {
3924 	int i = 0, k;
3925 	u_32_t j;
3926 
3927 	for (k = 3; k >= 0; k--)
3928 		if (msk[k] == 0xffffffff)
3929 			i += 32;
3930 		else {
3931 			for (j = msk[k]; j; j <<= 1)
3932 				if (j & 0x80000000)
3933 					i++;
3934 		}
3935 	return i;
3936 }
3937 # endif
3938 #endif /* _KERNEL */
3939 
3940 
3941 /* ------------------------------------------------------------------------ */
3942 /* Function:    ipf_synclist                                                */
3943 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3944 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3945 /*              ifp(I) - interface pointer for limiting sync lookups        */
3946 /* Write Locks: ipf_mutex                                                   */
3947 /*                                                                          */
3948 /* Walk through a list of filter rules and resolve any interface names into */
3949 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3950 /* used in the rule.  The interface pointer is used to limit the lookups to */
3951 /* a specific set of matching names if it is non-NULL.                      */
3952 /* Errors can occur when resolving the destination name of to/dup-to fields */
3953 /* when the name points to a pool and that pool doest not exist. If this    */
3954 /* does happen then it is necessary to check if there are any lookup refs   */
3955 /* that need to be dropped before returning with an error.                  */
3956 /* ------------------------------------------------------------------------ */
3957 static int
ipf_synclist(ipf_main_softc_t * softc,frentry_t * fr,void * ifp)3958 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3959 {
3960 	frentry_t *frt, *start = fr;
3961 	frdest_t *fdp;
3962 	char *name;
3963 	int error;
3964 	void *ifa;
3965 	int v, i;
3966 
3967 	error = 0;
3968 
3969 	for (; fr; fr = fr->fr_next) {
3970 		if (fr->fr_family == AF_INET)
3971 			v = 4;
3972 		else if (fr->fr_family == AF_INET6)
3973 			v = 6;
3974 		else
3975 			v = 0;
3976 
3977 		/*
3978 		 * Lookup all the interface names that are part of the rule.
3979 		 */
3980 		for (i = 0; i < 4; i++) {
3981 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3982 				continue;
3983 			if (fr->fr_ifnames[i] == -1)
3984 				continue;
3985 			name = FR_NAME(fr, fr_ifnames[i]);
3986 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3987 		}
3988 
3989 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3990 			if (fr->fr_satype != FRI_NORMAL &&
3991 			    fr->fr_satype != FRI_LOOKUP) {
3992 				ifa = ipf_resolvenic(softc, fr->fr_names +
3993 						     fr->fr_sifpidx, v);
3994 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3995 					    &fr->fr_src6, &fr->fr_smsk6);
3996 			}
3997 			if (fr->fr_datype != FRI_NORMAL &&
3998 			    fr->fr_datype != FRI_LOOKUP) {
3999 				ifa = ipf_resolvenic(softc, fr->fr_names +
4000 						     fr->fr_sifpidx, v);
4001 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4002 					    &fr->fr_dst6, &fr->fr_dmsk6);
4003 			}
4004 		}
4005 
4006 		fdp = &fr->fr_tifs[0];
4007 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4008 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4009 			if (error != 0)
4010 				goto unwind;
4011 		}
4012 
4013 		fdp = &fr->fr_tifs[1];
4014 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4015 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4016 			if (error != 0)
4017 				goto unwind;
4018 		}
4019 
4020 		fdp = &fr->fr_dif;
4021 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4022 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4023 			if (error != 0)
4024 				goto unwind;
4025 		}
4026 
4027 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4028 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4029 			fr->fr_srcptr = ipf_lookup_res_num(softc,
4030 							   fr->fr_srctype,
4031 							   IPL_LOGIPF,
4032 							   fr->fr_srcnum,
4033 							   &fr->fr_srcfunc);
4034 		}
4035 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4036 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4037 			fr->fr_dstptr = ipf_lookup_res_num(softc,
4038 							   fr->fr_dsttype,
4039 							   IPL_LOGIPF,
4040 							   fr->fr_dstnum,
4041 							   &fr->fr_dstfunc);
4042 		}
4043 	}
4044 	return 0;
4045 
4046 unwind:
4047 	for (frt = start; frt != fr; fr = fr->fr_next) {
4048 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4049 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4050 				ipf_lookup_deref(softc, frt->fr_srctype,
4051 						 frt->fr_srcptr);
4052 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4053 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4054 				ipf_lookup_deref(softc, frt->fr_dsttype,
4055 						 frt->fr_dstptr);
4056 	}
4057 	return error;
4058 }
4059 
4060 
4061 /* ------------------------------------------------------------------------ */
4062 /* Function:    ipf_sync                                                    */
4063 /* Returns:     void                                                        */
4064 /* Parameters:  Nil                                                         */
4065 /*                                                                          */
4066 /* ipf_sync() is called when we suspect that the interface list or          */
4067 /* information about interfaces (like IP#) has changed.  Go through all     */
4068 /* filter rules, NAT entries and the state table and check if anything      */
4069 /* needs to be changed/updated.                                             */
4070 /* ------------------------------------------------------------------------ */
4071 int
ipf_sync(ipf_main_softc_t * softc,void * ifp)4072 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4073 {
4074 	int i;
4075 
4076 # if !SOLARIS
4077 	ipf_nat_sync(softc, ifp);
4078 	ipf_state_sync(softc, ifp);
4079 	ipf_lookup_sync(softc, ifp);
4080 # endif
4081 
4082 	WRITE_ENTER(&softc->ipf_mutex);
4083 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4084 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4085 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4086 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4087 
4088 	for (i = 0; i < IPL_LOGSIZE; i++) {
4089 		frgroup_t *g;
4090 
4091 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4092 			(void) ipf_synclist(softc, g->fg_start, ifp);
4093 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4094 			(void) ipf_synclist(softc, g->fg_start, ifp);
4095 	}
4096 	RWLOCK_EXIT(&softc->ipf_mutex);
4097 
4098 	return 0;
4099 }
4100 
4101 
4102 /*
4103  * In the functions below, bcopy() is called because the pointer being
4104  * copied _from_ in this instance is a pointer to a char buf (which could
4105  * end up being unaligned) and on the kernel's local stack.
4106  */
4107 /* ------------------------------------------------------------------------ */
4108 /* Function:    copyinptr                                                   */
4109 /* Returns:     int - 0 = success, else failure                             */
4110 /* Parameters:  src(I)  - pointer to the source address                     */
4111 /*              dst(I)  - destination address                               */
4112 /*              size(I) - number of bytes to copy                           */
4113 /*                                                                          */
4114 /* Copy a block of data in from user space, given a pointer to the pointer  */
4115 /* to start copying from (src) and a pointer to where to store it (dst).    */
4116 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4117 /* ------------------------------------------------------------------------ */
4118 int
copyinptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4119 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4120 {
4121 	void *ca;
4122 	int error;
4123 
4124 # if SOLARIS
4125 	error = COPYIN(src, &ca, sizeof(ca));
4126 	if (error != 0)
4127 		return error;
4128 # else
4129 	bcopy(src, (void *)&ca, sizeof(ca));
4130 # endif
4131 	error = COPYIN(ca, dst, size);
4132 	if (error != 0) {
4133 		IPFERROR(3);
4134 		error = EFAULT;
4135 	}
4136 	return error;
4137 }
4138 
4139 
4140 /* ------------------------------------------------------------------------ */
4141 /* Function:    copyoutptr                                                  */
4142 /* Returns:     int - 0 = success, else failure                             */
4143 /* Parameters:  src(I)  - pointer to the source address                     */
4144 /*              dst(I)  - destination address                               */
4145 /*              size(I) - number of bytes to copy                           */
4146 /*                                                                          */
4147 /* Copy a block of data out to user space, given a pointer to the pointer   */
4148 /* to start copying from (src) and a pointer to where to store it (dst).    */
4149 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4150 /* ------------------------------------------------------------------------ */
4151 int
copyoutptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4152 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4153 {
4154 	void *ca;
4155 	int error;
4156 
4157 	bcopy(dst, &ca, sizeof(ca));
4158 	error = COPYOUT(src, ca, size);
4159 	if (error != 0) {
4160 		IPFERROR(4);
4161 		error = EFAULT;
4162 	}
4163 	return error;
4164 }
4165 #ifdef	_KERNEL
4166 #endif
4167 
4168 
4169 /* ------------------------------------------------------------------------ */
4170 /* Function:    ipf_lock                                                    */
4171 /* Returns:     int      - 0 = success, else error                          */
4172 /* Parameters:  data(I)  - pointer to lock value to set                     */
4173 /*              lockp(O) - pointer to location to store old lock value      */
4174 /*                                                                          */
4175 /* Get the new value for the lock integer, set it and return the old value  */
4176 /* in *lockp.                                                               */
4177 /* ------------------------------------------------------------------------ */
4178 int
ipf_lock(void * data,int * lockp)4179 ipf_lock(void *data, int *lockp)
4180 {
4181 	int arg, err;
4182 
4183 	err = BCOPYIN(data, &arg, sizeof(arg));
4184 	if (err != 0)
4185 		return EFAULT;
4186 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4187 	if (err != 0)
4188 		return EFAULT;
4189 	*lockp = arg;
4190 	return 0;
4191 }
4192 
4193 
4194 /* ------------------------------------------------------------------------ */
4195 /* Function:    ipf_getstat                                                 */
4196 /* Returns:     Nil                                                         */
4197 /* Parameters:  softc(I) - pointer to soft context main structure           */
4198 /*              fiop(I)  - pointer to ipfilter stats structure              */
4199 /*              rev(I)   - version claim by program doing ioctl             */
4200 /*                                                                          */
4201 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4202 /* structure.                                                               */
4203 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4204 /* program is looking for. This ensure that validation of the version it    */
4205 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4206 /* allow older binaries to work but kernels without it will not.            */
4207 /* ------------------------------------------------------------------------ */
4208 /*ARGSUSED*/
4209 static void
ipf_getstat(ipf_main_softc_t * softc,friostat_t * fiop,int rev)4210 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4211 {
4212 	int i;
4213 
4214 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4215 	      sizeof(ipf_statistics_t) * 2);
4216 	fiop->f_locks[IPL_LOGSTATE] = -1;
4217 	fiop->f_locks[IPL_LOGNAT] = -1;
4218 	fiop->f_locks[IPL_LOGIPF] = -1;
4219 	fiop->f_locks[IPL_LOGAUTH] = -1;
4220 
4221 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4222 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4223 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4224 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4225 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4226 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4227 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4228 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4229 
4230 	fiop->f_ticks = softc->ipf_ticks;
4231 	fiop->f_active = softc->ipf_active;
4232 	fiop->f_froute[0] = softc->ipf_frouteok[0];
4233 	fiop->f_froute[1] = softc->ipf_frouteok[1];
4234 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4235 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4236 
4237 	fiop->f_running = softc->ipf_running;
4238 	for (i = 0; i < IPL_LOGSIZE; i++) {
4239 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4240 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4241 	}
4242 #ifdef  IPFILTER_LOG
4243 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4244 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4245 	fiop->f_logging = 1;
4246 #else
4247 	fiop->f_log_ok = 0;
4248 	fiop->f_log_fail = 0;
4249 	fiop->f_logging = 0;
4250 #endif
4251 	fiop->f_defpass = softc->ipf_pass;
4252 	fiop->f_features = ipf_features;
4253 
4254 #ifdef IPFILTER_COMPAT
4255 	snprintf(fiop->f_version, sizeof(fiop->f_version),
4256 		 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
4257 		 (rev / 10000) % 100, (rev / 100) % 100);
4258 #else
4259 	rev = rev;
4260 	(void) strncpy(fiop->f_version, ipfilter_version,
4261 		       sizeof(fiop->f_version));
4262         fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
4263 #endif
4264 }
4265 
4266 
4267 #ifdef	USE_INET6
4268 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4269 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4270 	-1,			/* 1: UNUSED */
4271 	-1,			/* 2: UNUSED */
4272 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4273 	-1,			/* 4: ICMP_SOURCEQUENCH */
4274 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4275 	-1,			/* 6: UNUSED */
4276 	-1,			/* 7: UNUSED */
4277 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4278 	-1,			/* 9: UNUSED */
4279 	-1,			/* 10: UNUSED */
4280 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4281 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4282 	-1,			/* 13: ICMP_TSTAMP */
4283 	-1,			/* 14: ICMP_TSTAMPREPLY */
4284 	-1,			/* 15: ICMP_IREQ */
4285 	-1,			/* 16: ICMP_IREQREPLY */
4286 	-1,			/* 17: ICMP_MASKREQ */
4287 	-1,			/* 18: ICMP_MASKREPLY */
4288 };
4289 
4290 
4291 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4292 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4293 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4294 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4295 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4296 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4297 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4298 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4299 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4300 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4301 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4302 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4303 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4304 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4305 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4306 };
4307 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4308 #endif
4309 
4310 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4311 
4312 
4313 /* ------------------------------------------------------------------------ */
4314 /* Function:    ipf_matchicmpqueryreply                                     */
4315 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4316 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4317 /*              ic(I)   - ICMP information                                  */
4318 /*              icmp(I) - ICMP packet header                                */
4319 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4320 /*                                                                          */
4321 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4322 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4323 /* else return 0 for no match.                                              */
4324 /* ------------------------------------------------------------------------ */
4325 int
ipf_matchicmpqueryreply(int v,icmpinfo_t * ic,icmphdr_t * icmp,int rev)4326 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4327 {
4328 	int ictype;
4329 
4330 	ictype = ic->ici_type;
4331 
4332 	if (v == 4) {
4333 		/*
4334 		 * If we matched its type on the way in, then when going out
4335 		 * it will still be the same type.
4336 		 */
4337 		if ((!rev && (icmp->icmp_type == ictype)) ||
4338 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4339 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4340 				return 1;
4341 			if (icmp->icmp_id == ic->ici_id)
4342 				return 1;
4343 		}
4344 	}
4345 #ifdef	USE_INET6
4346 	else if (v == 6) {
4347 		if ((!rev && (icmp->icmp_type == ictype)) ||
4348 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4349 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4350 				return 1;
4351 			if (icmp->icmp_id == ic->ici_id)
4352 				return 1;
4353 		}
4354 	}
4355 #endif
4356 	return 0;
4357 }
4358 
4359 /* ------------------------------------------------------------------------ */
4360 /* Function:    ipf_rule_compare                                            */
4361 /* Parameters:  fr1(I) - first rule structure to compare                    */
4362 /*              fr2(I) - second rule structure to compare                   */
4363 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4364 /*                                                                          */
4365 /* Compare two rules and return 0 if they match or a number indicating      */
4366 /* which of the individual checks failed.                                   */
4367 /* ------------------------------------------------------------------------ */
4368 static int
ipf_rule_compare(frentry_t * fr1,frentry_t * fr2)4369 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4370 {
4371 	if (fr1->fr_cksum != fr2->fr_cksum)
4372 		return 1;
4373 	if (fr1->fr_size != fr2->fr_size)
4374 		return 2;
4375 	if (fr1->fr_dsize != fr2->fr_dsize)
4376 		return 3;
4377 	if (memcmp(&fr1->fr_func, &fr2->fr_func,
4378 		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4379 		return 4;
4380 	if (fr1->fr_data && !fr2->fr_data)
4381 		return 5;
4382 	if (!fr1->fr_data && fr2->fr_data)
4383 		return 6;
4384 	if (fr1->fr_data) {
4385 		if (memcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4386 			return 7;
4387 	}
4388 	return 0;
4389 }
4390 
4391 
4392 /* ------------------------------------------------------------------------ */
4393 /* Function:    frrequest                                                   */
4394 /* Returns:     int - 0 == success, > 0 == errno value                      */
4395 /* Parameters:  unit(I)     - device for which this is for                  */
4396 /*              req(I)      - ioctl command (SIOC*)                         */
4397 /*              data(I)     - pointr to ioctl data                          */
4398 /*              set(I)      - 1 or 0 (filter set)                           */
4399 /*              makecopy(I) - flag indicating whether data points to a rule */
4400 /*                            in kernel space & hence doesn't need copying. */
4401 /*                                                                          */
4402 /* This function handles all the requests which operate on the list of      */
4403 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4404 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4405 /* names are resolved here and other sanity checks are made on the content  */
4406 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4407 /* then make sure they are created and initialised before exiting.          */
4408 /* ------------------------------------------------------------------------ */
4409 int
frrequest(ipf_main_softc_t * softc,int unit,ioctlcmd_t req,void * data,int set,int makecopy)4410 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
4411     int set, int makecopy)
4412 {
4413 	int error = 0, in, family, addrem, need_free = 0;
4414 	frentry_t frd, *fp, *f, **fprev, **ftail;
4415 	void *ptr, *uptr;
4416 	u_int *p, *pp;
4417 	frgroup_t *fg;
4418 	char *group;
4419 
4420 	ptr = NULL;
4421 	fg = NULL;
4422 	fp = &frd;
4423 	if (makecopy != 0) {
4424 		bzero(fp, sizeof(frd));
4425 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4426 		if (error) {
4427 			return error;
4428 		}
4429 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4430 			IPFERROR(6);
4431 			return EINVAL;
4432 		}
4433 		KMALLOCS(f, frentry_t *, fp->fr_size);
4434 		if (f == NULL) {
4435 			IPFERROR(131);
4436 			return ENOMEM;
4437 		}
4438 		bzero(f, fp->fr_size);
4439 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4440 				    fp->fr_size);
4441 		if (error) {
4442 			KFREES(f, fp->fr_size);
4443 			return error;
4444 		}
4445 
4446 		fp = f;
4447 		f = NULL;
4448 		fp->fr_next = NULL;
4449 		fp->fr_dnext = NULL;
4450 		fp->fr_pnext = NULL;
4451 		fp->fr_pdnext = NULL;
4452 		fp->fr_grp = NULL;
4453 		fp->fr_grphead = NULL;
4454 		fp->fr_icmpgrp = NULL;
4455 		fp->fr_isc = (void *)-1;
4456 		fp->fr_ptr = NULL;
4457 		fp->fr_ref = 0;
4458 		fp->fr_flags |= FR_COPIED;
4459 	} else {
4460 		fp = (frentry_t *)data;
4461 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4462 			IPFERROR(7);
4463 			return EINVAL;
4464 		}
4465 		fp->fr_flags &= ~FR_COPIED;
4466 	}
4467 
4468 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4469 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4470 		IPFERROR(8);
4471 		error = EINVAL;
4472 		goto donenolock;
4473 	}
4474 
4475 	family = fp->fr_family;
4476 	uptr = fp->fr_data;
4477 
4478 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4479 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4480 		addrem = 0;
4481 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4482 		addrem = 1;
4483 	else if (req == (ioctlcmd_t)SIOCZRLST)
4484 		addrem = 2;
4485 	else {
4486 		IPFERROR(9);
4487 		error = EINVAL;
4488 		goto donenolock;
4489 	}
4490 
4491 	/*
4492 	 * Only filter rules for IPv4 or IPv6 are accepted.
4493 	 */
4494 	if (family == AF_INET) {
4495 		/*EMPTY*/;
4496 #ifdef	USE_INET6
4497 	} else if (family == AF_INET6) {
4498 		/*EMPTY*/;
4499 #endif
4500 	} else if (family != 0) {
4501 		IPFERROR(10);
4502 		error = EINVAL;
4503 		goto donenolock;
4504 	}
4505 
4506 	/*
4507 	 * If the rule is being loaded from user space, i.e. we had to copy it
4508 	 * into kernel space, then do not trust the function pointer in the
4509 	 * rule.
4510 	 */
4511 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4512 		if (ipf_findfunc(fp->fr_func) == NULL) {
4513 			IPFERROR(11);
4514 			error = ESRCH;
4515 			goto donenolock;
4516 		}
4517 
4518 		if (addrem == 0) {
4519 			error = ipf_funcinit(softc, fp);
4520 			if (error != 0)
4521 				goto donenolock;
4522 		}
4523 	}
4524 	if ((fp->fr_flags & FR_CALLNOW) &&
4525 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4526 		IPFERROR(142);
4527 		error = ESRCH;
4528 		goto donenolock;
4529 	}
4530 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4531 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4532 		IPFERROR(143);
4533 		error = ESRCH;
4534 		goto donenolock;
4535 	}
4536 
4537 	ptr = NULL;
4538 
4539 	if (FR_ISACCOUNT(fp->fr_flags))
4540 		unit = IPL_LOGCOUNT;
4541 
4542 	/*
4543 	 * Check that each group name in the rule has a start index that
4544 	 * is valid.
4545 	 */
4546 	if (fp->fr_icmphead != -1) {
4547 		if ((fp->fr_icmphead < 0) ||
4548 		    (fp->fr_icmphead >= fp->fr_namelen)) {
4549 			IPFERROR(136);
4550 			error = EINVAL;
4551 			goto donenolock;
4552 		}
4553 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4554 			fp->fr_names[fp->fr_icmphead] = '\0';
4555 	}
4556 
4557 	if (fp->fr_grhead != -1) {
4558 		if ((fp->fr_grhead < 0) ||
4559 		    (fp->fr_grhead >= fp->fr_namelen)) {
4560 			IPFERROR(137);
4561 			error = EINVAL;
4562 			goto donenolock;
4563 		}
4564 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4565 			fp->fr_names[fp->fr_grhead] = '\0';
4566 	}
4567 
4568 	if (fp->fr_group != -1) {
4569 		if ((fp->fr_group < 0) ||
4570 		    (fp->fr_group >= fp->fr_namelen)) {
4571 			IPFERROR(138);
4572 			error = EINVAL;
4573 			goto donenolock;
4574 		}
4575 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4576 			/*
4577 			 * Allow loading rules that are in groups to cause
4578 			 * them to be created if they don't already exit.
4579 			 */
4580 			group = FR_NAME(fp, fr_group);
4581 			if (addrem == 0) {
4582 				fg = ipf_group_add(softc, group, NULL,
4583 						   fp->fr_flags, unit, set);
4584 				if (fg == NULL) {
4585 					IPFERROR(152);
4586 					error = ESRCH;
4587 					goto donenolock;
4588 				}
4589 				fp->fr_grp = fg;
4590 			} else {
4591 				fg = ipf_findgroup(softc, group, unit,
4592 						   set, NULL);
4593 				if (fg == NULL) {
4594 					IPFERROR(12);
4595 					error = ESRCH;
4596 					goto donenolock;
4597 				}
4598 			}
4599 
4600 			if (fg->fg_flags == 0) {
4601 				fg->fg_flags = fp->fr_flags & FR_INOUT;
4602 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4603 				IPFERROR(13);
4604 				error = ESRCH;
4605 				goto donenolock;
4606 			}
4607 		}
4608 	} else {
4609 		/*
4610 		 * If a rule is going to be part of a group then it does
4611 		 * not matter whether it is an in or out rule, but if it
4612 		 * isn't in a group, then it does...
4613 		 */
4614 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4615 			IPFERROR(14);
4616 			error = EINVAL;
4617 			goto donenolock;
4618 		}
4619 	}
4620 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4621 
4622 	/*
4623 	 * Work out which rule list this change is being applied to.
4624 	 */
4625 	ftail = NULL;
4626 	fprev = NULL;
4627 	if (unit == IPL_LOGAUTH) {
4628 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4629 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4630 		    (fp->fr_dif.fd_ptr != NULL) ||
4631 		    (fp->fr_flags & FR_FASTROUTE)) {
4632 			IPFERROR(145);
4633 			error = EINVAL;
4634 			goto donenolock;
4635 		}
4636 		fprev = ipf_auth_rulehead(softc);
4637 	} else {
4638 		if (FR_ISACCOUNT(fp->fr_flags))
4639 			fprev = &softc->ipf_acct[in][set];
4640 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4641 			fprev = &softc->ipf_rules[in][set];
4642 	}
4643 	if (fprev == NULL) {
4644 		IPFERROR(15);
4645 		error = ESRCH;
4646 		goto donenolock;
4647 	}
4648 
4649 	if (fg != NULL)
4650 		fprev = &fg->fg_start;
4651 
4652 	/*
4653 	 * Copy in extra data for the rule.
4654 	 */
4655 	if (fp->fr_dsize != 0) {
4656 		if (makecopy != 0) {
4657 			KMALLOCS(ptr, void *, fp->fr_dsize);
4658 			if (ptr == NULL) {
4659 				IPFERROR(16);
4660 				error = ENOMEM;
4661 				goto donenolock;
4662 			}
4663 
4664 			/*
4665 			 * The bcopy case is for when the data is appended
4666 			 * to the rule by ipf_in_compat().
4667 			 */
4668 			if (uptr >= (void *)fp &&
4669 			    uptr < (void *)((char *)fp + fp->fr_size)) {
4670 				bcopy(uptr, ptr, fp->fr_dsize);
4671 				error = 0;
4672 			} else {
4673 				error = COPYIN(uptr, ptr, fp->fr_dsize);
4674 				if (error != 0) {
4675 					IPFERROR(17);
4676 					error = EFAULT;
4677 					goto donenolock;
4678 				}
4679 			}
4680 		} else {
4681 			ptr = uptr;
4682 		}
4683 		fp->fr_data = ptr;
4684 	} else {
4685 		fp->fr_data = NULL;
4686 	}
4687 
4688 	/*
4689 	 * Perform per-rule type sanity checks of their members.
4690 	 * All code after this needs to be aware that allocated memory
4691 	 * may need to be free'd before exiting.
4692 	 */
4693 	switch (fp->fr_type & ~FR_T_BUILTIN)
4694 	{
4695 #if defined(IPFILTER_BPF)
4696 	case FR_T_BPFOPC :
4697 		if (fp->fr_dsize == 0) {
4698 			IPFERROR(19);
4699 			error = EINVAL;
4700 			break;
4701 		}
4702 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4703 			IPFERROR(20);
4704 			error = EINVAL;
4705 			break;
4706 		}
4707 		break;
4708 #endif
4709 	case FR_T_IPF :
4710 		/*
4711 		 * Preparation for error case at the bottom of this function.
4712 		 */
4713 		if (fp->fr_datype == FRI_LOOKUP)
4714 			fp->fr_dstptr = NULL;
4715 		if (fp->fr_satype == FRI_LOOKUP)
4716 			fp->fr_srcptr = NULL;
4717 
4718 		if (fp->fr_dsize != sizeof(fripf_t)) {
4719 			IPFERROR(21);
4720 			error = EINVAL;
4721 			break;
4722 		}
4723 
4724 		/*
4725 		 * Allowing a rule with both "keep state" and "with oow" is
4726 		 * pointless because adding a state entry to the table will
4727 		 * fail with the out of window (oow) flag set.
4728 		 */
4729 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4730 			IPFERROR(22);
4731 			error = EINVAL;
4732 			break;
4733 		}
4734 
4735 		switch (fp->fr_satype)
4736 		{
4737 		case FRI_BROADCAST :
4738 		case FRI_DYNAMIC :
4739 		case FRI_NETWORK :
4740 		case FRI_NETMASKED :
4741 		case FRI_PEERADDR :
4742 			if (fp->fr_sifpidx < 0) {
4743 				IPFERROR(23);
4744 				error = EINVAL;
4745 			}
4746 			break;
4747 		case FRI_LOOKUP :
4748 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4749 						       &fp->fr_src6,
4750 						       &fp->fr_smsk6);
4751 			if (fp->fr_srcfunc == NULL) {
4752 				IPFERROR(132);
4753 				error = ESRCH;
4754 				break;
4755 			}
4756 			break;
4757 		case FRI_NORMAL :
4758 			break;
4759 		default :
4760 			IPFERROR(133);
4761 			error = EINVAL;
4762 			break;
4763 		}
4764 		if (error != 0)
4765 			break;
4766 
4767 		switch (fp->fr_datype)
4768 		{
4769 		case FRI_BROADCAST :
4770 		case FRI_DYNAMIC :
4771 		case FRI_NETWORK :
4772 		case FRI_NETMASKED :
4773 		case FRI_PEERADDR :
4774 			if (fp->fr_difpidx < 0) {
4775 				IPFERROR(24);
4776 				error = EINVAL;
4777 			}
4778 			break;
4779 		case FRI_LOOKUP :
4780 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4781 						       &fp->fr_dst6,
4782 						       &fp->fr_dmsk6);
4783 			if (fp->fr_dstfunc == NULL) {
4784 				IPFERROR(134);
4785 				error = ESRCH;
4786 			}
4787 			break;
4788 		case FRI_NORMAL :
4789 			break;
4790 		default :
4791 			IPFERROR(135);
4792 			error = EINVAL;
4793 		}
4794 		break;
4795 
4796 	case FR_T_NONE :
4797 	case FR_T_CALLFUNC :
4798 	case FR_T_COMPIPF :
4799 		break;
4800 
4801 	case FR_T_IPFEXPR :
4802 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4803 			IPFERROR(25);
4804 			error = EINVAL;
4805 		}
4806 		break;
4807 
4808 	default :
4809 		IPFERROR(26);
4810 		error = EINVAL;
4811 		break;
4812 	}
4813 	if (error != 0)
4814 		goto donenolock;
4815 
4816 	if (fp->fr_tif.fd_name != -1) {
4817 		if ((fp->fr_tif.fd_name < 0) ||
4818 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4819 			IPFERROR(139);
4820 			error = EINVAL;
4821 			goto donenolock;
4822 		}
4823 	}
4824 
4825 	if (fp->fr_dif.fd_name != -1) {
4826 		if ((fp->fr_dif.fd_name < 0) ||
4827 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4828 			IPFERROR(140);
4829 			error = EINVAL;
4830 			goto donenolock;
4831 		}
4832 	}
4833 
4834 	if (fp->fr_rif.fd_name != -1) {
4835 		if ((fp->fr_rif.fd_name < 0) ||
4836 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4837 			IPFERROR(141);
4838 			error = EINVAL;
4839 			goto donenolock;
4840 		}
4841 	}
4842 
4843 	/*
4844 	 * Lookup all the interface names that are part of the rule.
4845 	 */
4846 	error = ipf_synclist(softc, fp, NULL);
4847 	if (error != 0)
4848 		goto donenolock;
4849 	fp->fr_statecnt = 0;
4850 	if (fp->fr_srctrack.ht_max_nodes != 0)
4851 		ipf_rb_ht_init(&fp->fr_srctrack);
4852 
4853 	/*
4854 	 * Look for an existing matching filter rule, but don't include the
4855 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4856 	 * This elminates rules which are indentical being loaded.  Checksum
4857 	 * the constant part of the filter rule to make comparisons quicker
4858 	 * (this meaning no pointers are included).
4859 	 */
4860 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4861 	     p < pp; p++)
4862 		fp->fr_cksum += *p;
4863 	pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
4864 	for (p = (u_int *)fp->fr_data; p < pp; p++)
4865 		fp->fr_cksum += *p;
4866 
4867 	WRITE_ENTER(&softc->ipf_mutex);
4868 
4869 	/*
4870 	 * Now that the filter rule lists are locked, we can walk the
4871 	 * chain of them without fear.
4872 	 */
4873 	ftail = fprev;
4874 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4875 		if (fp->fr_collect <= f->fr_collect) {
4876 			ftail = fprev;
4877 			f = NULL;
4878 			break;
4879 		}
4880 		fprev = ftail;
4881 	}
4882 
4883 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4884 		DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
4885 		if (ipf_rule_compare(fp, f) == 0)
4886 			break;
4887 	}
4888 
4889 	/*
4890 	 * If zero'ing statistics, copy current to caller and zero.
4891 	 */
4892 	if (addrem == 2) {
4893 		if (f == NULL) {
4894 			IPFERROR(27);
4895 			error = ESRCH;
4896 		} else {
4897 			/*
4898 			 * Copy and reduce lock because of impending copyout.
4899 			 * Well we should, but if we do then the atomicity of
4900 			 * this call and the correctness of fr_hits and
4901 			 * fr_bytes cannot be guaranteed.  As it is, this code
4902 			 * only resets them to 0 if they are successfully
4903 			 * copied out into user space.
4904 			 */
4905 			bcopy((char *)f, (char *)fp, f->fr_size);
4906 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4907 
4908 			/*
4909 			 * When we copy this rule back out, set the data
4910 			 * pointer to be what it was in user space.
4911 			 */
4912 			fp->fr_data = uptr;
4913 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4914 
4915 			if (error == 0) {
4916 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4917 					error = COPYOUT(f->fr_data, uptr,
4918 							f->fr_dsize);
4919 					if (error != 0) {
4920 						IPFERROR(28);
4921 						error = EFAULT;
4922 					}
4923 				}
4924 				if (error == 0) {
4925 					f->fr_hits = 0;
4926 					f->fr_bytes = 0;
4927 				}
4928 			}
4929 		}
4930 
4931 		if (makecopy != 0) {
4932 			if (ptr != NULL) {
4933 				KFREES(ptr, fp->fr_dsize);
4934 			}
4935 			KFREES(fp, fp->fr_size);
4936 		}
4937 		RWLOCK_EXIT(&softc->ipf_mutex);
4938 		return error;
4939 	}
4940 
4941   	if (!f) {
4942 		/*
4943 		 * At the end of this, ftail must point to the place where the
4944 		 * new rule is to be saved/inserted/added.
4945 		 * For SIOCAD*FR, this should be the last rule in the group of
4946 		 * rules that have equal fr_collect fields.
4947 		 * For SIOCIN*FR, ...
4948 		 */
4949 		if (req == (ioctlcmd_t)SIOCADAFR ||
4950 		    req == (ioctlcmd_t)SIOCADIFR) {
4951 
4952 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4953 				if (f->fr_collect > fp->fr_collect)
4954 					break;
4955 				ftail = &f->fr_next;
4956 				fprev = ftail;
4957 			}
4958 			ftail = fprev;
4959 			f = NULL;
4960 			ptr = NULL;
4961 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4962 			   req == (ioctlcmd_t)SIOCINIFR) {
4963 			while ((f = *fprev) != NULL) {
4964 				if (f->fr_collect >= fp->fr_collect)
4965 					break;
4966 				fprev = &f->fr_next;
4967 			}
4968   			ftail = fprev;
4969   			if (fp->fr_hits != 0) {
4970 				while (fp->fr_hits && (f = *ftail)) {
4971 					if (f->fr_collect != fp->fr_collect)
4972 						break;
4973 					fprev = ftail;
4974   					ftail = &f->fr_next;
4975 					fp->fr_hits--;
4976 				}
4977   			}
4978   			f = NULL;
4979   			ptr = NULL;
4980 		}
4981 	}
4982 
4983 	/*
4984 	 * Request to remove a rule.
4985 	 */
4986 	if (addrem == 1) {
4987 		if (!f) {
4988 			IPFERROR(29);
4989 			error = ESRCH;
4990 		} else {
4991 			/*
4992 			 * Do not allow activity from user space to interfere
4993 			 * with rules not loaded that way.
4994 			 */
4995 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4996 				IPFERROR(30);
4997 				error = EPERM;
4998 				goto done;
4999 			}
5000 
5001 			/*
5002 			 * Return EBUSY if the rule is being reference by
5003 			 * something else (eg state information.)
5004 			 */
5005 			if (f->fr_ref > 1) {
5006 				IPFERROR(31);
5007 				error = EBUSY;
5008 				goto done;
5009 			}
5010 #ifdef	IPFILTER_SCAN
5011 			if (f->fr_isctag != -1 &&
5012 			    (f->fr_isc != (struct ipscan *)-1))
5013 				ipf_scan_detachfr(f);
5014 #endif
5015 
5016 			if (unit == IPL_LOGAUTH) {
5017 				error = ipf_auth_precmd(softc, req, f, ftail);
5018 				goto done;
5019 			}
5020 
5021 			ipf_rule_delete(softc, f, unit, set);
5022 
5023 			need_free = makecopy;
5024 		}
5025 	} else {
5026 		/*
5027 		 * Not removing, so we must be adding/inserting a rule.
5028 		 */
5029 		if (f != NULL) {
5030 			IPFERROR(32);
5031 			error = EEXIST;
5032 			goto done;
5033 		}
5034 		if (unit == IPL_LOGAUTH) {
5035 			error = ipf_auth_precmd(softc, req, fp, ftail);
5036 			goto done;
5037 		}
5038 
5039 		MUTEX_NUKE(&fp->fr_lock);
5040 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5041 		if (fp->fr_die != 0)
5042 			ipf_rule_expire_insert(softc, fp, set);
5043 
5044 		fp->fr_hits = 0;
5045 		if (makecopy != 0)
5046 			fp->fr_ref = 1;
5047 		fp->fr_pnext = ftail;
5048 		fp->fr_next = *ftail;
5049 		if (fp->fr_next != NULL)
5050 			fp->fr_next->fr_pnext = &fp->fr_next;
5051 		*ftail = fp;
5052 		if (addrem == 0)
5053 			ipf_fixskip(ftail, fp, 1);
5054 
5055 		fp->fr_icmpgrp = NULL;
5056 		if (fp->fr_icmphead != -1) {
5057 			group = FR_NAME(fp, fr_icmphead);
5058 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5059 			fp->fr_icmpgrp = fg;
5060 		}
5061 
5062 		fp->fr_grphead = NULL;
5063 		if (fp->fr_grhead != -1) {
5064 			group = FR_NAME(fp, fr_grhead);
5065 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5066 					   unit, set);
5067 			fp->fr_grphead = fg;
5068 		}
5069 	}
5070 done:
5071 	RWLOCK_EXIT(&softc->ipf_mutex);
5072 donenolock:
5073 	if (need_free || (error != 0)) {
5074 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5075 			if ((fp->fr_satype == FRI_LOOKUP) &&
5076 			    (fp->fr_srcptr != NULL))
5077 				ipf_lookup_deref(softc, fp->fr_srctype,
5078 						 fp->fr_srcptr);
5079 			if ((fp->fr_datype == FRI_LOOKUP) &&
5080 			    (fp->fr_dstptr != NULL))
5081 				ipf_lookup_deref(softc, fp->fr_dsttype,
5082 						 fp->fr_dstptr);
5083 		}
5084 		if (fp->fr_grp != NULL) {
5085 			WRITE_ENTER(&softc->ipf_mutex);
5086 			ipf_group_del(softc, fp->fr_grp, fp);
5087 			RWLOCK_EXIT(&softc->ipf_mutex);
5088 		}
5089 		if ((ptr != NULL) && (makecopy != 0)) {
5090 			KFREES(ptr, fp->fr_dsize);
5091 		}
5092 		KFREES(fp, fp->fr_size);
5093 	}
5094 	return (error);
5095 }
5096 
5097 
5098 /* ------------------------------------------------------------------------ */
5099 /* Function:   ipf_rule_delete                                              */
5100 /* Returns:    Nil                                                          */
5101 /* Parameters: softc(I) - pointer to soft context main structure            */
5102 /*             f(I)     - pointer to the rule being deleted                 */
5103 /*             ftail(I) - pointer to the pointer to f                       */
5104 /*             unit(I)  - device for which this is for                      */
5105 /*             set(I)   - 1 or 0 (filter set)                               */
5106 /*                                                                          */
5107 /* This function attempts to do what it can to delete a filter rule: remove */
5108 /* it from any linked lists and remove any groups it is responsible for.    */
5109 /* But in the end, removing a rule can only drop the reference count - we   */
5110 /* must use that as the guide for whether or not it can be freed.           */
5111 /* ------------------------------------------------------------------------ */
5112 static void
ipf_rule_delete(ipf_main_softc_t * softc,frentry_t * f,int unit,int set)5113 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5114 {
5115 
5116 	/*
5117 	 * If fr_pdnext is set, then the rule is on the expire list, so
5118 	 * remove it from there.
5119 	 */
5120 	if (f->fr_pdnext != NULL) {
5121 		*f->fr_pdnext = f->fr_dnext;
5122 		if (f->fr_dnext != NULL)
5123 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5124 		f->fr_pdnext = NULL;
5125 		f->fr_dnext = NULL;
5126 	}
5127 
5128 	ipf_fixskip(f->fr_pnext, f, -1);
5129 	if (f->fr_pnext != NULL)
5130 		*f->fr_pnext = f->fr_next;
5131 	if (f->fr_next != NULL)
5132 		f->fr_next->fr_pnext = f->fr_pnext;
5133 	f->fr_pnext = NULL;
5134 	f->fr_next = NULL;
5135 
5136 	(void) ipf_derefrule(softc, &f);
5137 }
5138 
5139 /* ------------------------------------------------------------------------ */
5140 /* Function:   ipf_rule_expire_insert                                       */
5141 /* Returns:    Nil                                                          */
5142 /* Parameters: softc(I) - pointer to soft context main structure            */
5143 /*             f(I)     - pointer to rule to be added to expire list        */
5144 /*             set(I)   - 1 or 0 (filter set)                               */
5145 /*                                                                          */
5146 /* If the new rule has a given expiration time, insert it into the list of  */
5147 /* expiring rules with the ones to be removed first added to the front of   */
5148 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5149 /* expiration interval checks.                                              */
5150 /* ------------------------------------------------------------------------ */
5151 static void
ipf_rule_expire_insert(ipf_main_softc_t * softc,frentry_t * f,int set)5152 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5153 {
5154 	frentry_t *fr;
5155 
5156 	/*
5157 	 */
5158 
5159 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5160 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5161 	     fr = fr->fr_dnext) {
5162 		if (f->fr_die < fr->fr_die)
5163 			break;
5164 		if (fr->fr_dnext == NULL) {
5165 			/*
5166 			 * We've got to the last rule and everything
5167 			 * wanted to be expired before this new node,
5168 			 * so we have to tack it on the end...
5169 			 */
5170 			fr->fr_dnext = f;
5171 			f->fr_pdnext = &fr->fr_dnext;
5172 			fr = NULL;
5173 			break;
5174 		}
5175 	}
5176 
5177 	if (softc->ipf_rule_explist[set] == NULL) {
5178 		softc->ipf_rule_explist[set] = f;
5179 		f->fr_pdnext = &softc->ipf_rule_explist[set];
5180 	} else if (fr != NULL) {
5181 		f->fr_dnext = fr;
5182 		f->fr_pdnext = fr->fr_pdnext;
5183 		fr->fr_pdnext = &f->fr_dnext;
5184 	}
5185 }
5186 
5187 
5188 /* ------------------------------------------------------------------------ */
5189 /* Function:   ipf_findlookup                                               */
5190 /* Returns:    NULL = failure, else success                                 */
5191 /* Parameters: softc(I) - pointer to soft context main structure            */
5192 /*             unit(I)  - ipf device we want to find match for              */
5193 /*             fp(I)    - rule for which lookup is for                      */
5194 /*             addrp(I) - pointer to lookup information in address struct   */
5195 /*             maskp(O) - pointer to lookup information for storage         */
5196 /*                                                                          */
5197 /* When using pools and hash tables to store addresses for matching in      */
5198 /* rules, it is necessary to resolve both the object referred to by the     */
5199 /* name or address (and return that pointer) and also provide the means by  */
5200 /* which to determine if an address belongs to that object to make the      */
5201 /* packet matching quicker.                                                 */
5202 /* ------------------------------------------------------------------------ */
5203 static void *
ipf_findlookup(ipf_main_softc_t * softc,int unit,frentry_t * fr,i6addr_t * addrp,i6addr_t * maskp)5204 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5205     i6addr_t *addrp, i6addr_t *maskp)
5206 {
5207 	void *ptr = NULL;
5208 
5209 	switch (addrp->iplookupsubtype)
5210 	{
5211 	case 0 :
5212 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5213 					 addrp->iplookupnum,
5214 					 &maskp->iplookupfunc);
5215 		break;
5216 	case 1 :
5217 		if (addrp->iplookupname < 0)
5218 			break;
5219 		if (addrp->iplookupname >= fr->fr_namelen)
5220 			break;
5221 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5222 					  fr->fr_names + addrp->iplookupname,
5223 					  &maskp->iplookupfunc);
5224 		break;
5225 	default :
5226 		break;
5227 	}
5228 
5229 	return ptr;
5230 }
5231 
5232 
5233 /* ------------------------------------------------------------------------ */
5234 /* Function:    ipf_funcinit                                                */
5235 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5236 /* Parameters:  softc(I) - pointer to soft context main structure           */
5237 /*              fr(I)    - pointer to filter rule                           */
5238 /*                                                                          */
5239 /* If a rule is a call rule, then check if the function it points to needs  */
5240 /* an init function to be called now the rule has been loaded.              */
5241 /* ------------------------------------------------------------------------ */
5242 static int
ipf_funcinit(ipf_main_softc_t * softc,frentry_t * fr)5243 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5244 {
5245 	ipfunc_resolve_t *ft;
5246 	int err;
5247 
5248 	IPFERROR(34);
5249 	err = ESRCH;
5250 
5251 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5252 		if (ft->ipfu_addr == fr->fr_func) {
5253 			err = 0;
5254 			if (ft->ipfu_init != NULL)
5255 				err = (*ft->ipfu_init)(softc, fr);
5256 			break;
5257 		}
5258 	return err;
5259 }
5260 
5261 
5262 /* ------------------------------------------------------------------------ */
5263 /* Function:    ipf_funcfini                                                */
5264 /* Returns:     Nil                                                         */
5265 /* Parameters:  softc(I) - pointer to soft context main structure           */
5266 /*              fr(I)    - pointer to filter rule                           */
5267 /*                                                                          */
5268 /* For a given filter rule, call the matching "fini" function if the rule   */
5269 /* is using a known function that would have resulted in the "init" being   */
5270 /* called for ealier.                                                       */
5271 /* ------------------------------------------------------------------------ */
5272 static void
ipf_funcfini(ipf_main_softc_t * softc,frentry_t * fr)5273 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5274 {
5275 	ipfunc_resolve_t *ft;
5276 
5277 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5278 		if (ft->ipfu_addr == fr->fr_func) {
5279 			if (ft->ipfu_fini != NULL)
5280 				(void) (*ft->ipfu_fini)(softc, fr);
5281 			break;
5282 		}
5283 }
5284 
5285 
5286 /* ------------------------------------------------------------------------ */
5287 /* Function:    ipf_findfunc                                                */
5288 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5289 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5290 /*                                                                          */
5291 /* Look for a function in the table of known functions.                     */
5292 /* ------------------------------------------------------------------------ */
5293 static ipfunc_t
ipf_findfunc(ipfunc_t funcptr)5294 ipf_findfunc(ipfunc_t funcptr)
5295 {
5296 	ipfunc_resolve_t *ft;
5297 
5298 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5299 		if (ft->ipfu_addr == funcptr)
5300 			return funcptr;
5301 	return NULL;
5302 }
5303 
5304 
5305 /* ------------------------------------------------------------------------ */
5306 /* Function:    ipf_resolvefunc                                             */
5307 /* Returns:     int - 0 == success, else error                              */
5308 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5309 /*                                                                          */
5310 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5311 /* This will either be the function name (if the pointer is set) or the     */
5312 /* function pointer if the name is set.  When found, fill in the other one  */
5313 /* so that the entire, complete, structure can be copied back to user space.*/
5314 /* ------------------------------------------------------------------------ */
5315 int
ipf_resolvefunc(ipf_main_softc_t * softc,void * data)5316 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5317 {
5318 	ipfunc_resolve_t res, *ft;
5319 	int error;
5320 
5321 	error = BCOPYIN(data, &res, sizeof(res));
5322 	if (error != 0) {
5323 		IPFERROR(123);
5324 		return EFAULT;
5325 	}
5326 
5327 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5328 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5329 			if (strncmp(res.ipfu_name, ft->ipfu_name,
5330 				    sizeof(res.ipfu_name)) == 0) {
5331 				res.ipfu_addr = ft->ipfu_addr;
5332 				res.ipfu_init = ft->ipfu_init;
5333 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5334 					IPFERROR(35);
5335 					return EFAULT;
5336 				}
5337 				return 0;
5338 			}
5339 	}
5340 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5341 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5342 			if (ft->ipfu_addr == res.ipfu_addr) {
5343 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5344 					       sizeof(res.ipfu_name));
5345 				res.ipfu_init = ft->ipfu_init;
5346 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5347 					IPFERROR(36);
5348 					return EFAULT;
5349 				}
5350 				return 0;
5351 			}
5352 	}
5353 	IPFERROR(37);
5354 	return ESRCH;
5355 }
5356 
5357 
5358 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5359      !defined(__FreeBSD__)) || \
5360     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5361     OPENBSD_LT_REV(200006)
5362 /*
5363  * From: NetBSD
5364  * ppsratecheck(): packets (or events) per second limitation.
5365  */
5366 int
ppsratecheck(lasttime,curpps,maxpps)5367 ppsratecheck(lasttime, curpps, maxpps)
5368 	struct timeval *lasttime;
5369 	int *curpps;
5370 	int maxpps;	/* maximum pps allowed */
5371 {
5372 	struct timeval tv, delta;
5373 	int rv;
5374 
5375 	GETKTIME(&tv);
5376 
5377 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5378 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5379 	if (delta.tv_usec < 0) {
5380 		delta.tv_sec--;
5381 		delta.tv_usec += 1000000;
5382 	}
5383 
5384 	/*
5385 	 * check for 0,0 is so that the message will be seen at least once.
5386 	 * if more than one second have passed since the last update of
5387 	 * lasttime, reset the counter.
5388 	 *
5389 	 * we do increment *curpps even in *curpps < maxpps case, as some may
5390 	 * try to use *curpps for stat purposes as well.
5391 	 */
5392 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5393 	    delta.tv_sec >= 1) {
5394 		*lasttime = tv;
5395 		*curpps = 0;
5396 		rv = 1;
5397 	} else if (maxpps < 0)
5398 		rv = 1;
5399 	else if (*curpps < maxpps)
5400 		rv = 1;
5401 	else
5402 		rv = 0;
5403 	*curpps = *curpps + 1;
5404 
5405 	return (rv);
5406 }
5407 #endif
5408 
5409 
5410 /* ------------------------------------------------------------------------ */
5411 /* Function:    ipf_derefrule                                               */
5412 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5413 /* Parameters:  fr(I) - pointer to filter rule                              */
5414 /*                                                                          */
5415 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5416 /* free it and any associated storage space being used by it.               */
5417 /* ------------------------------------------------------------------------ */
5418 int
ipf_derefrule(ipf_main_softc_t * softc,frentry_t ** frp)5419 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5420 {
5421 	frentry_t *fr;
5422 	frdest_t *fdp;
5423 
5424 	fr = *frp;
5425 	*frp = NULL;
5426 
5427 	MUTEX_ENTER(&fr->fr_lock);
5428 	fr->fr_ref--;
5429 	if (fr->fr_ref == 0) {
5430 		MUTEX_EXIT(&fr->fr_lock);
5431 		MUTEX_DESTROY(&fr->fr_lock);
5432 
5433 		ipf_funcfini(softc, fr);
5434 
5435 		fdp = &fr->fr_tif;
5436 		if (fdp->fd_type == FRD_DSTLIST)
5437 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5438 
5439 		fdp = &fr->fr_rif;
5440 		if (fdp->fd_type == FRD_DSTLIST)
5441 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5442 
5443 		fdp = &fr->fr_dif;
5444 		if (fdp->fd_type == FRD_DSTLIST)
5445 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5446 
5447 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5448 		    fr->fr_satype == FRI_LOOKUP)
5449 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5450 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5451 		    fr->fr_datype == FRI_LOOKUP)
5452 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5453 
5454 		if (fr->fr_grp != NULL)
5455 			ipf_group_del(softc, fr->fr_grp, fr);
5456 
5457 		if (fr->fr_grphead != NULL)
5458 			ipf_group_del(softc, fr->fr_grphead, fr);
5459 
5460 		if (fr->fr_icmpgrp != NULL)
5461 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5462 
5463 		if ((fr->fr_flags & FR_COPIED) != 0) {
5464 			if (fr->fr_dsize) {
5465 				KFREES(fr->fr_data, fr->fr_dsize);
5466 			}
5467 			KFREES(fr, fr->fr_size);
5468 			return 0;
5469 		}
5470 		return 1;
5471 	} else {
5472 		MUTEX_EXIT(&fr->fr_lock);
5473 	}
5474 	return -1;
5475 }
5476 
5477 
5478 /* ------------------------------------------------------------------------ */
5479 /* Function:    ipf_grpmapinit                                              */
5480 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5481 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5482 /*                                                                          */
5483 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5484 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5485 /* ------------------------------------------------------------------------ */
5486 static int
ipf_grpmapinit(ipf_main_softc_t * softc,frentry_t * fr)5487 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5488 {
5489 	char name[FR_GROUPLEN];
5490 	iphtable_t *iph;
5491 
5492 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5493 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5494 	if (iph == NULL) {
5495 		IPFERROR(38);
5496 		return ESRCH;
5497 	}
5498 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5499 		IPFERROR(39);
5500 		return ESRCH;
5501 	}
5502 	iph->iph_ref++;
5503 	fr->fr_ptr = iph;
5504 	return 0;
5505 }
5506 
5507 
5508 /* ------------------------------------------------------------------------ */
5509 /* Function:    ipf_grpmapfini                                              */
5510 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5511 /* Parameters:  softc(I) - pointer to soft context main structure           */
5512 /*              fr(I)    - pointer to rule to release hash table for        */
5513 /*                                                                          */
5514 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5515 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5516 /* ------------------------------------------------------------------------ */
5517 static int
ipf_grpmapfini(ipf_main_softc_t * softc,frentry_t * fr)5518 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5519 {
5520 	iphtable_t *iph;
5521 	iph = fr->fr_ptr;
5522 	if (iph != NULL)
5523 		ipf_lookup_deref(softc, IPLT_HASH, iph);
5524 	return 0;
5525 }
5526 
5527 
5528 /* ------------------------------------------------------------------------ */
5529 /* Function:    ipf_srcgrpmap                                               */
5530 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5531 /* Parameters:  fin(I)    - pointer to packet information                   */
5532 /*              passp(IO) - pointer to current/new filter decision (unused) */
5533 /*                                                                          */
5534 /* Look for a rule group head in a hash table, using the source address as  */
5535 /* the key, and descend into that group and continue matching rules against */
5536 /* the packet.                                                              */
5537 /* ------------------------------------------------------------------------ */
5538 frentry_t *
ipf_srcgrpmap(fr_info_t * fin,u_32_t * passp)5539 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5540 {
5541 	frgroup_t *fg;
5542 	void *rval;
5543 
5544 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5545 				 &fin->fin_src);
5546 	if (rval == NULL)
5547 		return NULL;
5548 
5549 	fg = rval;
5550 	fin->fin_fr = fg->fg_start;
5551 	(void) ipf_scanlist(fin, *passp);
5552 	return fin->fin_fr;
5553 }
5554 
5555 
5556 /* ------------------------------------------------------------------------ */
5557 /* Function:    ipf_dstgrpmap                                               */
5558 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5559 /* Parameters:  fin(I)    - pointer to packet information                   */
5560 /*              passp(IO) - pointer to current/new filter decision (unused) */
5561 /*                                                                          */
5562 /* Look for a rule group head in a hash table, using the destination        */
5563 /* address as the key, and descend into that group and continue matching    */
5564 /* rules against  the packet.                                               */
5565 /* ------------------------------------------------------------------------ */
5566 frentry_t *
ipf_dstgrpmap(fr_info_t * fin,u_32_t * passp)5567 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5568 {
5569 	frgroup_t *fg;
5570 	void *rval;
5571 
5572 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5573 				 &fin->fin_dst);
5574 	if (rval == NULL)
5575 		return NULL;
5576 
5577 	fg = rval;
5578 	fin->fin_fr = fg->fg_start;
5579 	(void) ipf_scanlist(fin, *passp);
5580 	return fin->fin_fr;
5581 }
5582 
5583 /*
5584  * Queue functions
5585  * ===============
5586  * These functions manage objects on queues for efficient timeouts.  There
5587  * are a number of system defined queues as well as user defined timeouts.
5588  * It is expected that a lock is held in the domain in which the queue
5589  * belongs (i.e. either state or NAT) when calling any of these functions
5590  * that prevents ipf_freetimeoutqueue() from being called at the same time
5591  * as any other.
5592  */
5593 
5594 
5595 /* ------------------------------------------------------------------------ */
5596 /* Function:    ipf_addtimeoutqueue                                         */
5597 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5598 /*                               timeout queue with given interval.         */
5599 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5600 /*                           of interface queues.                           */
5601 /*              seconds(I) - timeout value in seconds for this queue.       */
5602 /*                                                                          */
5603 /* This routine first looks for a timeout queue that matches the interval   */
5604 /* being requested.  If it finds one, increments the reference counter and  */
5605 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5606 /* inserts it at the top of the list.                                       */
5607 /*                                                                          */
5608 /* Locking.                                                                 */
5609 /* It is assumed that the caller of this function has an appropriate lock   */
5610 /* held (exclusively) in the domain that encompases 'parent'.               */
5611 /* ------------------------------------------------------------------------ */
5612 ipftq_t *
ipf_addtimeoutqueue(ipf_main_softc_t * softc,ipftq_t ** parent,u_int seconds)5613 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5614 {
5615 	ipftq_t *ifq;
5616 	u_int period;
5617 
5618 	period = seconds * IPF_HZ_DIVIDE;
5619 
5620 	MUTEX_ENTER(&softc->ipf_timeoutlock);
5621 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5622 		if (ifq->ifq_ttl == period) {
5623 			/*
5624 			 * Reset the delete flag, if set, so the structure
5625 			 * gets reused rather than freed and reallocated.
5626 			 */
5627 			MUTEX_ENTER(&ifq->ifq_lock);
5628 			ifq->ifq_flags &= ~IFQF_DELETE;
5629 			ifq->ifq_ref++;
5630 			MUTEX_EXIT(&ifq->ifq_lock);
5631 			MUTEX_EXIT(&softc->ipf_timeoutlock);
5632 
5633 			return ifq;
5634 		}
5635 	}
5636 
5637 	KMALLOC(ifq, ipftq_t *);
5638 	if (ifq != NULL) {
5639 		MUTEX_NUKE(&ifq->ifq_lock);
5640 		IPFTQ_INIT(ifq, period, "ipftq mutex");
5641 		ifq->ifq_next = *parent;
5642 		ifq->ifq_pnext = parent;
5643 		ifq->ifq_flags = IFQF_USER;
5644 		ifq->ifq_ref++;
5645 		*parent = ifq;
5646 		softc->ipf_userifqs++;
5647 	}
5648 	MUTEX_EXIT(&softc->ipf_timeoutlock);
5649 	return ifq;
5650 }
5651 
5652 
5653 /* ------------------------------------------------------------------------ */
5654 /* Function:    ipf_deletetimeoutqueue                                      */
5655 /* Returns:     int    - new reference count value of the timeout queue     */
5656 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5657 /* Locks:       ifq->ifq_lock                                               */
5658 /*                                                                          */
5659 /* This routine must be called when we're discarding a pointer to a timeout */
5660 /* queue object, taking care of the reference counter.                      */
5661 /*                                                                          */
5662 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5663 /* check the list of user defined timeout queues and call the free function */
5664 /* below (currently commented out) to stop memory leaking.  It is done this */
5665 /* way because the locking may not be sufficient to safely do a free when   */
5666 /* this function is called.                                                 */
5667 /* ------------------------------------------------------------------------ */
5668 int
ipf_deletetimeoutqueue(ipftq_t * ifq)5669 ipf_deletetimeoutqueue(ipftq_t *ifq)
5670 {
5671 
5672 	ifq->ifq_ref--;
5673 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5674 		ifq->ifq_flags |= IFQF_DELETE;
5675 	}
5676 
5677 	return ifq->ifq_ref;
5678 }
5679 
5680 
5681 /* ------------------------------------------------------------------------ */
5682 /* Function:    ipf_freetimeoutqueue                                        */
5683 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5684 /* Returns:     Nil                                                         */
5685 /*                                                                          */
5686 /* Locking:                                                                 */
5687 /* It is assumed that the caller of this function has an appropriate lock   */
5688 /* held (exclusively) in the domain that encompases the callers "domain".   */
5689 /* The ifq_lock for this structure should not be held.                      */
5690 /*                                                                          */
5691 /* Remove a user defined timeout queue from the list of queues it is in and */
5692 /* tidy up after this is done.                                              */
5693 /* ------------------------------------------------------------------------ */
5694 void
ipf_freetimeoutqueue(ipf_main_softc_t * softc,ipftq_t * ifq)5695 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5696 {
5697 
5698 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5699 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5700 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5701 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5702 		       ifq->ifq_ref);
5703 		return;
5704 	}
5705 
5706 	/*
5707 	 * Remove from its position in the list.
5708 	 */
5709 	*ifq->ifq_pnext = ifq->ifq_next;
5710 	if (ifq->ifq_next != NULL)
5711 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5712 	ifq->ifq_next = NULL;
5713 	ifq->ifq_pnext = NULL;
5714 
5715 	MUTEX_DESTROY(&ifq->ifq_lock);
5716 	ATOMIC_DEC(softc->ipf_userifqs);
5717 	KFREE(ifq);
5718 }
5719 
5720 
5721 /* ------------------------------------------------------------------------ */
5722 /* Function:    ipf_deletequeueentry                                        */
5723 /* Returns:     Nil                                                         */
5724 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5725 /*                                                                          */
5726 /* Remove a tail queue entry from its queue and make it an orphan.          */
5727 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5728 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5729 /* the correct lock(s) may not be held that would make it safe to do so.    */
5730 /* ------------------------------------------------------------------------ */
5731 void
ipf_deletequeueentry(ipftqent_t * tqe)5732 ipf_deletequeueentry(ipftqent_t *tqe)
5733 {
5734 	ipftq_t *ifq;
5735 
5736 	ifq = tqe->tqe_ifq;
5737 
5738 	MUTEX_ENTER(&ifq->ifq_lock);
5739 
5740 	if (tqe->tqe_pnext != NULL) {
5741 		*tqe->tqe_pnext = tqe->tqe_next;
5742 		if (tqe->tqe_next != NULL)
5743 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5744 		else    /* we must be the tail anyway */
5745 			ifq->ifq_tail = tqe->tqe_pnext;
5746 
5747 		tqe->tqe_pnext = NULL;
5748 		tqe->tqe_ifq = NULL;
5749 	}
5750 
5751 	(void) ipf_deletetimeoutqueue(ifq);
5752 	ASSERT(ifq->ifq_ref > 0);
5753 
5754 	MUTEX_EXIT(&ifq->ifq_lock);
5755 }
5756 
5757 
5758 /* ------------------------------------------------------------------------ */
5759 /* Function:    ipf_queuefront                                              */
5760 /* Returns:     Nil                                                         */
5761 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5762 /*                                                                          */
5763 /* Move a queue entry to the front of the queue, if it isn't already there. */
5764 /* ------------------------------------------------------------------------ */
5765 void
ipf_queuefront(ipftqent_t * tqe)5766 ipf_queuefront(ipftqent_t *tqe)
5767 {
5768 	ipftq_t *ifq;
5769 
5770 	ifq = tqe->tqe_ifq;
5771 	if (ifq == NULL)
5772 		return;
5773 
5774 	MUTEX_ENTER(&ifq->ifq_lock);
5775 	if (ifq->ifq_head != tqe) {
5776 		*tqe->tqe_pnext = tqe->tqe_next;
5777 		if (tqe->tqe_next)
5778 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5779 		else
5780 			ifq->ifq_tail = tqe->tqe_pnext;
5781 
5782 		tqe->tqe_next = ifq->ifq_head;
5783 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5784 		ifq->ifq_head = tqe;
5785 		tqe->tqe_pnext = &ifq->ifq_head;
5786 	}
5787 	MUTEX_EXIT(&ifq->ifq_lock);
5788 }
5789 
5790 
5791 /* ------------------------------------------------------------------------ */
5792 /* Function:    ipf_queueback                                               */
5793 /* Returns:     Nil                                                         */
5794 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5795 /*              tqe(I)   - pointer to timeout queue entry                   */
5796 /*                                                                          */
5797 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5798 /* We use use ticks to calculate the expiration and mark for when we last   */
5799 /* touched the structure.                                                   */
5800 /* ------------------------------------------------------------------------ */
5801 void
ipf_queueback(u_long ticks,ipftqent_t * tqe)5802 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5803 {
5804 	ipftq_t *ifq;
5805 
5806 	ifq = tqe->tqe_ifq;
5807 	if (ifq == NULL)
5808 		return;
5809 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5810 	tqe->tqe_touched = ticks;
5811 
5812 	MUTEX_ENTER(&ifq->ifq_lock);
5813 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5814 		/*
5815 		 * Remove from list
5816 		 */
5817 		*tqe->tqe_pnext = tqe->tqe_next;
5818 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5819 
5820 		/*
5821 		 * Make it the last entry.
5822 		 */
5823 		tqe->tqe_next = NULL;
5824 		tqe->tqe_pnext = ifq->ifq_tail;
5825 		*ifq->ifq_tail = tqe;
5826 		ifq->ifq_tail = &tqe->tqe_next;
5827 	}
5828 	MUTEX_EXIT(&ifq->ifq_lock);
5829 }
5830 
5831 
5832 /* ------------------------------------------------------------------------ */
5833 /* Function:    ipf_queueappend                                             */
5834 /* Returns:     Nil                                                         */
5835 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5836 /*              tqe(I)    - pointer to timeout queue entry                  */
5837 /*              ifq(I)    - pointer to timeout queue                        */
5838 /*              parent(I) - owing object pointer                            */
5839 /*                                                                          */
5840 /* Add a new item to this queue and put it on the very end.                 */
5841 /* We use use ticks to calculate the expiration and mark for when we last   */
5842 /* touched the structure.                                                   */
5843 /* ------------------------------------------------------------------------ */
5844 void
ipf_queueappend(u_long ticks,ipftqent_t * tqe,ipftq_t * ifq,void * parent)5845 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5846 {
5847 
5848 	MUTEX_ENTER(&ifq->ifq_lock);
5849 	tqe->tqe_parent = parent;
5850 	tqe->tqe_pnext = ifq->ifq_tail;
5851 	*ifq->ifq_tail = tqe;
5852 	ifq->ifq_tail = &tqe->tqe_next;
5853 	tqe->tqe_next = NULL;
5854 	tqe->tqe_ifq = ifq;
5855 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5856 	tqe->tqe_touched = ticks;
5857 	ifq->ifq_ref++;
5858 	MUTEX_EXIT(&ifq->ifq_lock);
5859 }
5860 
5861 
5862 /* ------------------------------------------------------------------------ */
5863 /* Function:    ipf_movequeue                                               */
5864 /* Returns:     Nil                                                         */
5865 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5866 /*              oifp(I) - old timeout queue entry was on                    */
5867 /*              nifp(I) - new timeout queue to put entry on                 */
5868 /*                                                                          */
5869 /* Move a queue entry from one timeout queue to another timeout queue.      */
5870 /* If it notices that the current entry is already last and does not need   */
5871 /* to move queue, the return.                                               */
5872 /* ------------------------------------------------------------------------ */
5873 void
ipf_movequeue(u_long ticks,ipftqent_t * tqe,ipftq_t * oifq,ipftq_t * nifq)5874 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5875 {
5876 
5877 	/*
5878 	 * If the queue hasn't changed and we last touched this entry at the
5879 	 * same ipf time, then we're not going to achieve anything by either
5880 	 * changing the ttl or moving it on the queue.
5881 	 */
5882 	if (oifq == nifq && tqe->tqe_touched == ticks)
5883 		return;
5884 
5885 	/*
5886 	 * For any of this to be outside the lock, there is a risk that two
5887 	 * packets entering simultaneously, with one changing to a different
5888 	 * queue and one not, could end up with things in a bizarre state.
5889 	 */
5890 	MUTEX_ENTER(&oifq->ifq_lock);
5891 
5892 	tqe->tqe_touched = ticks;
5893 	tqe->tqe_die = ticks + nifq->ifq_ttl;
5894 	/*
5895 	 * Is the operation here going to be a no-op ?
5896 	 */
5897 	if (oifq == nifq) {
5898 		if ((tqe->tqe_next == NULL) ||
5899 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5900 			MUTEX_EXIT(&oifq->ifq_lock);
5901 			return;
5902 		}
5903 	}
5904 
5905 	/*
5906 	 * Remove from the old queue
5907 	 */
5908 	*tqe->tqe_pnext = tqe->tqe_next;
5909 	if (tqe->tqe_next)
5910 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5911 	else
5912 		oifq->ifq_tail = tqe->tqe_pnext;
5913 	tqe->tqe_next = NULL;
5914 
5915 	/*
5916 	 * If we're moving from one queue to another, release the
5917 	 * lock on the old queue and get a lock on the new queue.
5918 	 * For user defined queues, if we're moving off it, call
5919 	 * delete in case it can now be freed.
5920 	 */
5921 	if (oifq != nifq) {
5922 		tqe->tqe_ifq = NULL;
5923 
5924 		(void) ipf_deletetimeoutqueue(oifq);
5925 
5926 		MUTEX_EXIT(&oifq->ifq_lock);
5927 
5928 		MUTEX_ENTER(&nifq->ifq_lock);
5929 
5930 		tqe->tqe_ifq = nifq;
5931 		nifq->ifq_ref++;
5932 	}
5933 
5934 	/*
5935 	 * Add to the bottom of the new queue
5936 	 */
5937 	tqe->tqe_pnext = nifq->ifq_tail;
5938 	*nifq->ifq_tail = tqe;
5939 	nifq->ifq_tail = &tqe->tqe_next;
5940 	MUTEX_EXIT(&nifq->ifq_lock);
5941 }
5942 
5943 
5944 /* ------------------------------------------------------------------------ */
5945 /* Function:    ipf_updateipid                                              */
5946 /* Returns:     int - 0 == success, -1 == error (packet should be dropped)  */
5947 /* Parameters:  fin(I) - pointer to packet information                      */
5948 /*                                                                          */
5949 /* When we are doing NAT, change the IP of every packet to represent a      */
5950 /* single sequence of packets coming from the host, hiding any host         */
5951 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5952 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5953 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5954 /* has no match in the cache, return an error.                              */
5955 /* ------------------------------------------------------------------------ */
5956 static int
ipf_updateipid(fr_info_t * fin)5957 ipf_updateipid(fr_info_t *fin)
5958 {
5959 	u_short id, ido, sums;
5960 	u_32_t sumd, sum;
5961 	ip_t *ip;
5962 
5963 	if (fin->fin_off != 0) {
5964 		sum = ipf_frag_ipidknown(fin);
5965 		if (sum == 0xffffffff)
5966 			return -1;
5967 		sum &= 0xffff;
5968 		id = (u_short)sum;
5969 	} else {
5970 		id = ipf_nextipid(fin);
5971 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5972 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
5973 	}
5974 
5975 	ip = fin->fin_ip;
5976 	ido = ntohs(ip->ip_id);
5977 	if (id == ido)
5978 		return 0;
5979 	ip->ip_id = htons(id);
5980 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5981 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5982 	sum += sumd;
5983 	sum = (sum >> 16) + (sum & 0xffff);
5984 	sum = (sum >> 16) + (sum & 0xffff);
5985 	sums = ~(u_short)sum;
5986 	ip->ip_sum = htons(sums);
5987 	return 0;
5988 }
5989 
5990 
5991 #ifdef	NEED_FRGETIFNAME
5992 /* ------------------------------------------------------------------------ */
5993 /* Function:    ipf_getifname                                               */
5994 /* Returns:     char *    - pointer to interface name                       */
5995 /* Parameters:  ifp(I)    - pointer to network interface                    */
5996 /*              buffer(O) - pointer to where to store interface name        */
5997 /*                                                                          */
5998 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5999 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6000 /* as a NULL pointer then return a pointer to a static array.               */
6001 /* ------------------------------------------------------------------------ */
6002 char *
ipf_getifname(ifp,buffer)6003 ipf_getifname(ifp, buffer)
6004 	struct ifnet *ifp;
6005 	char *buffer;
6006 {
6007 	static char namebuf[LIFNAMSIZ];
6008 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6009      defined(__sgi) || defined(linux) || defined(_AIX51) || \
6010      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6011 	int unit, space;
6012 	char temp[20];
6013 	char *s;
6014 # endif
6015 
6016 	if (buffer == NULL)
6017 		buffer = namebuf;
6018 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6019 	buffer[LIFNAMSIZ - 1] = '\0';
6020 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6021      defined(__sgi) || defined(_AIX51) || \
6022      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6023 	for (s = buffer; *s; s++)
6024 		;
6025 	unit = ifp->if_unit;
6026 	space = LIFNAMSIZ - (s - buffer);
6027 	if ((space > 0) && (unit >= 0)) {
6028 		snprintf(temp, sizeof(temp), "%d", unit);
6029 		(void) strncpy(s, temp, space);
6030 		s[space - 1] = '\0';
6031 	}
6032 # endif
6033 	return buffer;
6034 }
6035 #endif
6036 
6037 
6038 /* ------------------------------------------------------------------------ */
6039 /* Function:    ipf_ioctlswitch                                             */
6040 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6041 /* Parameters:  unit(I) - device unit opened                                */
6042 /*              data(I) - pointer to ioctl data                             */
6043 /*              cmd(I)  - ioctl command                                     */
6044 /*              mode(I) - mode value                                        */
6045 /*              uid(I)  - uid making the ioctl call                         */
6046 /*              ctx(I)  - pointer to context data                           */
6047 /*                                                                          */
6048 /* Based on the value of unit, call the appropriate ioctl handler or return */
6049 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6050 /* for the device in order to execute the ioctl.  A special case is made    */
6051 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6052 /* The context data pointer is passed through as this is used as the key    */
6053 /* for locating a matching token for continued access for walking lists,    */
6054 /* etc.                                                                     */
6055 /* ------------------------------------------------------------------------ */
6056 int
ipf_ioctlswitch(ipf_main_softc_t * softc,int unit,void * data,ioctlcmd_t cmd,int mode,int uid,void * ctx)6057 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
6058     int mode, int uid, void *ctx)
6059 {
6060 	int error = 0;
6061 
6062 	switch (cmd)
6063 	{
6064 	case SIOCIPFINTERROR :
6065 		error = BCOPYOUT(&softc->ipf_interror, data,
6066 				 sizeof(softc->ipf_interror));
6067 		if (error != 0) {
6068 			IPFERROR(40);
6069 			error = EFAULT;
6070 		}
6071 		return error;
6072 	default :
6073 		break;
6074 	}
6075 
6076 	switch (unit)
6077 	{
6078 	case IPL_LOGIPF :
6079 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6080 		break;
6081 	case IPL_LOGNAT :
6082 		if (softc->ipf_running > 0) {
6083 			error = ipf_nat_ioctl(softc, data, cmd, mode,
6084 					      uid, ctx);
6085 		} else {
6086 			IPFERROR(42);
6087 			error = EIO;
6088 		}
6089 		break;
6090 	case IPL_LOGSTATE :
6091 		if (softc->ipf_running > 0) {
6092 			error = ipf_state_ioctl(softc, data, cmd, mode,
6093 						uid, ctx);
6094 		} else {
6095 			IPFERROR(43);
6096 			error = EIO;
6097 		}
6098 		break;
6099 	case IPL_LOGAUTH :
6100 		if (softc->ipf_running > 0) {
6101 			error = ipf_auth_ioctl(softc, data, cmd, mode,
6102 					       uid, ctx);
6103 		} else {
6104 			IPFERROR(44);
6105 			error = EIO;
6106 		}
6107 		break;
6108 	case IPL_LOGSYNC :
6109 		if (softc->ipf_running > 0) {
6110 			error = ipf_sync_ioctl(softc, data, cmd, mode,
6111 					       uid, ctx);
6112 		} else {
6113 			error = EIO;
6114 			IPFERROR(45);
6115 		}
6116 		break;
6117 	case IPL_LOGSCAN :
6118 #ifdef IPFILTER_SCAN
6119 		if (softc->ipf_running > 0)
6120 			error = ipf_scan_ioctl(softc, data, cmd, mode,
6121 					       uid, ctx);
6122 		else
6123 #endif
6124 		{
6125 			error = EIO;
6126 			IPFERROR(46);
6127 		}
6128 		break;
6129 	case IPL_LOGLOOKUP :
6130 		if (softc->ipf_running > 0) {
6131 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6132 						 uid, ctx);
6133 		} else {
6134 			error = EIO;
6135 			IPFERROR(47);
6136 		}
6137 		break;
6138 	default :
6139 		IPFERROR(48);
6140 		error = EIO;
6141 		break;
6142 	}
6143 
6144 	return error;
6145 }
6146 
6147 
6148 /*
6149  * This array defines the expected size of objects coming into the kernel
6150  * for the various recognised object types. The first column is flags (see
6151  * below), 2nd column is current size, 3rd column is the version number of
6152  * when the current size became current.
6153  * Flags:
6154  * 1 = minimum size, not absolute size
6155  */
6156 static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6157 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6158 	{ 1,	sizeof(struct friostat),	5010000 },
6159 	{ 0,	sizeof(struct fr_info),		5010000 },
6160 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6161 	{ 0,	sizeof(struct ipfrstat),	5010000 },
6162 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6163 	{ 0,	sizeof(struct natstat),		5010000 },
6164 	{ 0,	sizeof(struct ipstate_save),	5010000 },
6165 	{ 1,	sizeof(struct nat_save),	5010000 },
6166 	{ 0,	sizeof(struct natlookup),	5010000 },
6167 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6168 	{ 0,	sizeof(struct ips_stat),	5010000 },
6169 	{ 0,	sizeof(struct frauth),		5010000 },
6170 	{ 0,	sizeof(struct ipftune),		4010100 },
6171 	{ 0,	sizeof(struct nat),		5010000 },
6172 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6173 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6174 	{ 0,	sizeof(struct ipftable),	4011400 },
6175 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6176 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6177 	{ 1,	0,				0	}, /* IPFEXPR */
6178 	{ 0,	0,				0	}, /* PROXYCTL */
6179 	{ 0,	sizeof (struct fripf),		5010000	}
6180 };
6181 
6182 
6183 /* ------------------------------------------------------------------------ */
6184 /* Function:    ipf_inobj                                                   */
6185 /* Returns:     int     - 0 = success, else failure                         */
6186 /* Parameters:  softc(I) - soft context pointerto work with                 */
6187 /*              data(I)  - pointer to ioctl data                            */
6188 /*              objp(O)  - where to store ipfobj structure                  */
6189 /*              ptr(I)   - pointer to data to copy out                      */
6190 /*              type(I)  - type of structure being moved                    */
6191 /*                                                                          */
6192 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6193 /* add things to check for version numbers, sizes, etc, to make it backward */
6194 /* compatible at the ABI for user land.                                     */
6195 /* If objp is not NULL then we assume that the caller wants to see what is  */
6196 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6197 /* the caller what version of ipfilter the ioctl program was written to.    */
6198 /* ------------------------------------------------------------------------ */
6199 int
ipf_inobj(ipf_main_softc_t * softc,void * data,ipfobj_t * objp,void * ptr,int type)6200 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6201     int type)
6202 {
6203 	ipfobj_t obj;
6204 	int error;
6205 	int size;
6206 
6207 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6208 		IPFERROR(49);
6209 		return EINVAL;
6210 	}
6211 
6212 	if (objp == NULL)
6213 		objp = &obj;
6214 	error = BCOPYIN(data, objp, sizeof(*objp));
6215 	if (error != 0) {
6216 		IPFERROR(124);
6217 		return EFAULT;
6218 	}
6219 
6220 	if (objp->ipfo_type != type) {
6221 		IPFERROR(50);
6222 		return EINVAL;
6223 	}
6224 
6225 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6226 		if ((ipf_objbytes[type][0] & 1) != 0) {
6227 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6228 				IPFERROR(51);
6229 				return EINVAL;
6230 			}
6231 			size =  ipf_objbytes[type][1];
6232 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6233 			size =  objp->ipfo_size;
6234 		} else {
6235 			IPFERROR(52);
6236 			return EINVAL;
6237 		}
6238 		error = COPYIN(objp->ipfo_ptr, ptr, size);
6239 		if (error != 0) {
6240 			IPFERROR(55);
6241 			error = EFAULT;
6242 		}
6243 	} else {
6244 #ifdef  IPFILTER_COMPAT
6245 		error = ipf_in_compat(softc, objp, ptr, 0);
6246 #else
6247 		IPFERROR(54);
6248 		error = EINVAL;
6249 #endif
6250 	}
6251 	return error;
6252 }
6253 
6254 
6255 /* ------------------------------------------------------------------------ */
6256 /* Function:    ipf_inobjsz                                                 */
6257 /* Returns:     int     - 0 = success, else failure                         */
6258 /* Parameters:  softc(I) - soft context pointerto work with                 */
6259 /*              data(I)  - pointer to ioctl data                            */
6260 /*              ptr(I)   - pointer to store real data in                    */
6261 /*              type(I)  - type of structure being moved                    */
6262 /*              sz(I)    - size of data to copy                             */
6263 /*                                                                          */
6264 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6265 /* but it must not be smaller than the size defined for the type and the    */
6266 /* type must allow for varied sized objects.  The extra requirement here is */
6267 /* that sz must match the size of the object being passed in - this is not  */
6268 /* not possible nor required in ipf_inobj().                                */
6269 /* ------------------------------------------------------------------------ */
6270 int
ipf_inobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6271 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6272 {
6273 	ipfobj_t obj;
6274 	int error;
6275 
6276 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6277 		IPFERROR(56);
6278 		return EINVAL;
6279 	}
6280 
6281 	error = BCOPYIN(data, &obj, sizeof(obj));
6282 	if (error != 0) {
6283 		IPFERROR(125);
6284 		return EFAULT;
6285 	}
6286 
6287 	if (obj.ipfo_type != type) {
6288 		IPFERROR(58);
6289 		return EINVAL;
6290 	}
6291 
6292 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6293 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6294 		    (sz < ipf_objbytes[type][1])) {
6295 			IPFERROR(57);
6296 			return EINVAL;
6297 		}
6298 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6299 		if (error != 0) {
6300 			IPFERROR(61);
6301 			error = EFAULT;
6302 		}
6303 	} else {
6304 #ifdef	IPFILTER_COMPAT
6305 		error = ipf_in_compat(softc, &obj, ptr, sz);
6306 #else
6307 		IPFERROR(60);
6308 		error = EINVAL;
6309 #endif
6310 	}
6311 	return error;
6312 }
6313 
6314 
6315 /* ------------------------------------------------------------------------ */
6316 /* Function:    ipf_outobjsz                                                */
6317 /* Returns:     int     - 0 = success, else failure                         */
6318 /* Parameters:  data(I) - pointer to ioctl data                             */
6319 /*              ptr(I)  - pointer to store real data in                     */
6320 /*              type(I) - type of structure being moved                     */
6321 /*              sz(I)   - size of data to copy                              */
6322 /*                                                                          */
6323 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6324 /* but it must not be smaller than the size defined for the type and the    */
6325 /* type must allow for varied sized objects.  The extra requirement here is */
6326 /* that sz must match the size of the object being passed in - this is not  */
6327 /* not possible nor required in ipf_outobj().                               */
6328 /* ------------------------------------------------------------------------ */
6329 int
ipf_outobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6330 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6331 {
6332 	ipfobj_t obj;
6333 	int error;
6334 
6335 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6336 		IPFERROR(62);
6337 		return EINVAL;
6338 	}
6339 
6340 	error = BCOPYIN(data, &obj, sizeof(obj));
6341 	if (error != 0) {
6342 		IPFERROR(127);
6343 		return EFAULT;
6344 	}
6345 
6346 	if (obj.ipfo_type != type) {
6347 		IPFERROR(63);
6348 		return EINVAL;
6349 	}
6350 
6351 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6352 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6353 		    (sz < ipf_objbytes[type][1])) {
6354 			IPFERROR(146);
6355 			return EINVAL;
6356 		}
6357 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6358 		if (error != 0) {
6359 			IPFERROR(66);
6360 			error = EFAULT;
6361 		}
6362 	} else {
6363 #ifdef	IPFILTER_COMPAT
6364 		error = ipf_out_compat(softc, &obj, ptr);
6365 #else
6366 		IPFERROR(65);
6367 		error = EINVAL;
6368 #endif
6369 	}
6370 	return error;
6371 }
6372 
6373 
6374 /* ------------------------------------------------------------------------ */
6375 /* Function:    ipf_outobj                                                  */
6376 /* Returns:     int     - 0 = success, else failure                         */
6377 /* Parameters:  data(I) - pointer to ioctl data                             */
6378 /*              ptr(I)  - pointer to store real data in                     */
6379 /*              type(I) - type of structure being moved                     */
6380 /*                                                                          */
6381 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6382 /* future, we add things to check for version numbers, sizes, etc, to make  */
6383 /* it backward  compatible at the ABI for user land.                        */
6384 /* ------------------------------------------------------------------------ */
6385 int
ipf_outobj(ipf_main_softc_t * softc,void * data,void * ptr,int type)6386 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6387 {
6388 	ipfobj_t obj;
6389 	int error;
6390 
6391 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6392 		IPFERROR(67);
6393 		return EINVAL;
6394 	}
6395 
6396 	error = BCOPYIN(data, &obj, sizeof(obj));
6397 	if (error != 0) {
6398 		IPFERROR(126);
6399 		return EFAULT;
6400 	}
6401 
6402 	if (obj.ipfo_type != type) {
6403 		IPFERROR(68);
6404 		return EINVAL;
6405 	}
6406 
6407 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6408 		if ((ipf_objbytes[type][0] & 1) != 0) {
6409 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6410 				IPFERROR(69);
6411 				return EINVAL;
6412 			}
6413 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6414 			IPFERROR(70);
6415 			return EINVAL;
6416 		}
6417 
6418 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6419 		if (error != 0) {
6420 			IPFERROR(73);
6421 			error = EFAULT;
6422 		}
6423 	} else {
6424 #ifdef	IPFILTER_COMPAT
6425 		error = ipf_out_compat(softc, &obj, ptr);
6426 #else
6427 		IPFERROR(72);
6428 		error = EINVAL;
6429 #endif
6430 	}
6431 	return error;
6432 }
6433 
6434 
6435 /* ------------------------------------------------------------------------ */
6436 /* Function:    ipf_outobjk                                                 */
6437 /* Returns:     int     - 0 = success, else failure                         */
6438 /* Parameters:  obj(I)  - pointer to data description structure             */
6439 /*              ptr(I)  - pointer to kernel data to copy out                */
6440 /*                                                                          */
6441 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6442 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6443 /* already populated with information and now we just need to use it.       */
6444 /* There is no need for this function to have a "type" parameter as there   */
6445 /* is no point in validating information that comes from the kernel with    */
6446 /* itself.                                                                  */
6447 /* ------------------------------------------------------------------------ */
6448 int
ipf_outobjk(ipf_main_softc_t * softc,ipfobj_t * obj,void * ptr)6449 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6450 {
6451 	int type = obj->ipfo_type;
6452 	int error;
6453 
6454 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6455 		IPFERROR(147);
6456 		return EINVAL;
6457 	}
6458 
6459 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6460 		if ((ipf_objbytes[type][0] & 1) != 0) {
6461 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6462 				IPFERROR(148);
6463 				return EINVAL;
6464 			}
6465 
6466 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6467 			IPFERROR(149);
6468 			return EINVAL;
6469 		}
6470 
6471 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6472 		if (error != 0) {
6473 			IPFERROR(150);
6474 			error = EFAULT;
6475 		}
6476 	} else {
6477 #ifdef  IPFILTER_COMPAT
6478 		error = ipf_out_compat(softc, obj, ptr);
6479 #else
6480 		IPFERROR(151);
6481 		error = EINVAL;
6482 #endif
6483 	}
6484 	return error;
6485 }
6486 
6487 
6488 /* ------------------------------------------------------------------------ */
6489 /* Function:    ipf_checkl4sum                                              */
6490 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6491 /* Parameters:  fin(I) - pointer to packet information                      */
6492 /*                                                                          */
6493 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6494 /* not possible, return without indicating a failure or success but in a    */
6495 /* way that is ditinguishable. This function should only be called by the   */
6496 /* ipf_checkv6sum() for each platform.                                      */
6497 /* ------------------------------------------------------------------------ */
6498 int
ipf_checkl4sum(fr_info_t * fin)6499 ipf_checkl4sum(fr_info_t *fin)
6500 {
6501 	u_short sum, hdrsum, *csump;
6502 	udphdr_t *udp;
6503 	int dosum;
6504 
6505 	/*
6506 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6507 	 * isn't already considered "bad", then validate the checksum.  If
6508 	 * this check fails then considered the packet to be "bad".
6509 	 */
6510 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6511 		return 1;
6512 
6513 	csump = NULL;
6514 	hdrsum = 0;
6515 	dosum = 0;
6516 	sum = 0;
6517 
6518 	switch (fin->fin_p)
6519 	{
6520 	case IPPROTO_TCP :
6521 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6522 		dosum = 1;
6523 		break;
6524 
6525 	case IPPROTO_UDP :
6526 		udp = fin->fin_dp;
6527 		if (udp->uh_sum != 0) {
6528 			csump = &udp->uh_sum;
6529 			dosum = 1;
6530 		}
6531 		break;
6532 
6533 #ifdef USE_INET6
6534 	case IPPROTO_ICMPV6 :
6535 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6536 		dosum = 1;
6537 		break;
6538 #endif
6539 
6540 	case IPPROTO_ICMP :
6541 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6542 		dosum = 1;
6543 		break;
6544 
6545 	default :
6546 		return 1;
6547 		/*NOTREACHED*/
6548 	}
6549 
6550 	if (csump != NULL) {
6551 		hdrsum = *csump;
6552 		if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6553 			hdrsum = 0x0000;
6554 	}
6555 
6556 	if (dosum) {
6557 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6558 	}
6559 #if !defined(_KERNEL)
6560 	if (sum == hdrsum) {
6561 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6562 	} else {
6563 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6564 	}
6565 #endif
6566 	DT2(l4sums, u_short, hdrsum, u_short, sum);
6567 	if (hdrsum == sum) {
6568 		fin->fin_cksum = FI_CK_SUMOK;
6569 		return 0;
6570 	}
6571 	fin->fin_cksum = FI_CK_BAD;
6572 	return -1;
6573 }
6574 
6575 
6576 /* ------------------------------------------------------------------------ */
6577 /* Function:    ipf_ifpfillv4addr                                           */
6578 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6579 /* Parameters:  atype(I)   - type of network address update to perform      */
6580 /*              sin(I)     - pointer to source of address information       */
6581 /*              mask(I)    - pointer to source of netmask information       */
6582 /*              inp(I)     - pointer to destination address store           */
6583 /*              inpmask(I) - pointer to destination netmask store           */
6584 /*                                                                          */
6585 /* Given a type of network address update (atype) to perform, copy          */
6586 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6587 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6588 /* which case the operation fails.  For all values of atype other than      */
6589 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6590 /* value.                                                                   */
6591 /* ------------------------------------------------------------------------ */
6592 int
ipf_ifpfillv4addr(int atype,struct sockaddr_in * sin,struct sockaddr_in * mask,struct in_addr * inp,struct in_addr * inpmask)6593 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6594     struct in_addr *inp, struct in_addr *inpmask)
6595 {
6596 	if (inpmask != NULL && atype != FRI_NETMASKED)
6597 		inpmask->s_addr = 0xffffffff;
6598 
6599 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6600 		if (atype == FRI_NETMASKED) {
6601 			if (inpmask == NULL)
6602 				return -1;
6603 			inpmask->s_addr = mask->sin_addr.s_addr;
6604 		}
6605 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6606 	} else {
6607 		inp->s_addr = sin->sin_addr.s_addr;
6608 	}
6609 	return 0;
6610 }
6611 
6612 
6613 #ifdef	USE_INET6
6614 /* ------------------------------------------------------------------------ */
6615 /* Function:    ipf_ifpfillv6addr                                           */
6616 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6617 /* Parameters:  atype(I)   - type of network address update to perform      */
6618 /*              sin(I)     - pointer to source of address information       */
6619 /*              mask(I)    - pointer to source of netmask information       */
6620 /*              inp(I)     - pointer to destination address store           */
6621 /*              inpmask(I) - pointer to destination netmask store           */
6622 /*                                                                          */
6623 /* Given a type of network address update (atype) to perform, copy          */
6624 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6625 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6626 /* which case the operation fails.  For all values of atype other than      */
6627 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6628 /* value.                                                                   */
6629 /* ------------------------------------------------------------------------ */
6630 int
ipf_ifpfillv6addr(int atype,struct sockaddr_in6 * sin,struct sockaddr_in6 * mask,i6addr_t * inp,i6addr_t * inpmask)6631 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6632     struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6633 {
6634 	i6addr_t *src, *and;
6635 
6636 	src = (i6addr_t *)&sin->sin6_addr;
6637 	and = (i6addr_t *)&mask->sin6_addr;
6638 
6639 	if (inpmask != NULL && atype != FRI_NETMASKED) {
6640 		inpmask->i6[0] = 0xffffffff;
6641 		inpmask->i6[1] = 0xffffffff;
6642 		inpmask->i6[2] = 0xffffffff;
6643 		inpmask->i6[3] = 0xffffffff;
6644 	}
6645 
6646 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6647 		if (atype == FRI_NETMASKED) {
6648 			if (inpmask == NULL)
6649 				return -1;
6650 			inpmask->i6[0] = and->i6[0];
6651 			inpmask->i6[1] = and->i6[1];
6652 			inpmask->i6[2] = and->i6[2];
6653 			inpmask->i6[3] = and->i6[3];
6654 		}
6655 
6656 		inp->i6[0] = src->i6[0] & and->i6[0];
6657 		inp->i6[1] = src->i6[1] & and->i6[1];
6658 		inp->i6[2] = src->i6[2] & and->i6[2];
6659 		inp->i6[3] = src->i6[3] & and->i6[3];
6660 	} else {
6661 		inp->i6[0] = src->i6[0];
6662 		inp->i6[1] = src->i6[1];
6663 		inp->i6[2] = src->i6[2];
6664 		inp->i6[3] = src->i6[3];
6665 	}
6666 	return 0;
6667 }
6668 #endif
6669 
6670 
6671 /* ------------------------------------------------------------------------ */
6672 /* Function:    ipf_matchtag                                                */
6673 /* Returns:     0 == mismatch, 1 == match.                                  */
6674 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6675 /*              tag2(I) - pointer to second tag to compare                  */
6676 /*                                                                          */
6677 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6678 /* considered to be a match or not match, respectively.  The tag is 16      */
6679 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6680 /* compare the ints instead, for speed. tag1 is the master of the           */
6681 /* comparison.  This function should only be called with both tag1 and tag2 */
6682 /* as non-NULL pointers.                                                    */
6683 /* ------------------------------------------------------------------------ */
6684 int
ipf_matchtag(ipftag_t * tag1,ipftag_t * tag2)6685 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6686 {
6687 	if (tag1 == tag2)
6688 		return 1;
6689 
6690 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6691 		return 1;
6692 
6693 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6694 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6695 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6696 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6697 		return 1;
6698 	return 0;
6699 }
6700 
6701 
6702 /* ------------------------------------------------------------------------ */
6703 /* Function:    ipf_coalesce                                                */
6704 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6705 /* Parameters:  fin(I) - pointer to packet information                      */
6706 /*                                                                          */
6707 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6708 /* If this call returns a failure then the buffers have also been freed.    */
6709 /* ------------------------------------------------------------------------ */
6710 int
ipf_coalesce(fr_info_t * fin)6711 ipf_coalesce(fr_info_t *fin)
6712 {
6713 
6714 	if ((fin->fin_flx & FI_COALESCE) != 0)
6715 		return 1;
6716 
6717 	/*
6718 	 * If the mbuf pointers indicate that there is no mbuf to work with,
6719 	 * return but do not indicate success or failure.
6720 	 */
6721 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6722 		return 0;
6723 
6724 #if defined(_KERNEL)
6725 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6726 		ipf_main_softc_t *softc = fin->fin_main_soft;
6727 
6728 		DT1(frb_coalesce, fr_info_t *, fin);
6729 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6730 # ifdef MENTAT
6731 		FREE_MB_T(*fin->fin_mp);
6732 # endif
6733 		fin->fin_reason = FRB_COALESCE;
6734 		*fin->fin_mp = NULL;
6735 		fin->fin_m = NULL;
6736 		return -1;
6737 	}
6738 #else
6739 	fin = fin;	/* LINT */
6740 #endif
6741 	return 1;
6742 }
6743 
6744 
6745 /*
6746  * The following table lists all of the tunable variables that can be
6747  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6748  * in the table below is as follows:
6749  *
6750  * pointer to value, name of value, minimum, maximum, size of the value's
6751  *     container, value attribute flags
6752  *
6753  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6754  * means the value can only be written to when IPFilter is loaded but disabled.
6755  * The obvious implication is if neither of these are set then the value can be
6756  * changed at any time without harm.
6757  */
6758 
6759 
6760 /* ------------------------------------------------------------------------ */
6761 /* Function:    ipf_tune_findbycookie                                       */
6762 /* Returns:     NULL = search failed, else pointer to tune struct           */
6763 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6764 /*              next(O)   - pointer to place to store the cookie for the    */
6765 /*                          "next" tuneable, if it is desired.              */
6766 /*                                                                          */
6767 /* This function is used to walk through all of the existing tunables with  */
6768 /* successive calls.  It searches the known tunables for the one which has  */
6769 /* a matching value for "cookie" - ie its address.  When returning a match, */
6770 /* the next one to be found may be returned inside next.                    */
6771 /* ------------------------------------------------------------------------ */
6772 static ipftuneable_t *
ipf_tune_findbycookie(ipftuneable_t ** ptop,void * cookie,void ** next)6773 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6774 {
6775 	ipftuneable_t *ta, **tap;
6776 
6777 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6778 		if (ta == cookie) {
6779 			if (next != NULL) {
6780 				/*
6781 				 * If the next entry in the array has a name
6782 				 * present, then return a pointer to it for
6783 				 * where to go next, else return a pointer to
6784 				 * the dynaminc list as a key to search there
6785 				 * next.  This facilitates a weak linking of
6786 				 * the two "lists" together.
6787 				 */
6788 				if ((ta + 1)->ipft_name != NULL)
6789 					*next = ta + 1;
6790 				else
6791 					*next = ptop;
6792 			}
6793 			return ta;
6794 		}
6795 
6796 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6797 		if (tap == cookie) {
6798 			if (next != NULL)
6799 				*next = &ta->ipft_next;
6800 			return ta;
6801 		}
6802 
6803 	if (next != NULL)
6804 		*next = NULL;
6805 	return NULL;
6806 }
6807 
6808 
6809 /* ------------------------------------------------------------------------ */
6810 /* Function:    ipf_tune_findbyname                                         */
6811 /* Returns:     NULL = search failed, else pointer to tune struct           */
6812 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6813 /*                                                                          */
6814 /* Search the static array of tuneables and the list of dynamic tuneables   */
6815 /* for an entry with a matching name.  If we can find one, return a pointer */
6816 /* to the matching structure.                                               */
6817 /* ------------------------------------------------------------------------ */
6818 static ipftuneable_t *
ipf_tune_findbyname(ipftuneable_t * top,const char * name)6819 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6820 {
6821 	ipftuneable_t *ta;
6822 
6823 	for (ta = top; ta != NULL; ta = ta->ipft_next)
6824 		if (!strcmp(ta->ipft_name, name)) {
6825 			return ta;
6826 		}
6827 
6828 	return NULL;
6829 }
6830 
6831 
6832 /* ------------------------------------------------------------------------ */
6833 /* Function:    ipf_tune_add_array                                          */
6834 /* Returns:     int - 0 == success, else failure                            */
6835 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6836 /*                                                                          */
6837 /* Appends tune structures from the array passed in (newtune) to the end of */
6838 /* the current list of "dynamic" tuneable parameters.                       */
6839 /* If any entry to be added is already present (by name) then the operation */
6840 /* is aborted - entries that have been added are removed before returning.  */
6841 /* An entry with no name (NULL) is used as the indication that the end of   */
6842 /* the array has been reached.                                              */
6843 /* ------------------------------------------------------------------------ */
6844 int
ipf_tune_add_array(ipf_main_softc_t * softc,ipftuneable_t * newtune)6845 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6846 {
6847 	ipftuneable_t *nt, *dt;
6848 	int error = 0;
6849 
6850 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6851 		error = ipf_tune_add(softc, nt);
6852 		if (error != 0) {
6853 			for (dt = newtune; dt != nt; dt++) {
6854 				(void) ipf_tune_del(softc, dt);
6855 			}
6856 		}
6857 	}
6858 
6859 	return error;
6860 }
6861 
6862 
6863 /* ------------------------------------------------------------------------ */
6864 /* Function:    ipf_tune_array_link                                         */
6865 /* Returns:     0 == success, -1 == failure                                 */
6866 /* Parameters:  softc(I) - soft context pointerto work with                 */
6867 /*              array(I) - pointer to an array of tuneables                 */
6868 /*                                                                          */
6869 /* Given an array of tunables (array), append them to the current list of   */
6870 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
6871 /* the array for being appended to the list, initialise all of the next     */
6872 /* pointers so we don't need to walk parts of it with ++ and others with    */
6873 /* next. The array is expected to have an entry with a NULL name as the     */
6874 /* terminator. Trying to add an array with no non-NULL names will return as */
6875 /* a failure.                                                               */
6876 /* ------------------------------------------------------------------------ */
6877 int
ipf_tune_array_link(ipf_main_softc_t * softc,ipftuneable_t * array)6878 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6879 {
6880 	ipftuneable_t *t, **p;
6881 
6882 	t = array;
6883 	if (t->ipft_name == NULL)
6884 		return -1;
6885 
6886 	for (; t[1].ipft_name != NULL; t++)
6887 		t[0].ipft_next = &t[1];
6888 	t->ipft_next = NULL;
6889 
6890 	/*
6891 	 * Since a pointer to the last entry isn't kept, we need to find it
6892 	 * each time we want to add new variables to the list.
6893 	 */
6894 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6895 		if (t->ipft_name == NULL)
6896 			break;
6897 	*p = array;
6898 
6899 	return 0;
6900 }
6901 
6902 
6903 /* ------------------------------------------------------------------------ */
6904 /* Function:    ipf_tune_array_unlink                                       */
6905 /* Returns:     0 == success, -1 == failure                                 */
6906 /* Parameters:  softc(I) - soft context pointerto work with                 */
6907 /*              array(I) - pointer to an array of tuneables                 */
6908 /*                                                                          */
6909 /* ------------------------------------------------------------------------ */
6910 int
ipf_tune_array_unlink(ipf_main_softc_t * softc,ipftuneable_t * array)6911 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6912 {
6913 	ipftuneable_t *t, **p;
6914 
6915 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6916 		if (t == array)
6917 			break;
6918 	if (t == NULL)
6919 		return -1;
6920 
6921 	for (; t[1].ipft_name != NULL; t++)
6922 		;
6923 
6924 	*p = t->ipft_next;
6925 
6926 	return 0;
6927 }
6928 
6929 
6930 /* ------------------------------------------------------------------------ */
6931 /* Function:   ipf_tune_array_copy                                          */
6932 /* Returns:    NULL = failure, else pointer to new array                    */
6933 /* Parameters: base(I)     - pointer to structure base                      */
6934 /*             size(I)     - size of the array at template                  */
6935 /*             template(I) - original array to copy                         */
6936 /*                                                                          */
6937 /* Allocate memory for a new set of tuneable values and copy everything     */
6938 /* from template into the new region of memory.  The new region is full of  */
6939 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
6940 /*                                                                          */
6941 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
6942 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
6943 /* location of the tuneable value inside the structure pointed to by base.  */
6944 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
6945 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
6946 /* ipftp_void that points to the stored value.                              */
6947 /* ------------------------------------------------------------------------ */
6948 ipftuneable_t *
ipf_tune_array_copy(void * base,size_t size,const ipftuneable_t * template)6949 ipf_tune_array_copy(void *base, size_t size, const ipftuneable_t *template)
6950 {
6951 	ipftuneable_t *copy;
6952 	int i;
6953 
6954 
6955 	KMALLOCS(copy, ipftuneable_t *, size);
6956 	if (copy == NULL) {
6957 		return NULL;
6958 	}
6959 	bcopy(template, copy, size);
6960 
6961 	for (i = 0; copy[i].ipft_name; i++) {
6962 		copy[i].ipft_una.ipftp_offset += (u_long)base;
6963 		copy[i].ipft_next = copy + i + 1;
6964 	}
6965 
6966 	return copy;
6967 }
6968 
6969 
6970 /* ------------------------------------------------------------------------ */
6971 /* Function:    ipf_tune_add                                                */
6972 /* Returns:     int - 0 == success, else failure                            */
6973 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
6974 /*                                                                          */
6975 /* Appends tune structures from the array passed in (newtune) to the end of */
6976 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
6977 /* owner of the object is not expected to ever change "ipft_next".          */
6978 /* ------------------------------------------------------------------------ */
6979 int
ipf_tune_add(ipf_main_softc_t * softc,ipftuneable_t * newtune)6980 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6981 {
6982 	ipftuneable_t *ta, **tap;
6983 
6984 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
6985 	if (ta != NULL) {
6986 		IPFERROR(74);
6987 		return EEXIST;
6988 	}
6989 
6990 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
6991 		;
6992 
6993 	newtune->ipft_next = NULL;
6994 	*tap = newtune;
6995 	return 0;
6996 }
6997 
6998 
6999 /* ------------------------------------------------------------------------ */
7000 /* Function:    ipf_tune_del                                                */
7001 /* Returns:     int - 0 == success, else failure                            */
7002 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7003 /*                        current dynamic tuneables                         */
7004 /*                                                                          */
7005 /* Search for the tune structure, by pointer, in the list of those that are */
7006 /* dynamically added at run time.  If found, adjust the list so that this   */
7007 /* structure is no longer part of it.                                       */
7008 /* ------------------------------------------------------------------------ */
7009 int
ipf_tune_del(ipf_main_softc_t * softc,ipftuneable_t * oldtune)7010 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7011 {
7012 	ipftuneable_t *ta, **tap;
7013 	int error = 0;
7014 
7015 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7016 	     tap = &ta->ipft_next) {
7017 		if (ta == oldtune) {
7018 			*tap = oldtune->ipft_next;
7019 			oldtune->ipft_next = NULL;
7020 			break;
7021 		}
7022 	}
7023 
7024 	if (ta == NULL) {
7025 		error = ESRCH;
7026 		IPFERROR(75);
7027 	}
7028 	return error;
7029 }
7030 
7031 
7032 /* ------------------------------------------------------------------------ */
7033 /* Function:    ipf_tune_del_array                                          */
7034 /* Returns:     int - 0 == success, else failure                            */
7035 /* Parameters:  oldtune - pointer to tuneables array                        */
7036 /*                                                                          */
7037 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7038 /* tunables.  If one entry should fail to be found, an error will be        */
7039 /* returned and no further ones removed.                                    */
7040 /* An entry with a NULL name is used as the indicator of the last entry in  */
7041 /* the array.                                                               */
7042 /* ------------------------------------------------------------------------ */
7043 int
ipf_tune_del_array(ipf_main_softc_t * softc,ipftuneable_t * oldtune)7044 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7045 {
7046 	ipftuneable_t *ot;
7047 	int error = 0;
7048 
7049 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7050 		error = ipf_tune_del(softc, ot);
7051 		if (error != 0)
7052 			break;
7053 	}
7054 
7055 	return error;
7056 
7057 }
7058 
7059 
7060 /* ------------------------------------------------------------------------ */
7061 /* Function:    ipf_tune                                                    */
7062 /* Returns:     int - 0 == success, else failure                            */
7063 /* Parameters:  cmd(I)  - ioctl command number                              */
7064 /*              data(I) - pointer to ioctl data structure                   */
7065 /*                                                                          */
7066 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7067 /* three ioctls provide the means to access and control global variables    */
7068 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7069 /* changed without rebooting, reloading or recompiling.  The initialisation */
7070 /* and 'destruction' routines of the various components of ipfilter are all */
7071 /* each responsible for handling their own values being too big.            */
7072 /* ------------------------------------------------------------------------ */
7073 int
ipf_ipftune(ipf_main_softc_t * softc,ioctlcmd_t cmd,void * data)7074 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
7075 {
7076 	ipftuneable_t *ta;
7077 	ipftune_t tu;
7078 	void *cookie;
7079 	int error;
7080 
7081 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7082 	if (error != 0)
7083 		return error;
7084 
7085 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7086 	cookie = tu.ipft_cookie;
7087 	ta = NULL;
7088 
7089 	switch (cmd)
7090 	{
7091 	case SIOCIPFGETNEXT :
7092 		/*
7093 		 * If cookie is non-NULL, assume it to be a pointer to the last
7094 		 * entry we looked at, so find it (if possible) and return a
7095 		 * pointer to the next one after it.  The last entry in the
7096 		 * the table is a NULL entry, so when we get to it, set cookie
7097 		 * to NULL and return that, indicating end of list, erstwhile
7098 		 * if we come in with cookie set to NULL, we are starting anew
7099 		 * at the front of the list.
7100 		 */
7101 		if (cookie != NULL) {
7102 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7103 						   cookie, &tu.ipft_cookie);
7104 		} else {
7105 			ta = softc->ipf_tuners;
7106 			tu.ipft_cookie = ta + 1;
7107 		}
7108 		if (ta != NULL) {
7109 			/*
7110 			 * Entry found, but does the data pointed to by that
7111 			 * row fit in what we can return?
7112 			 */
7113 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7114 				IPFERROR(76);
7115 				return EINVAL;
7116 			}
7117 
7118 			tu.ipft_vlong = 0;
7119 			if (ta->ipft_sz == sizeof(u_long))
7120 				tu.ipft_vlong = *ta->ipft_plong;
7121 			else if (ta->ipft_sz == sizeof(u_int))
7122 				tu.ipft_vint = *ta->ipft_pint;
7123 			else if (ta->ipft_sz == sizeof(u_short))
7124 				tu.ipft_vshort = *ta->ipft_pshort;
7125 			else if (ta->ipft_sz == sizeof(u_char))
7126 				tu.ipft_vchar = *ta->ipft_pchar;
7127 
7128 			tu.ipft_sz = ta->ipft_sz;
7129 			tu.ipft_min = ta->ipft_min;
7130 			tu.ipft_max = ta->ipft_max;
7131 			tu.ipft_flags = ta->ipft_flags;
7132 			bcopy(ta->ipft_name, tu.ipft_name,
7133 			      MIN(sizeof(tu.ipft_name),
7134 				  strlen(ta->ipft_name) + 1));
7135 		}
7136 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7137 		break;
7138 
7139 	case SIOCIPFGET :
7140 	case SIOCIPFSET :
7141 		/*
7142 		 * Search by name or by cookie value for a particular entry
7143 		 * in the tuning paramter table.
7144 		 */
7145 		IPFERROR(77);
7146 		error = ESRCH;
7147 		if (cookie != NULL) {
7148 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7149 						   cookie, NULL);
7150 			if (ta != NULL)
7151 				error = 0;
7152 		} else if (tu.ipft_name[0] != '\0') {
7153 			ta = ipf_tune_findbyname(softc->ipf_tuners,
7154 						 tu.ipft_name);
7155 			if (ta != NULL)
7156 				error = 0;
7157 		}
7158 		if (error != 0)
7159 			break;
7160 
7161 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7162 			/*
7163 			 * Fetch the tuning parameters for a particular value
7164 			 */
7165 			tu.ipft_vlong = 0;
7166 			if (ta->ipft_sz == sizeof(u_long))
7167 				tu.ipft_vlong = *ta->ipft_plong;
7168 			else if (ta->ipft_sz == sizeof(u_int))
7169 				tu.ipft_vint = *ta->ipft_pint;
7170 			else if (ta->ipft_sz == sizeof(u_short))
7171 				tu.ipft_vshort = *ta->ipft_pshort;
7172 			else if (ta->ipft_sz == sizeof(u_char))
7173 				tu.ipft_vchar = *ta->ipft_pchar;
7174 			tu.ipft_cookie = ta;
7175 			tu.ipft_sz = ta->ipft_sz;
7176 			tu.ipft_min = ta->ipft_min;
7177 			tu.ipft_max = ta->ipft_max;
7178 			tu.ipft_flags = ta->ipft_flags;
7179 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7180 
7181 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7182 			/*
7183 			 * Set an internal parameter.  The hard part here is
7184 			 * getting the new value safely and correctly out of
7185 			 * the kernel (given we only know its size, not type.)
7186 			 */
7187 			u_long in;
7188 
7189 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7190 			    (softc->ipf_running > 0)) {
7191 				IPFERROR(78);
7192 				error = EBUSY;
7193 				break;
7194 			}
7195 
7196 			in = tu.ipft_vlong;
7197 			if (in < ta->ipft_min || in > ta->ipft_max) {
7198 				IPFERROR(79);
7199 				error = EINVAL;
7200 				break;
7201 			}
7202 
7203 			if (ta->ipft_func != NULL) {
7204 				SPL_INT(s);
7205 
7206 				SPL_NET(s);
7207 				error = (*ta->ipft_func)(softc, ta,
7208 							 &tu.ipft_un);
7209 				SPL_X(s);
7210 
7211 			} else if (ta->ipft_sz == sizeof(u_long)) {
7212 				tu.ipft_vlong = *ta->ipft_plong;
7213 				*ta->ipft_plong = in;
7214 
7215 			} else if (ta->ipft_sz == sizeof(u_int)) {
7216 				tu.ipft_vint = *ta->ipft_pint;
7217 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7218 
7219 			} else if (ta->ipft_sz == sizeof(u_short)) {
7220 				tu.ipft_vshort = *ta->ipft_pshort;
7221 				*ta->ipft_pshort = (u_short)(in & 0xffff);
7222 
7223 			} else if (ta->ipft_sz == sizeof(u_char)) {
7224 				tu.ipft_vchar = *ta->ipft_pchar;
7225 				*ta->ipft_pchar = (u_char)(in & 0xff);
7226 			}
7227 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7228 		}
7229 		break;
7230 
7231 	default :
7232 		IPFERROR(80);
7233 		error = EINVAL;
7234 		break;
7235 	}
7236 
7237 	return error;
7238 }
7239 
7240 
7241 /* ------------------------------------------------------------------------ */
7242 /* Function:    ipf_zerostats                                               */
7243 /* Returns:     int - 0 = success, else failure                             */
7244 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7245 /*                                                                          */
7246 /* Copies the current statistics out to userspace and then zero's the       */
7247 /* current ones in the kernel. The lock is only held across the bzero() as  */
7248 /* the copyout may result in paging (ie network activity.)                  */
7249 /* ------------------------------------------------------------------------ */
7250 int
ipf_zerostats(ipf_main_softc_t * softc,void * data)7251 ipf_zerostats(ipf_main_softc_t *softc, void *data)
7252 {
7253 	friostat_t fio;
7254 	ipfobj_t obj;
7255 	int error;
7256 
7257 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7258 	if (error != 0)
7259 		return error;
7260 	ipf_getstat(softc, &fio, obj.ipfo_rev);
7261 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7262 	if (error != 0)
7263 		return error;
7264 
7265 	WRITE_ENTER(&softc->ipf_mutex);
7266 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7267 	RWLOCK_EXIT(&softc->ipf_mutex);
7268 
7269 	return 0;
7270 }
7271 
7272 
7273 /* ------------------------------------------------------------------------ */
7274 /* Function:    ipf_resolvedest                                             */
7275 /* Returns:     Nil                                                         */
7276 /* Parameters:  softc(I) - pointer to soft context main structure           */
7277 /*              base(I)  - where strings are stored                         */
7278 /*              fdp(IO)  - pointer to destination information to resolve    */
7279 /*              v(I)     - IP protocol version to match                     */
7280 /*                                                                          */
7281 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7282 /* if a matching name can be found for the particular IP protocol version   */
7283 /* then store the interface pointer in the frdest struct.  If no match is   */
7284 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7285 /* indicate there is no information at all in the structure.                */
7286 /* ------------------------------------------------------------------------ */
7287 int
ipf_resolvedest(ipf_main_softc_t * softc,char * base,frdest_t * fdp,int v)7288 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7289 {
7290 	int errval = 0;
7291 	void *ifp;
7292 
7293 	ifp = NULL;
7294 
7295 	if (fdp->fd_name != -1) {
7296 		if (fdp->fd_type == FRD_DSTLIST) {
7297 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7298 						  IPLT_DSTLIST,
7299 						  base + fdp->fd_name,
7300 						  NULL);
7301 			if (ifp == NULL) {
7302 				IPFERROR(144);
7303 				errval = ESRCH;
7304 			}
7305 		} else {
7306 			ifp = GETIFP(base + fdp->fd_name, v);
7307 		}
7308 	}
7309 	fdp->fd_ptr = ifp;
7310 
7311 	return errval;
7312 }
7313 
7314 
7315 /* ------------------------------------------------------------------------ */
7316 /* Function:    ipf_resolvenic                                              */
7317 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7318 /*                      pointer to interface structure for NIC              */
7319 /* Parameters:  softc(I)- pointer to soft context main structure            */
7320 /*              name(I) - complete interface name                           */
7321 /*              v(I)    - IP protocol version                               */
7322 /*                                                                          */
7323 /* Look for a network interface structure that firstly has a matching name  */
7324 /* to that passed in and that is also being used for that IP protocol       */
7325 /* version (necessary on some platforms where there are separate listings   */
7326 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7327 /*                                                                          */
7328 /* ------------------------------------------------------------------------ */
7329 void *
ipf_resolvenic(ipf_main_softc_t * softc,char * name,int v)7330 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
7331 {
7332 	void *nic;
7333 
7334 	softc = softc;	/* gcc -Wextra */
7335 	if (name[0] == '\0')
7336 		return NULL;
7337 
7338 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7339 		return NULL;
7340 	}
7341 
7342 	nic = GETIFP(name, v);
7343 	if (nic == NULL)
7344 		nic = (void *)-1;
7345 	return nic;
7346 }
7347 
7348 
7349 /* ------------------------------------------------------------------------ */
7350 /* Function:    ipf_token_expire                                            */
7351 /* Returns:     None.                                                       */
7352 /* Parameters:  softc(I) - pointer to soft context main structure           */
7353 /*                                                                          */
7354 /* This function is run every ipf tick to see if there are any tokens that  */
7355 /* have been held for too long and need to be freed up.                     */
7356 /* ------------------------------------------------------------------------ */
7357 void
ipf_token_expire(ipf_main_softc_t * softc)7358 ipf_token_expire(ipf_main_softc_t *softc)
7359 {
7360 	ipftoken_t *it;
7361 
7362 	WRITE_ENTER(&softc->ipf_tokens);
7363 	while ((it = softc->ipf_token_head) != NULL) {
7364 		if (it->ipt_die > softc->ipf_ticks)
7365 			break;
7366 
7367 		ipf_token_deref(softc, it);
7368 	}
7369 	RWLOCK_EXIT(&softc->ipf_tokens);
7370 }
7371 
7372 
7373 /* ------------------------------------------------------------------------ */
7374 /* Function:    ipf_token_flush                                             */
7375 /* Returns:     None.                                                       */
7376 /* Parameters:  softc(I) - pointer to soft context main structure           */
7377 /*                                                                          */
7378 /* Loop through all of the existing tokens and call deref to see if they    */
7379 /* can be freed. Normally a function like this might just loop on           */
7380 /* ipf_token_head but there is a chance that a token might have a ref count */
7381 /* of greater than one and in that case the the reference would drop twice  */
7382 /* by code that is only entitled to drop it once.                           */
7383 /* ------------------------------------------------------------------------ */
7384 static void
ipf_token_flush(ipf_main_softc_t * softc)7385 ipf_token_flush(ipf_main_softc_t *softc)
7386 {
7387 	ipftoken_t *it, *next;
7388 
7389 	WRITE_ENTER(&softc->ipf_tokens);
7390 	for (it = softc->ipf_token_head; it != NULL; it = next) {
7391 		next = it->ipt_next;
7392 		(void) ipf_token_deref(softc, it);
7393 	}
7394 	RWLOCK_EXIT(&softc->ipf_tokens);
7395 }
7396 
7397 
7398 /* ------------------------------------------------------------------------ */
7399 /* Function:    ipf_token_del                                               */
7400 /* Returns:     int     - 0 = success, else error                           */
7401 /* Parameters:  softc(I)- pointer to soft context main structure            */
7402 /*              type(I) - the token type to match                           */
7403 /*              uid(I)  - uid owning the token                              */
7404 /*              ptr(I)  - context pointer for the token                     */
7405 /*                                                                          */
7406 /* This function looks for a a token in the current list that matches up    */
7407 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7408 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7409 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7410 /* enables debugging to distinguish between the two paths that ultimately   */
7411 /* lead to a token to be deleted.                                           */
7412 /* ------------------------------------------------------------------------ */
7413 int
ipf_token_del(ipf_main_softc_t * softc,int type,int uid,void * ptr)7414 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7415 {
7416 	ipftoken_t *it;
7417 	int error;
7418 
7419 	IPFERROR(82);
7420 	error = ESRCH;
7421 
7422 	WRITE_ENTER(&softc->ipf_tokens);
7423 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7424 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7425 		    uid == it->ipt_uid) {
7426 			it->ipt_complete = 2;
7427 			ipf_token_deref(softc, it);
7428 			error = 0;
7429 			break;
7430 		}
7431 	}
7432 	RWLOCK_EXIT(&softc->ipf_tokens);
7433 
7434 	return error;
7435 }
7436 
7437 
7438 /* ------------------------------------------------------------------------ */
7439 /* Function:    ipf_token_mark_complete                                     */
7440 /* Returns:     None.                                                       */
7441 /* Parameters:  token(I) - pointer to token structure                       */
7442 /*                                                                          */
7443 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7444 /* ------------------------------------------------------------------------ */
7445 void
ipf_token_mark_complete(ipftoken_t * token)7446 ipf_token_mark_complete(ipftoken_t *token)
7447 {
7448 	if (token->ipt_complete == 0)
7449 		token->ipt_complete = 1;
7450 }
7451 
7452 
7453 /* ------------------------------------------------------------------------ */
7454 /* Function:    ipf_token_find                                               */
7455 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7456 /* Parameters:  softc(I)- pointer to soft context main structure            */
7457 /*              type(I) - the token type to match                           */
7458 /*              uid(I)  - uid owning the token                              */
7459 /*              ptr(I)  - context pointer for the token                     */
7460 /*                                                                          */
7461 /* This function looks for a live token in the list of current tokens that  */
7462 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7463 /* allocated.  If one is found then it is moved to the top of the list of   */
7464 /* currently active tokens.                                                 */
7465 /* ------------------------------------------------------------------------ */
7466 ipftoken_t *
ipf_token_find(ipf_main_softc_t * softc,int type,int uid,void * ptr)7467 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7468 {
7469 	ipftoken_t *it, *new;
7470 
7471 	KMALLOC(new, ipftoken_t *);
7472 	if (new != NULL)
7473 		bzero((char *)new, sizeof(*new));
7474 
7475 	WRITE_ENTER(&softc->ipf_tokens);
7476 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7477 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7478 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7479 			break;
7480 	}
7481 
7482 	if (it == NULL) {
7483 		it = new;
7484 		new = NULL;
7485 		if (it == NULL) {
7486 			RWLOCK_EXIT(&softc->ipf_tokens);
7487 			return NULL;
7488 		}
7489 		it->ipt_ctx = ptr;
7490 		it->ipt_uid = uid;
7491 		it->ipt_type = type;
7492 		it->ipt_ref = 1;
7493 	} else {
7494 		if (new != NULL) {
7495 			KFREE(new);
7496 			new = NULL;
7497 		}
7498 
7499 		if (it->ipt_complete > 0)
7500 			it = NULL;
7501 		else
7502 			ipf_token_unlink(softc, it);
7503 	}
7504 
7505 	if (it != NULL) {
7506 		it->ipt_pnext = softc->ipf_token_tail;
7507 		*softc->ipf_token_tail = it;
7508 		softc->ipf_token_tail = &it->ipt_next;
7509 		it->ipt_next = NULL;
7510 		it->ipt_ref++;
7511 
7512 		it->ipt_die = softc->ipf_ticks + 20;
7513 	}
7514 
7515 	RWLOCK_EXIT(&softc->ipf_tokens);
7516 
7517 	return it;
7518 }
7519 
7520 
7521 /* ------------------------------------------------------------------------ */
7522 /* Function:    ipf_token_unlink                                            */
7523 /* Returns:     None.                                                       */
7524 /* Parameters:  softc(I) - pointer to soft context main structure           */
7525 /*              token(I) - pointer to token structure                       */
7526 /* Write Locks: ipf_tokens                                                  */
7527 /*                                                                          */
7528 /* This function unlinks a token structure from the linked list of tokens   */
7529 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7530 /* but the tail does due to the linked list implementation.                 */
7531 /* ------------------------------------------------------------------------ */
7532 static void
ipf_token_unlink(ipf_main_softc_t * softc,ipftoken_t * token)7533 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7534 {
7535 
7536 	if (softc->ipf_token_tail == &token->ipt_next)
7537 		softc->ipf_token_tail = token->ipt_pnext;
7538 
7539 	*token->ipt_pnext = token->ipt_next;
7540 	if (token->ipt_next != NULL)
7541 		token->ipt_next->ipt_pnext = token->ipt_pnext;
7542 	token->ipt_next = NULL;
7543 	token->ipt_pnext = NULL;
7544 }
7545 
7546 
7547 /* ------------------------------------------------------------------------ */
7548 /* Function:    ipf_token_deref                                             */
7549 /* Returns:     int      - 0 == token freed, else reference count           */
7550 /* Parameters:  softc(I) - pointer to soft context main structure           */
7551 /*              token(I) - pointer to token structure                       */
7552 /* Write Locks: ipf_tokens                                                  */
7553 /*                                                                          */
7554 /* Drop the reference count on the token structure and if it drops to zero, */
7555 /* call the dereference function for the token type because it is then      */
7556 /* possible to free the token data structure.                               */
7557 /* ------------------------------------------------------------------------ */
7558 int
ipf_token_deref(ipf_main_softc_t * softc,ipftoken_t * token)7559 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7560 {
7561 	void *data, **datap;
7562 
7563 	ASSERT(token->ipt_ref > 0);
7564 	token->ipt_ref--;
7565 	if (token->ipt_ref > 0)
7566 		return token->ipt_ref;
7567 
7568 	data = token->ipt_data;
7569 	datap = &data;
7570 
7571 	if ((data != NULL) && (data != (void *)-1)) {
7572 		switch (token->ipt_type)
7573 		{
7574 		case IPFGENITER_IPF :
7575 			(void) ipf_derefrule(softc, (frentry_t **)datap);
7576 			break;
7577 		case IPFGENITER_IPNAT :
7578 			WRITE_ENTER(&softc->ipf_nat);
7579 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7580 			RWLOCK_EXIT(&softc->ipf_nat);
7581 			break;
7582 		case IPFGENITER_NAT :
7583 			ipf_nat_deref(softc, (nat_t **)datap);
7584 			break;
7585 		case IPFGENITER_STATE :
7586 			ipf_state_deref(softc, (ipstate_t **)datap);
7587 			break;
7588 		case IPFGENITER_FRAG :
7589 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7590 			break;
7591 		case IPFGENITER_NATFRAG :
7592 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7593 			break;
7594 		case IPFGENITER_HOSTMAP :
7595 			WRITE_ENTER(&softc->ipf_nat);
7596 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7597 			RWLOCK_EXIT(&softc->ipf_nat);
7598 			break;
7599 		default :
7600 			ipf_lookup_iterderef(softc, token->ipt_type, data);
7601 			break;
7602 		}
7603 	}
7604 
7605 	ipf_token_unlink(softc, token);
7606 	KFREE(token);
7607 	return 0;
7608 }
7609 
7610 
7611 /* ------------------------------------------------------------------------ */
7612 /* Function:    ipf_nextrule                                                */
7613 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7614 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7615 /*              fr(I)       - pointer to filter rule                        */
7616 /*              out(I)      - 1 == out rules, 0 == input rules              */
7617 /*                                                                          */
7618 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7619 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7620 /* last rule in the list. When walking rule lists, it is either input or    */
7621 /* output rules that are returned, never both.                              */
7622 /* ------------------------------------------------------------------------ */
7623 static frentry_t *
ipf_nextrule(ipf_main_softc_t * softc,int active,int unit,frentry_t * fr,int out)7624 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
7625     frentry_t *fr, int out)
7626 {
7627 	frentry_t *next;
7628 	frgroup_t *fg;
7629 
7630 	if (fr != NULL && fr->fr_group != -1) {
7631 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7632 				   unit, active, NULL);
7633 		if (fg != NULL)
7634 			fg = fg->fg_next;
7635 	} else {
7636 		fg = softc->ipf_groups[unit][active];
7637 	}
7638 
7639 	while (fg != NULL) {
7640 		next = fg->fg_start;
7641 		while (next != NULL) {
7642 			if (out) {
7643 				if (next->fr_flags & FR_OUTQUE)
7644 					return next;
7645 			} else if (next->fr_flags & FR_INQUE) {
7646 				return next;
7647 			}
7648 			next = next->fr_next;
7649 		}
7650 		if (next == NULL)
7651 			fg = fg->fg_next;
7652 	}
7653 
7654 	return NULL;
7655 }
7656 
7657 /* ------------------------------------------------------------------------ */
7658 /* Function:    ipf_getnextrule                                             */
7659 /* Returns:     int - 0 = success, else error                               */
7660 /* Parameters:  softc(I)- pointer to soft context main structure            */
7661 /*              t(I)   - pointer to destination information to resolve      */
7662 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7663 /*                                                                          */
7664 /* This function's first job is to bring in the ipfruleiter_t structure via */
7665 /* the ipfobj_t structure to determine what should be the next rule to      */
7666 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7667 /* find the 'next rule'.  This may include searching rule group lists or    */
7668 /* just be as simple as looking at the 'next' field in the rule structure.  */
7669 /* When we have found the rule to return, increase its reference count and  */
7670 /* if we used an existing rule to get here, decrease its reference count.   */
7671 /* ------------------------------------------------------------------------ */
7672 int
ipf_getnextrule(ipf_main_softc_t * softc,ipftoken_t * t,void * ptr)7673 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7674 {
7675 	frentry_t *fr, *next, zero;
7676 	ipfruleiter_t it;
7677 	int error, out;
7678 	frgroup_t *fg;
7679 	ipfobj_t obj;
7680 	int predict;
7681 	char *dst;
7682 	int unit;
7683 
7684 	if (t == NULL || ptr == NULL) {
7685 		IPFERROR(84);
7686 		return EFAULT;
7687 	}
7688 
7689 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7690 	if (error != 0)
7691 		return error;
7692 
7693 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7694 		IPFERROR(85);
7695 		return EINVAL;
7696 	}
7697 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7698 		IPFERROR(86);
7699 		return EINVAL;
7700 	}
7701 	if (it.iri_nrules == 0) {
7702 		IPFERROR(87);
7703 		return ENOSPC;
7704 	}
7705 	if (it.iri_rule == NULL) {
7706 		IPFERROR(88);
7707 		return EFAULT;
7708 	}
7709 
7710 	fg = NULL;
7711 	fr = t->ipt_data;
7712 	if ((it.iri_inout & F_OUT) != 0)
7713 		out = 1;
7714 	else
7715 		out = 0;
7716 	if ((it.iri_inout & F_ACIN) != 0)
7717 		unit = IPL_LOGCOUNT;
7718 	else
7719 		unit = IPL_LOGIPF;
7720 
7721 	READ_ENTER(&softc->ipf_mutex);
7722 	if (fr == NULL) {
7723 		if (*it.iri_group == '\0') {
7724 			if (unit == IPL_LOGCOUNT) {
7725 				next = softc->ipf_acct[out][it.iri_active];
7726 			} else {
7727 				next = softc->ipf_rules[out][it.iri_active];
7728 			}
7729 			if (next == NULL)
7730 				next = ipf_nextrule(softc, it.iri_active,
7731 						    unit, NULL, out);
7732 		} else {
7733 			fg = ipf_findgroup(softc, it.iri_group, unit,
7734 					   it.iri_active, NULL);
7735 			if (fg != NULL)
7736 				next = fg->fg_start;
7737 			else
7738 				next = NULL;
7739 		}
7740 	} else {
7741 		next = fr->fr_next;
7742 		if (next == NULL)
7743 			next = ipf_nextrule(softc, it.iri_active, unit,
7744 					    fr, out);
7745 	}
7746 
7747 	if (next != NULL && next->fr_next != NULL)
7748 		predict = 1;
7749 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7750 		predict = 1;
7751 	else
7752 		predict = 0;
7753 
7754 	if (fr != NULL)
7755 		(void) ipf_derefrule(softc, &fr);
7756 
7757 	obj.ipfo_type = IPFOBJ_FRENTRY;
7758 	dst = (char *)it.iri_rule;
7759 
7760 	if (next != NULL) {
7761 		obj.ipfo_size = next->fr_size;
7762 		MUTEX_ENTER(&next->fr_lock);
7763 		next->fr_ref++;
7764 		MUTEX_EXIT(&next->fr_lock);
7765 		t->ipt_data = next;
7766 	} else {
7767 		obj.ipfo_size = sizeof(frentry_t);
7768 		bzero(&zero, sizeof(zero));
7769 		next = &zero;
7770 		t->ipt_data = NULL;
7771 	}
7772 	it.iri_rule = predict ? next : NULL;
7773 	if (predict == 0)
7774 		ipf_token_mark_complete(t);
7775 
7776 	RWLOCK_EXIT(&softc->ipf_mutex);
7777 
7778 	obj.ipfo_ptr = dst;
7779 	error = ipf_outobjk(softc, &obj, next);
7780 	if (error == 0 && t->ipt_data != NULL) {
7781 		dst += obj.ipfo_size;
7782 		if (next->fr_data != NULL) {
7783 			ipfobj_t dobj;
7784 
7785 			if (next->fr_type == FR_T_IPFEXPR)
7786 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7787 			else
7788 				dobj.ipfo_type = IPFOBJ_FRIPF;
7789 			dobj.ipfo_size = next->fr_dsize;
7790 			dobj.ipfo_rev = obj.ipfo_rev;
7791 			dobj.ipfo_ptr = dst;
7792 			error = ipf_outobjk(softc, &dobj, next->fr_data);
7793 		}
7794 	}
7795 
7796 	if ((fr != NULL) && (next == &zero))
7797 		(void) ipf_derefrule(softc, &fr);
7798 
7799 	return error;
7800 }
7801 
7802 
7803 /* ------------------------------------------------------------------------ */
7804 /* Function:    ipf_frruleiter                                              */
7805 /* Returns:     int - 0 = success, else error                               */
7806 /* Parameters:  softc(I)- pointer to soft context main structure            */
7807 /*              data(I) - the token type to match                           */
7808 /*              uid(I)  - uid owning the token                              */
7809 /*              ptr(I)  - context pointer for the token                     */
7810 /*                                                                          */
7811 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
7812 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7813 /* the process doing the ioctl and use that to ask for the next rule.       */
7814 /* ------------------------------------------------------------------------ */
7815 static int
ipf_frruleiter(ipf_main_softc_t * softc,void * data,int uid,void * ctx)7816 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7817 {
7818 	ipftoken_t *token;
7819 	ipfruleiter_t it;
7820 	ipfobj_t obj;
7821 	int error;
7822 
7823 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7824 	if (token != NULL) {
7825 		error = ipf_getnextrule(softc, token, data);
7826 		WRITE_ENTER(&softc->ipf_tokens);
7827 		ipf_token_deref(softc, token);
7828 		RWLOCK_EXIT(&softc->ipf_tokens);
7829 	} else {
7830 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7831 		if (error != 0)
7832 			return error;
7833 		it.iri_rule = NULL;
7834 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7835 	}
7836 
7837 	return error;
7838 }
7839 
7840 
7841 /* ------------------------------------------------------------------------ */
7842 /* Function:    ipf_geniter                                                 */
7843 /* Returns:     int - 0 = success, else error                               */
7844 /* Parameters:  softc(I) - pointer to soft context main structure           */
7845 /*              token(I) - pointer to ipftoken_t structure                  */
7846 /*              itp(I)   - pointer to iterator data                         */
7847 /*                                                                          */
7848 /* Decide which iterator function to call using information passed through  */
7849 /* the ipfgeniter_t structure at itp.                                       */
7850 /* ------------------------------------------------------------------------ */
7851 static int
ipf_geniter(ipf_main_softc_t * softc,ipftoken_t * token,ipfgeniter_t * itp)7852 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7853 {
7854 	int error;
7855 
7856 	switch (itp->igi_type)
7857 	{
7858 	case IPFGENITER_FRAG :
7859 		error = ipf_frag_pkt_next(softc, token, itp);
7860 		break;
7861 	default :
7862 		IPFERROR(92);
7863 		error = EINVAL;
7864 		break;
7865 	}
7866 
7867 	return error;
7868 }
7869 
7870 
7871 /* ------------------------------------------------------------------------ */
7872 /* Function:    ipf_genericiter                                             */
7873 /* Returns:     int - 0 = success, else error                               */
7874 /* Parameters:  softc(I)- pointer to soft context main structure            */
7875 /*              data(I) - the token type to match                           */
7876 /*              uid(I)  - uid owning the token                              */
7877 /*              ptr(I)  - context pointer for the token                     */
7878 /*                                                                          */
7879 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
7880 /* ------------------------------------------------------------------------ */
7881 int
ipf_genericiter(ipf_main_softc_t * softc,void * data,int uid,void * ctx)7882 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7883 {
7884 	ipftoken_t *token;
7885 	ipfgeniter_t iter;
7886 	int error;
7887 
7888 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7889 	if (error != 0)
7890 		return error;
7891 
7892 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7893 	if (token != NULL) {
7894 		token->ipt_subtype = iter.igi_type;
7895 		error = ipf_geniter(softc, token, &iter);
7896 		WRITE_ENTER(&softc->ipf_tokens);
7897 		ipf_token_deref(softc, token);
7898 		RWLOCK_EXIT(&softc->ipf_tokens);
7899 	} else {
7900 		IPFERROR(93);
7901 		error = 0;
7902 	}
7903 
7904 	return error;
7905 }
7906 
7907 
7908 /* ------------------------------------------------------------------------ */
7909 /* Function:    ipf_ipf_ioctl                                               */
7910 /* Returns:     int - 0 = success, else error                               */
7911 /* Parameters:  softc(I)- pointer to soft context main structure           */
7912 /*              data(I) - the token type to match                           */
7913 /*              cmd(I)  - the ioctl command number                          */
7914 /*              mode(I) - mode flags for the ioctl                          */
7915 /*              uid(I)  - uid owning the token                              */
7916 /*              ptr(I)  - context pointer for the token                     */
7917 /*                                                                          */
7918 /* This function handles all of the ioctl command that are actually isssued */
7919 /* to the /dev/ipl device.                                                  */
7920 /* ------------------------------------------------------------------------ */
7921 int
ipf_ipf_ioctl(ipf_main_softc_t * softc,void * data,ioctlcmd_t cmd,int mode,int uid,void * ctx)7922 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
7923     int uid, void *ctx)
7924 {
7925 	friostat_t fio;
7926 	int error, tmp;
7927 	ipfobj_t obj;
7928 	SPL_INT(s);
7929 
7930 	switch (cmd)
7931 	{
7932 	case SIOCFRENB :
7933 		if (!(mode & FWRITE)) {
7934 			IPFERROR(94);
7935 			error = EPERM;
7936 		} else {
7937 			error = BCOPYIN(data, &tmp, sizeof(tmp));
7938 			if (error != 0) {
7939 				IPFERROR(95);
7940 				error = EFAULT;
7941 				break;
7942 			}
7943 
7944 			WRITE_ENTER(&softc->ipf_global);
7945 			if (tmp) {
7946 				if (softc->ipf_running > 0)
7947 					error = 0;
7948 				else
7949 					error = ipfattach(softc);
7950 				if (error == 0)
7951 					softc->ipf_running = 1;
7952 				else
7953 					(void) ipfdetach(softc);
7954 			} else {
7955 				if (softc->ipf_running == 1)
7956 					error = ipfdetach(softc);
7957 				else
7958 					error = 0;
7959 				if (error == 0)
7960 					softc->ipf_running = -1;
7961 			}
7962 			RWLOCK_EXIT(&softc->ipf_global);
7963 		}
7964 		break;
7965 
7966 	case SIOCIPFSET :
7967 		if (!(mode & FWRITE)) {
7968 			IPFERROR(96);
7969 			error = EPERM;
7970 			break;
7971 		}
7972 		/* FALLTHRU */
7973 	case SIOCIPFGETNEXT :
7974 	case SIOCIPFGET :
7975 		error = ipf_ipftune(softc, cmd, (void *)data);
7976 		break;
7977 
7978 	case SIOCSETFF :
7979 		if (!(mode & FWRITE)) {
7980 			IPFERROR(97);
7981 			error = EPERM;
7982 		} else {
7983 			error = BCOPYIN(data, &softc->ipf_flags,
7984 					sizeof(softc->ipf_flags));
7985 			if (error != 0) {
7986 				IPFERROR(98);
7987 				error = EFAULT;
7988 			}
7989 		}
7990 		break;
7991 
7992 	case SIOCGETFF :
7993 		error = BCOPYOUT(&softc->ipf_flags, data,
7994 				 sizeof(softc->ipf_flags));
7995 		if (error != 0) {
7996 			IPFERROR(99);
7997 			error = EFAULT;
7998 		}
7999 		break;
8000 
8001 	case SIOCFUNCL :
8002 		error = ipf_resolvefunc(softc, (void *)data);
8003 		break;
8004 
8005 	case SIOCINAFR :
8006 	case SIOCRMAFR :
8007 	case SIOCADAFR :
8008 	case SIOCZRLST :
8009 		if (!(mode & FWRITE)) {
8010 			IPFERROR(100);
8011 			error = EPERM;
8012 		} else {
8013 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
8014 					  softc->ipf_active, 1);
8015 		}
8016 		break;
8017 
8018 	case SIOCINIFR :
8019 	case SIOCRMIFR :
8020 	case SIOCADIFR :
8021 		if (!(mode & FWRITE)) {
8022 			IPFERROR(101);
8023 			error = EPERM;
8024 		} else {
8025 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
8026 					  1 - softc->ipf_active, 1);
8027 		}
8028 		break;
8029 
8030 	case SIOCSWAPA :
8031 		if (!(mode & FWRITE)) {
8032 			IPFERROR(102);
8033 			error = EPERM;
8034 		} else {
8035 			WRITE_ENTER(&softc->ipf_mutex);
8036 			error = BCOPYOUT(&softc->ipf_active, data,
8037 					 sizeof(softc->ipf_active));
8038 			if (error != 0) {
8039 				IPFERROR(103);
8040 				error = EFAULT;
8041 			} else {
8042 				softc->ipf_active = 1 - softc->ipf_active;
8043 			}
8044 			RWLOCK_EXIT(&softc->ipf_mutex);
8045 		}
8046 		break;
8047 
8048 	case SIOCGETFS :
8049 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8050 				  IPFOBJ_IPFSTAT);
8051 		if (error != 0)
8052 			break;
8053 		ipf_getstat(softc, &fio, obj.ipfo_rev);
8054 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8055 		break;
8056 
8057 	case SIOCFRZST :
8058 		if (!(mode & FWRITE)) {
8059 			IPFERROR(104);
8060 			error = EPERM;
8061 		} else
8062 			error = ipf_zerostats(softc, data);
8063 		break;
8064 
8065 	case SIOCIPFFL :
8066 		if (!(mode & FWRITE)) {
8067 			IPFERROR(105);
8068 			error = EPERM;
8069 		} else {
8070 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8071 			if (!error) {
8072 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8073 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8074 				if (error != 0) {
8075 					IPFERROR(106);
8076 					error = EFAULT;
8077 				}
8078 			} else {
8079 				IPFERROR(107);
8080 				error = EFAULT;
8081 			}
8082 		}
8083 		break;
8084 
8085 #ifdef USE_INET6
8086 	case SIOCIPFL6 :
8087 		if (!(mode & FWRITE)) {
8088 			IPFERROR(108);
8089 			error = EPERM;
8090 		} else {
8091 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8092 			if (!error) {
8093 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8094 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8095 				if (error != 0) {
8096 					IPFERROR(109);
8097 					error = EFAULT;
8098 				}
8099 			} else {
8100 				IPFERROR(110);
8101 				error = EFAULT;
8102 			}
8103 		}
8104 		break;
8105 #endif
8106 
8107 	case SIOCSTLCK :
8108 		if (!(mode & FWRITE)) {
8109 			IPFERROR(122);
8110 			error = EPERM;
8111 		} else {
8112 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8113 			if (error == 0) {
8114 				ipf_state_setlock(softc->ipf_state_soft, tmp);
8115 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8116 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8117 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8118 			} else {
8119 				IPFERROR(111);
8120 				error = EFAULT;
8121 			}
8122 		}
8123 		break;
8124 
8125 #ifdef	IPFILTER_LOG
8126 	case SIOCIPFFB :
8127 		if (!(mode & FWRITE)) {
8128 			IPFERROR(112);
8129 			error = EPERM;
8130 		} else {
8131 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8132 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8133 			if (error) {
8134 				IPFERROR(113);
8135 				error = EFAULT;
8136 			}
8137 		}
8138 		break;
8139 #endif /* IPFILTER_LOG */
8140 
8141 	case SIOCFRSYN :
8142 		if (!(mode & FWRITE)) {
8143 			IPFERROR(114);
8144 			error = EPERM;
8145 		} else {
8146 			WRITE_ENTER(&softc->ipf_global);
8147 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8148 			error = ipfsync();
8149 #else
8150 			ipf_sync(softc, NULL);
8151 			error = 0;
8152 #endif
8153 			RWLOCK_EXIT(&softc->ipf_global);
8154 
8155 		}
8156 		break;
8157 
8158 	case SIOCGFRST :
8159 		error = ipf_outobj(softc, (void *)data,
8160 				   ipf_frag_stats(softc->ipf_frag_soft),
8161 				   IPFOBJ_FRAGSTAT);
8162 		break;
8163 
8164 #ifdef	IPFILTER_LOG
8165 	case FIONREAD :
8166 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8167 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8168 		break;
8169 #endif
8170 
8171 	case SIOCIPFITER :
8172 		SPL_SCHED(s);
8173 		error = ipf_frruleiter(softc, data, uid, ctx);
8174 		SPL_X(s);
8175 		break;
8176 
8177 	case SIOCGENITER :
8178 		SPL_SCHED(s);
8179 		error = ipf_genericiter(softc, data, uid, ctx);
8180 		SPL_X(s);
8181 		break;
8182 
8183 	case SIOCIPFDELTOK :
8184 		error = BCOPYIN(data, &tmp, sizeof(tmp));
8185 		if (error == 0) {
8186 			SPL_SCHED(s);
8187 			error = ipf_token_del(softc, tmp, uid, ctx);
8188 			SPL_X(s);
8189 		}
8190 		break;
8191 
8192 	default :
8193 		IPFERROR(115);
8194 		error = EINVAL;
8195 		break;
8196 	}
8197 
8198 	return error;
8199 }
8200 
8201 
8202 /* ------------------------------------------------------------------------ */
8203 /* Function:    ipf_decaps                                                  */
8204 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8205 /*                           flags indicating packet filtering decision.    */
8206 /* Parameters:  fin(I)     - pointer to packet information                  */
8207 /*              pass(I)    - IP protocol version to match                   */
8208 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8209 /*                                                                          */
8210 /* This function is called for packets that are wrapt up in other packets,  */
8211 /* for example, an IP packet that is the entire data segment for another IP */
8212 /* packet.  If the basic constraints for this are satisfied, change the     */
8213 /* buffer to point to the start of the inner packet and start processing    */
8214 /* rules belonging to the head group this rule specifies.                   */
8215 /* ------------------------------------------------------------------------ */
8216 u_32_t
ipf_decaps(fr_info_t * fin,u_32_t pass,int l5proto)8217 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8218 {
8219 	fr_info_t fin2, *fino = NULL;
8220 	int elen, hlen, nh;
8221 	grehdr_t gre;
8222 	ip_t *ip;
8223 	mb_t *m;
8224 
8225 	if ((fin->fin_flx & FI_COALESCE) == 0)
8226 		if (ipf_coalesce(fin) == -1)
8227 			goto cantdecaps;
8228 
8229 	m = fin->fin_m;
8230 	hlen = fin->fin_hlen;
8231 
8232 	switch (fin->fin_p)
8233 	{
8234 	case IPPROTO_UDP :
8235 		/*
8236 		 * In this case, the specific protocol being decapsulated
8237 		 * inside UDP frames comes from the rule.
8238 		 */
8239 		nh = fin->fin_fr->fr_icode;
8240 		break;
8241 
8242 	case IPPROTO_GRE :	/* 47 */
8243 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8244 		hlen += sizeof(grehdr_t);
8245 		if (gre.gr_R|gre.gr_s)
8246 			goto cantdecaps;
8247 		if (gre.gr_C)
8248 			hlen += 4;
8249 		if (gre.gr_K)
8250 			hlen += 4;
8251 		if (gre.gr_S)
8252 			hlen += 4;
8253 
8254 		nh = IPPROTO_IP;
8255 
8256 		/*
8257 		 * If the routing options flag is set, validate that it is
8258 		 * there and bounce over it.
8259 		 */
8260 #if 0
8261 		/* This is really heavy weight and lots of room for error, */
8262 		/* so for now, put it off and get the simple stuff right.  */
8263 		if (gre.gr_R) {
8264 			u_char off, len, *s;
8265 			u_short af;
8266 			int end;
8267 
8268 			end = 0;
8269 			s = fin->fin_dp;
8270 			s += hlen;
8271 			aplen = fin->fin_plen - hlen;
8272 			while (aplen > 3) {
8273 				af = (s[0] << 8) | s[1];
8274 				off = s[2];
8275 				len = s[3];
8276 				aplen -= 4;
8277 				s += 4;
8278 				if (af == 0 && len == 0) {
8279 					end = 1;
8280 					break;
8281 				}
8282 				if (aplen < len)
8283 					break;
8284 				s += len;
8285 				aplen -= len;
8286 			}
8287 			if (end != 1)
8288 				goto cantdecaps;
8289 			hlen = s - (u_char *)fin->fin_dp;
8290 		}
8291 #endif
8292 		break;
8293 
8294 #ifdef IPPROTO_IPIP
8295 	case IPPROTO_IPIP :	/* 4 */
8296 #endif
8297 		nh = IPPROTO_IP;
8298 		break;
8299 
8300 	default :	/* Includes ESP, AH is special for IPv4 */
8301 		goto cantdecaps;
8302 	}
8303 
8304 	switch (nh)
8305 	{
8306 	case IPPROTO_IP :
8307 	case IPPROTO_IPV6 :
8308 		break;
8309 	default :
8310 		goto cantdecaps;
8311 	}
8312 
8313 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8314 	fino = fin;
8315 	fin = &fin2;
8316 	elen = hlen;
8317 #if defined(MENTAT) && defined(_KERNEL)
8318 	m->b_rptr += elen;
8319 #else
8320 	m->m_data += elen;
8321 	m->m_len -= elen;
8322 #endif
8323 	fin->fin_plen -= elen;
8324 
8325 	ip = (ip_t *)((char *)fin->fin_ip + elen);
8326 
8327 	/*
8328 	 * Make sure we have at least enough data for the network layer
8329 	 * header.
8330 	 */
8331 	if (IP_V(ip) == 4)
8332 		hlen = IP_HL(ip) << 2;
8333 #ifdef USE_INET6
8334 	else if (IP_V(ip) == 6)
8335 		hlen = sizeof(ip6_t);
8336 #endif
8337 	else
8338 		goto cantdecaps2;
8339 
8340 	if (fin->fin_plen < hlen)
8341 		goto cantdecaps2;
8342 
8343 	fin->fin_dp = (char *)ip + hlen;
8344 
8345 	if (IP_V(ip) == 4) {
8346 		/*
8347 		 * Perform IPv4 header checksum validation.
8348 		 */
8349 		if (ipf_cksum((u_short *)ip, hlen))
8350 			goto cantdecaps2;
8351 	}
8352 
8353 	if (ipf_makefrip(hlen, ip, fin) == -1) {
8354 cantdecaps2:
8355 		if (m != NULL) {
8356 #if defined(MENTAT) && defined(_KERNEL)
8357 			m->b_rptr -= elen;
8358 #else
8359 			m->m_data -= elen;
8360 			m->m_len += elen;
8361 #endif
8362 		}
8363 cantdecaps:
8364 		DT1(frb_decapfrip, fr_info_t *, fin);
8365 		pass &= ~FR_CMDMASK;
8366 		pass |= FR_BLOCK|FR_QUICK;
8367 		fin->fin_reason = FRB_DECAPFRIP;
8368 		return -1;
8369 	}
8370 
8371 	pass = ipf_scanlist(fin, pass);
8372 
8373 	/*
8374 	 * Copy the packet filter "result" fields out of the fr_info_t struct
8375 	 * that is local to the decapsulation processing and back into the
8376 	 * one we were called with.
8377 	 */
8378 	fino->fin_flx = fin->fin_flx;
8379 	fino->fin_rev = fin->fin_rev;
8380 	fino->fin_icode = fin->fin_icode;
8381 	fino->fin_rule = fin->fin_rule;
8382 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8383 	fino->fin_fr = fin->fin_fr;
8384 	fino->fin_error = fin->fin_error;
8385 	fino->fin_mp = fin->fin_mp;
8386 	fino->fin_m = fin->fin_m;
8387 	m = fin->fin_m;
8388 	if (m != NULL) {
8389 #if defined(MENTAT) && defined(_KERNEL)
8390 		m->b_rptr -= elen;
8391 #else
8392 		m->m_data -= elen;
8393 		m->m_len += elen;
8394 #endif
8395 	}
8396 	return pass;
8397 }
8398 
8399 
8400 /* ------------------------------------------------------------------------ */
8401 /* Function:    ipf_matcharray_load                                         */
8402 /* Returns:     int         - 0 = success, else error                       */
8403 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8404 /*              data(I)     - pointer to ioctl data                         */
8405 /*              objp(I)     - ipfobj_t structure to load data into          */
8406 /*              arrayptr(I) - pointer to location to store array pointer    */
8407 /*                                                                          */
8408 /* This function loads in a mathing array through the ipfobj_t struct that  */
8409 /* describes it.  Sanity checking and array size limitations are enforced   */
8410 /* in this function to prevent userspace from trying to load in something   */
8411 /* that is insanely big.  Once the size of the array is known, the memory   */
8412 /* required is malloc'd and returned through changing *arrayptr.  The       */
8413 /* contents of the array are verified before returning.  Only in the event  */
8414 /* of a successful call is the caller required to free up the malloc area.  */
8415 /* ------------------------------------------------------------------------ */
8416 int
ipf_matcharray_load(ipf_main_softc_t * softc,void * data,ipfobj_t * objp,int ** arrayptr)8417 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
8418     int **arrayptr)
8419 {
8420 	int arraysize, *array, error;
8421 
8422 	*arrayptr = NULL;
8423 
8424 	error = BCOPYIN(data, objp, sizeof(*objp));
8425 	if (error != 0) {
8426 		IPFERROR(116);
8427 		return EFAULT;
8428 	}
8429 
8430 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8431 		IPFERROR(117);
8432 		return EINVAL;
8433 	}
8434 
8435 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8436 	    (objp->ipfo_size > 1024)) {
8437 		IPFERROR(118);
8438 		return EINVAL;
8439 	}
8440 
8441 	arraysize = objp->ipfo_size * sizeof(*array);
8442 	KMALLOCS(array, int *, arraysize);
8443 	if (array == NULL) {
8444 		IPFERROR(119);
8445 		return ENOMEM;
8446 	}
8447 
8448 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8449 	if (error != 0) {
8450 		KFREES(array, arraysize);
8451 		IPFERROR(120);
8452 		return EFAULT;
8453 	}
8454 
8455 	if (ipf_matcharray_verify(array, arraysize) != 0) {
8456 		KFREES(array, arraysize);
8457 		IPFERROR(121);
8458 		return EINVAL;
8459 	}
8460 
8461 	*arrayptr = array;
8462 	return 0;
8463 }
8464 
8465 
8466 /* ------------------------------------------------------------------------ */
8467 /* Function:    ipf_matcharray_verify                                       */
8468 /* Returns:     Nil                                                         */
8469 /* Parameters:  array(I)     - pointer to matching array                    */
8470 /*              arraysize(I) - number of elements in the array              */
8471 /*                                                                          */
8472 /* Verify the contents of a matching array by stepping through each element */
8473 /* in it.  The actual commands in the array are not verified for            */
8474 /* correctness, only that all of the sizes are correctly within limits.     */
8475 /* ------------------------------------------------------------------------ */
8476 int
ipf_matcharray_verify(int * array,int arraysize)8477 ipf_matcharray_verify(int *array, int arraysize)
8478 {
8479 	int i, nelem, maxidx;
8480 	ipfexp_t *e;
8481 
8482 	nelem = arraysize / sizeof(*array);
8483 
8484 	/*
8485 	 * Currently, it makes no sense to have an array less than 6
8486 	 * elements long - the initial size at the from, a single operation
8487 	 * (minimum 4 in length) and a trailer, for a total of 6.
8488 	 */
8489 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8490 		return -1;
8491 	}
8492 
8493 	/*
8494 	 * Verify the size of data pointed to by array with how long
8495 	 * the array claims to be itself.
8496 	 */
8497 	if (array[0] * sizeof(*array) != arraysize) {
8498 		return -1;
8499 	}
8500 
8501 	maxidx = nelem - 1;
8502 	/*
8503 	 * The last opcode in this array should be an IPF_EXP_END.
8504 	 */
8505 	if (array[maxidx] != IPF_EXP_END) {
8506 		return -1;
8507 	}
8508 
8509 	for (i = 1; i < maxidx; ) {
8510 		e = (ipfexp_t *)(array + i);
8511 
8512 		/*
8513 		 * The length of the bits to check must be at least 1
8514 		 * (or else there is nothing to comapre with!) and it
8515 		 * cannot exceed the length of the data present.
8516 		 */
8517 		if ((e->ipfe_size < 1 ) ||
8518 		    (e->ipfe_size + i > maxidx)) {
8519 			return -1;
8520 		}
8521 		i += e->ipfe_size;
8522 	}
8523 	return 0;
8524 }
8525 
8526 
8527 /* ------------------------------------------------------------------------ */
8528 /* Function:    ipf_fr_matcharray                                           */
8529 /* Returns:     int      - 0 = match failed, else positive match            */
8530 /* Parameters:  fin(I)   - pointer to packet information                    */
8531 /*              array(I) - pointer to matching array                        */
8532 /*                                                                          */
8533 /* This function is used to apply a matching array against a packet and     */
8534 /* return an indication of whether or not the packet successfully matches   */
8535 /* all of the commands in it.                                               */
8536 /* ------------------------------------------------------------------------ */
8537 static int
ipf_fr_matcharray(fr_info_t * fin,int * array)8538 ipf_fr_matcharray(fr_info_t *fin, int *array)
8539 {
8540 	int i, n, *x, rv, p;
8541 	ipfexp_t *e;
8542 
8543 	rv = 0;
8544 	n = array[0];
8545 	x = array + 1;
8546 
8547 	for (; n > 0; x += 3 + x[3], rv = 0) {
8548 		e = (ipfexp_t *)x;
8549 		if (e->ipfe_cmd == IPF_EXP_END)
8550 			break;
8551 		n -= e->ipfe_size;
8552 
8553 		/*
8554 		 * The upper 16 bits currently store the protocol value.
8555 		 * This is currently used with TCP and UDP port compares and
8556 		 * allows "tcp.port = 80" without requiring an explicit
8557 		 " "ip.pr = tcp" first.
8558 		 */
8559 		p = e->ipfe_cmd >> 16;
8560 		if ((p != 0) && (p != fin->fin_p))
8561 			break;
8562 
8563 		switch (e->ipfe_cmd)
8564 		{
8565 		case IPF_EXP_IP_PR :
8566 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8567 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8568 			}
8569 			break;
8570 
8571 		case IPF_EXP_IP_SRCADDR :
8572 			if (fin->fin_v != 4)
8573 				break;
8574 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8575 				rv |= ((fin->fin_saddr &
8576 					e->ipfe_arg0[i * 2 + 1]) ==
8577 				       e->ipfe_arg0[i * 2]);
8578 			}
8579 			break;
8580 
8581 		case IPF_EXP_IP_DSTADDR :
8582 			if (fin->fin_v != 4)
8583 				break;
8584 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8585 				rv |= ((fin->fin_daddr &
8586 					e->ipfe_arg0[i * 2 + 1]) ==
8587 				       e->ipfe_arg0[i * 2]);
8588 			}
8589 			break;
8590 
8591 		case IPF_EXP_IP_ADDR :
8592 			if (fin->fin_v != 4)
8593 				break;
8594 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8595 				rv |= ((fin->fin_saddr &
8596 					e->ipfe_arg0[i * 2 + 1]) ==
8597 				       e->ipfe_arg0[i * 2]) ||
8598 				      ((fin->fin_daddr &
8599 					e->ipfe_arg0[i * 2 + 1]) ==
8600 				       e->ipfe_arg0[i * 2]);
8601 			}
8602 			break;
8603 
8604 #ifdef USE_INET6
8605 		case IPF_EXP_IP6_SRCADDR :
8606 			if (fin->fin_v != 6)
8607 				break;
8608 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8609 				rv |= IP6_MASKEQ(&fin->fin_src6,
8610 						 &e->ipfe_arg0[i * 8 + 4],
8611 						 &e->ipfe_arg0[i * 8]);
8612 			}
8613 			break;
8614 
8615 		case IPF_EXP_IP6_DSTADDR :
8616 			if (fin->fin_v != 6)
8617 				break;
8618 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8619 				rv |= IP6_MASKEQ(&fin->fin_dst6,
8620 						 &e->ipfe_arg0[i * 8 + 4],
8621 						 &e->ipfe_arg0[i * 8]);
8622 			}
8623 			break;
8624 
8625 		case IPF_EXP_IP6_ADDR :
8626 			if (fin->fin_v != 6)
8627 				break;
8628 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8629 				rv |= IP6_MASKEQ(&fin->fin_src6,
8630 						 &e->ipfe_arg0[i * 8 + 4],
8631 						 &e->ipfe_arg0[i * 8]) ||
8632 				      IP6_MASKEQ(&fin->fin_dst6,
8633 						 &e->ipfe_arg0[i * 8 + 4],
8634 						 &e->ipfe_arg0[i * 8]);
8635 			}
8636 			break;
8637 #endif
8638 
8639 		case IPF_EXP_UDP_PORT :
8640 		case IPF_EXP_TCP_PORT :
8641 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8642 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8643 				      (fin->fin_dport == e->ipfe_arg0[i]);
8644 			}
8645 			break;
8646 
8647 		case IPF_EXP_UDP_SPORT :
8648 		case IPF_EXP_TCP_SPORT :
8649 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8650 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8651 			}
8652 			break;
8653 
8654 		case IPF_EXP_UDP_DPORT :
8655 		case IPF_EXP_TCP_DPORT :
8656 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8657 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8658 			}
8659 			break;
8660 
8661 		case IPF_EXP_TCP_FLAGS :
8662 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8663 				rv |= ((fin->fin_tcpf &
8664 					e->ipfe_arg0[i * 2 + 1]) ==
8665 				       e->ipfe_arg0[i * 2]);
8666 			}
8667 			break;
8668 		}
8669 		rv ^= e->ipfe_not;
8670 
8671 		if (rv == 0)
8672 			break;
8673 	}
8674 
8675 	return rv;
8676 }
8677 
8678 
8679 /* ------------------------------------------------------------------------ */
8680 /* Function:    ipf_queueflush                                              */
8681 /* Returns:     int - number of entries flushed (0 = none)                  */
8682 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8683 /*              deletefn(I) - function to call to delete entry              */
8684 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8685 /*              userqs(I)   - top of the list of user defined timeouts      */
8686 /*                                                                          */
8687 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8688 /* need to try a bit harder to free up some space.  The algorithm used here */
8689 /* split into two parts but both halves have the same goal: to reduce the   */
8690 /* number of connections considered to be "active" to the low watermark.    */
8691 /* There are two steps in doing this:                                       */
8692 /* 1) Remove any TCP connections that are already considered to be "closed" */
8693 /*    but have not yet been removed from the state table.  The two states   */
8694 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8695 /*    candidates for this style of removal.  If freeing up entries in       */
8696 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8697 /*    we do not go on to step 2.                                            */
8698 /*                                                                          */
8699 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8700 /*    they are within the given window we are considering.  Where the       */
8701 /*    window starts and the steps taken to increase its size depend upon    */
8702 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8703 /*    last 30 seconds is not touched.                                       */
8704 /*                                              touched                     */
8705 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8706 /*           |          |        |           |     |     |                  */
8707 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8708 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8709 /*                                                                          */
8710 /* Points to note:                                                          */
8711 /* - tqe_die is the time, in the future, when entries die.                  */
8712 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8713 /*   ticks.                                                                 */
8714 /* - tqe_touched is when the entry was last used by NAT/state               */
8715 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8716 /*   ipf_ticks any given timeout queue and vice versa.                      */
8717 /* - both tqe_die and tqe_touched increase over time                        */
8718 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8719 /*   bottom and therefore the smallest values of each are at the top        */
8720 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8721 /*   queues representing each of the TCP states                             */
8722 /*                                                                          */
8723 /* We start by setting up a maximum range to scan for things to move of     */
8724 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8725 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8726 /* we start again with a new value for "iend" and "istart".  This is        */
8727 /* continued until we either finish the scan of 30 second intervals or the  */
8728 /* low water mark is reached.                                               */
8729 /* ------------------------------------------------------------------------ */
8730 int
ipf_queueflush(ipf_main_softc_t * softc,ipftq_delete_fn_t deletefn,ipftq_t * ipfqs,ipftq_t * userqs,u_int * activep,int size,int low)8731 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8732     ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8733 {
8734 	u_long interval, istart, iend;
8735 	ipftq_t *ifq, *ifqnext;
8736 	ipftqent_t *tqe, *tqn;
8737 	int removed = 0;
8738 
8739 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8740 		tqn = tqe->tqe_next;
8741 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8742 			removed++;
8743 	}
8744 	if ((*activep * 100 / size) > low) {
8745 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8746 		     ((tqe = tqn) != NULL); ) {
8747 			tqn = tqe->tqe_next;
8748 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8749 				removed++;
8750 		}
8751 	}
8752 
8753 	if ((*activep * 100 / size) <= low) {
8754 		return removed;
8755 	}
8756 
8757 	/*
8758 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8759 	 *       used then the operations are upgraded to floating point
8760 	 *       and kernels don't like floating point...
8761 	 */
8762 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8763 		istart = IPF_TTLVAL(86400 * 4);
8764 		interval = IPF_TTLVAL(43200);
8765 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8766 		istart = IPF_TTLVAL(43200);
8767 		interval = IPF_TTLVAL(1800);
8768 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8769 		istart = IPF_TTLVAL(1800);
8770 		interval = IPF_TTLVAL(30);
8771 	} else {
8772 		return 0;
8773 	}
8774 	if (istart > softc->ipf_ticks) {
8775 		if (softc->ipf_ticks - interval < interval)
8776 			istart = interval;
8777 		else
8778 			istart = (softc->ipf_ticks / interval) * interval;
8779 	}
8780 
8781 	iend = softc->ipf_ticks - interval;
8782 
8783 	while ((*activep * 100 / size) > low) {
8784 		u_long try;
8785 
8786 		try = softc->ipf_ticks - istart;
8787 
8788 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8789 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8790 				if (try < tqe->tqe_touched)
8791 					break;
8792 				tqn = tqe->tqe_next;
8793 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8794 					removed++;
8795 			}
8796 		}
8797 
8798 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8799 			ifqnext = ifq->ifq_next;
8800 
8801 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8802 				if (try < tqe->tqe_touched)
8803 					break;
8804 				tqn = tqe->tqe_next;
8805 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8806 					removed++;
8807 			}
8808 		}
8809 
8810 		if (try >= iend) {
8811 			if (interval == IPF_TTLVAL(43200)) {
8812 				interval = IPF_TTLVAL(1800);
8813 			} else if (interval == IPF_TTLVAL(1800)) {
8814 				interval = IPF_TTLVAL(30);
8815 			} else {
8816 				break;
8817 			}
8818 			if (interval >= softc->ipf_ticks)
8819 				break;
8820 
8821 			iend = softc->ipf_ticks - interval;
8822 		}
8823 		istart -= interval;
8824 	}
8825 
8826 	return removed;
8827 }
8828 
8829 
8830 /* ------------------------------------------------------------------------ */
8831 /* Function:    ipf_deliverlocal                                            */
8832 /* Returns:     int - 1 = local address, 0 = non-local address              */
8833 /* Parameters:  softc(I)     - pointer to soft context main structure       */
8834 /*              ipversion(I) - IP protocol version (4 or 6)                 */
8835 /*              ifp(I)       - network interface pointer                    */
8836 /*              ipaddr(I)    - IPv4/6 destination address                   */
8837 /*                                                                          */
8838 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
8839 /* the network interface represented by ifp.                                */
8840 /* ------------------------------------------------------------------------ */
8841 int
ipf_deliverlocal(ipf_main_softc_t * softc,int ipversion,void * ifp,i6addr_t * ipaddr)8842 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8843     i6addr_t *ipaddr)
8844 {
8845 	i6addr_t addr;
8846 	int islocal = 0;
8847 
8848 	if (ipversion == 4) {
8849 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8850 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
8851 				islocal = 1;
8852 		}
8853 
8854 #ifdef USE_INET6
8855 	} else if (ipversion == 6) {
8856 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8857 			if (IP6_EQ(&addr, ipaddr))
8858 				islocal = 1;
8859 		}
8860 #endif
8861 	}
8862 
8863 	return islocal;
8864 }
8865 
8866 
8867 /* ------------------------------------------------------------------------ */
8868 /* Function:    ipf_settimeout                                              */
8869 /* Returns:     int - 0 = success, -1 = failure                             */
8870 /* Parameters:  softc(I) - pointer to soft context main structure           */
8871 /*              t(I)     - pointer to tuneable array entry                  */
8872 /*              p(I)     - pointer to values passed in to apply             */
8873 /*                                                                          */
8874 /* This function is called to set the timeout values for each distinct      */
8875 /* queue timeout that is available.  When called, it calls into both the    */
8876 /* state and NAT code, telling them to update their timeout queues.         */
8877 /* ------------------------------------------------------------------------ */
8878 static int
ipf_settimeout(struct ipf_main_softc_s * softc,ipftuneable_t * t,ipftuneval_t * p)8879 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8880     ipftuneval_t *p)
8881 {
8882 
8883 	/*
8884 	 * ipf_interror should be set by the functions called here, not
8885 	 * by this function - it's just a middle man.
8886 	 */
8887 	if (ipf_state_settimeout(softc, t, p) == -1)
8888 		return -1;
8889 	if (ipf_nat_settimeout(softc, t, p) == -1)
8890 		return -1;
8891 	return 0;
8892 }
8893 
8894 
8895 /* ------------------------------------------------------------------------ */
8896 /* Function:    ipf_apply_timeout                                           */
8897 /* Returns:     int - 0 = success, -1 = failure                             */
8898 /* Parameters:  head(I)    - pointer to tuneable array entry                */
8899 /*              seconds(I) - pointer to values passed in to apply           */
8900 /*                                                                          */
8901 /* This function applies a timeout of "seconds" to the timeout queue that   */
8902 /* is pointed to by "head".  All entries on this list have an expiration    */
8903 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
8904 /* function should only be called when the delta is non-zero, the task is   */
8905 /* to walk the entire list and apply the change.  The sort order will not   */
8906 /* change.  The only catch is that this is O(n) across the list, so if the  */
8907 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
8908 /* could take a relatively long time to work through them all.              */
8909 /* ------------------------------------------------------------------------ */
8910 void
ipf_apply_timeout(ipftq_t * head,u_int seconds)8911 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8912 {
8913 	u_int oldtimeout, newtimeout;
8914 	ipftqent_t *tqe;
8915 	int delta;
8916 
8917 	MUTEX_ENTER(&head->ifq_lock);
8918 	oldtimeout = head->ifq_ttl;
8919 	newtimeout = IPF_TTLVAL(seconds);
8920 	delta = oldtimeout - newtimeout;
8921 
8922 	head->ifq_ttl = newtimeout;
8923 
8924 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8925 		tqe->tqe_die += delta;
8926 	}
8927 	MUTEX_EXIT(&head->ifq_lock);
8928 }
8929 
8930 
8931 /* ------------------------------------------------------------------------ */
8932 /* Function:   ipf_settimeout_tcp                                           */
8933 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
8934 /* Parameters: t(I)   - pointer to tuneable to change                       */
8935 /*             p(I)   - pointer to new timeout information                  */
8936 /*             tab(I) - pointer to table of TCP queues                      */
8937 /*                                                                          */
8938 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
8939 /* updates all of the entries on the relevant timeout queue by calling      */
8940 /* ipf_apply_timeout().                                                     */
8941 /* ------------------------------------------------------------------------ */
8942 int
ipf_settimeout_tcp(ipftuneable_t * t,ipftuneval_t * p,ipftq_t * tab)8943 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8944 {
8945 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8946 	    !strcmp(t->ipft_name, "tcp_established")) {
8947 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8948 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8949 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8950 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8951 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8952 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8953 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8954 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8955 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8956 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
8957 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8958 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8959 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8960 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
8961 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8962 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8963 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8964 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
8965 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
8966 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
8967 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8968 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
8969 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8970 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
8971 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
8972 	} else {
8973 		/*
8974 		 * ipf_interror isn't set here because it should be set
8975 		 * by whatever called this function.
8976 		 */
8977 		return -1;
8978 	}
8979 	return 0;
8980 }
8981 
8982 
8983 /* ------------------------------------------------------------------------ */
8984 /* Function:   ipf_main_soft_create                                         */
8985 /* Returns:    NULL = failure, else success                                 */
8986 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
8987 /*                                                                          */
8988 /* Create the foundation soft context structure. In circumstances where it  */
8989 /* is not required to dynamically allocate the context, a pointer can be    */
8990 /* passed in (rather than NULL) to a structure to be initialised.           */
8991 /* The main thing of interest is that a number of locks are initialised     */
8992 /* here instead of in the where might be expected - in the relevant create  */
8993 /* function elsewhere.  This is done because the current locking design has */
8994 /* some areas where these locks are used outside of their module.           */
8995 /* Possibly the most important exercise that is done here is setting of all */
8996 /* the timeout values, allowing them to be changed before init().           */
8997 /* ------------------------------------------------------------------------ */
8998 void *
ipf_main_soft_create(void * arg)8999 ipf_main_soft_create(void *arg)
9000 {
9001 	ipf_main_softc_t *softc;
9002 
9003 	if (arg == NULL) {
9004 		KMALLOC(softc, ipf_main_softc_t *);
9005 		if (softc == NULL)
9006 			return NULL;
9007 	} else {
9008 		softc = arg;
9009 	}
9010 
9011 	bzero((char *)softc, sizeof(*softc));
9012 
9013 	/*
9014 	 * This serves as a flag as to whether or not the softc should be
9015 	 * free'd when _destroy is called.
9016 	 */
9017 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9018 
9019 	softc->ipf_tuners = ipf_tune_array_copy(softc,
9020 						sizeof(ipf_main_tuneables),
9021 						ipf_main_tuneables);
9022 	if (softc->ipf_tuners == NULL) {
9023 		ipf_main_soft_destroy(softc);
9024 		return NULL;
9025 	}
9026 
9027 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9028 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9029 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9030 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9031 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9032 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9033 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9034 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9035 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9036 
9037 	softc->ipf_token_head = NULL;
9038 	softc->ipf_token_tail = &softc->ipf_token_head;
9039 
9040 	softc->ipf_tcpidletimeout = FIVE_DAYS;
9041 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9042 	softc->ipf_tcplastack = IPF_TTLVAL(30);
9043 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9044 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9045 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9046 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9047 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9048 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9049 	softc->ipf_udptimeout = IPF_TTLVAL(120);
9050 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9051 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9052 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9053 	softc->ipf_iptimeout = IPF_TTLVAL(60);
9054 
9055 #if defined(IPFILTER_DEFAULT_BLOCK)
9056 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9057 #else
9058 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9059 #endif
9060 	softc->ipf_minttl = 4;
9061 	softc->ipf_icmpminfragmtu = 68;
9062 	softc->ipf_flags = IPF_LOGGING;
9063 
9064 	return softc;
9065 }
9066 
9067 /* ------------------------------------------------------------------------ */
9068 /* Function:   ipf_main_soft_init                                           */
9069 /* Returns:    0 = success, -1 = failure                                    */
9070 /* Parameters: softc(I) - pointer to soft context main structure            */
9071 /*                                                                          */
9072 /* A null-op function that exists as a placeholder so that the flow in      */
9073 /* other functions is obvious.                                              */
9074 /* ------------------------------------------------------------------------ */
9075 /*ARGSUSED*/
9076 int
ipf_main_soft_init(ipf_main_softc_t * softc)9077 ipf_main_soft_init(ipf_main_softc_t *softc)
9078 {
9079 	return 0;
9080 }
9081 
9082 
9083 /* ------------------------------------------------------------------------ */
9084 /* Function:   ipf_main_soft_destroy                                        */
9085 /* Returns:    void                                                         */
9086 /* Parameters: softc(I) - pointer to soft context main structure            */
9087 /*                                                                          */
9088 /* Undo everything that we did in ipf_main_soft_create.                     */
9089 /*                                                                          */
9090 /* The most important check that needs to be made here is whether or not    */
9091 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9092 /* value is stored in ipf_dynamic_main.                                     */
9093 /* ------------------------------------------------------------------------ */
9094 /*ARGSUSED*/
9095 void
ipf_main_soft_destroy(ipf_main_softc_t * softc)9096 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9097 {
9098 
9099 	RW_DESTROY(&softc->ipf_frag);
9100 	RW_DESTROY(&softc->ipf_poolrw);
9101 	RW_DESTROY(&softc->ipf_nat);
9102 	RW_DESTROY(&softc->ipf_state);
9103 	RW_DESTROY(&softc->ipf_tokens);
9104 	RW_DESTROY(&softc->ipf_mutex);
9105 	RW_DESTROY(&softc->ipf_global);
9106 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9107 	MUTEX_DESTROY(&softc->ipf_rw);
9108 
9109 	if (softc->ipf_tuners != NULL) {
9110 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9111 	}
9112 	if (softc->ipf_dynamic_softc == 1) {
9113 		KFREE(softc);
9114 	}
9115 }
9116 
9117 
9118 /* ------------------------------------------------------------------------ */
9119 /* Function:   ipf_main_soft_fini                                           */
9120 /* Returns:    0 = success, -1 = failure                                    */
9121 /* Parameters: softc(I) - pointer to soft context main structure            */
9122 /*                                                                          */
9123 /* Clean out the rules which have been added since _init was last called,   */
9124 /* the only dynamic part of the mainline.                                   */
9125 /* ------------------------------------------------------------------------ */
9126 int
ipf_main_soft_fini(ipf_main_softc_t * softc)9127 ipf_main_soft_fini(ipf_main_softc_t *softc)
9128 {
9129 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9130 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9131 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9132 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9133 
9134 	return 0;
9135 }
9136 
9137 
9138 /* ------------------------------------------------------------------------ */
9139 /* Function:   ipf_main_load                                                */
9140 /* Returns:    0 = success, -1 = failure                                    */
9141 /* Parameters: none                                                         */
9142 /*                                                                          */
9143 /* Handle global initialisation that needs to be done for the base part of  */
9144 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9145 /* arrays that get used by the state/NAT code.                              */
9146 /* ------------------------------------------------------------------------ */
9147 int
ipf_main_load(void)9148 ipf_main_load(void)
9149 {
9150 	int i;
9151 
9152 	/* fill icmp reply type table */
9153 	for (i = 0; i <= ICMP_MAXTYPE; i++)
9154 		icmpreplytype4[i] = -1;
9155 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9156 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9157 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9158 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9159 
9160 #ifdef  USE_INET6
9161 	/* fill icmp reply type table */
9162 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9163 		icmpreplytype6[i] = -1;
9164 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9165 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9166 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9167 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9168 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9169 #endif
9170 
9171 	return 0;
9172 }
9173 
9174 
9175 /* ------------------------------------------------------------------------ */
9176 /* Function:   ipf_main_unload                                              */
9177 /* Returns:    0 = success, -1 = failure                                    */
9178 /* Parameters: none                                                         */
9179 /*                                                                          */
9180 /* A null-op function that exists as a placeholder so that the flow in      */
9181 /* other functions is obvious.                                              */
9182 /* ------------------------------------------------------------------------ */
9183 int
ipf_main_unload(void)9184 ipf_main_unload(void)
9185 {
9186 	return 0;
9187 }
9188 
9189 
9190 /* ------------------------------------------------------------------------ */
9191 /* Function:   ipf_load_all                                                 */
9192 /* Returns:    0 = success, -1 = failure                                    */
9193 /* Parameters: none                                                         */
9194 /*                                                                          */
9195 /* Work through all of the subsystems inside IPFilter and call the load     */
9196 /* function for each in an order that won't lead to a crash :)              */
9197 /* ------------------------------------------------------------------------ */
9198 int
ipf_load_all(void)9199 ipf_load_all(void)
9200 {
9201 	if (ipf_main_load() == -1)
9202 		return -1;
9203 
9204 	if (ipf_state_main_load() == -1)
9205 		return -1;
9206 
9207 	if (ipf_nat_main_load() == -1)
9208 		return -1;
9209 
9210 	if (ipf_frag_main_load() == -1)
9211 		return -1;
9212 
9213 	if (ipf_auth_main_load() == -1)
9214 		return -1;
9215 
9216 	if (ipf_proxy_main_load() == -1)
9217 		return -1;
9218 
9219 	return 0;
9220 }
9221 
9222 
9223 /* ------------------------------------------------------------------------ */
9224 /* Function:   ipf_unload_all                                               */
9225 /* Returns:    0 = success, -1 = failure                                    */
9226 /* Parameters: none                                                         */
9227 /*                                                                          */
9228 /* Work through all of the subsystems inside IPFilter and call the unload   */
9229 /* function for each in an order that won't lead to a crash :)              */
9230 /* ------------------------------------------------------------------------ */
9231 int
ipf_unload_all(void)9232 ipf_unload_all(void)
9233 {
9234 	if (ipf_proxy_main_unload() == -1)
9235 		return -1;
9236 
9237 	if (ipf_auth_main_unload() == -1)
9238 		return -1;
9239 
9240 	if (ipf_frag_main_unload() == -1)
9241 		return -1;
9242 
9243 	if (ipf_nat_main_unload() == -1)
9244 		return -1;
9245 
9246 	if (ipf_state_main_unload() == -1)
9247 		return -1;
9248 
9249 	if (ipf_main_unload() == -1)
9250 		return -1;
9251 
9252 	return 0;
9253 }
9254 
9255 
9256 /* ------------------------------------------------------------------------ */
9257 /* Function:   ipf_create_all                                               */
9258 /* Returns:    NULL = failure, else success                                 */
9259 /* Parameters: arg(I) - pointer to soft context main structure              */
9260 /*                                                                          */
9261 /* Work through all of the subsystems inside IPFilter and call the create   */
9262 /* function for each in an order that won't lead to a crash :)              */
9263 /* ------------------------------------------------------------------------ */
9264 ipf_main_softc_t *
ipf_create_all(void * arg)9265 ipf_create_all(void *arg)
9266 {
9267 	ipf_main_softc_t *softc;
9268 
9269 	softc = ipf_main_soft_create(arg);
9270 	if (softc == NULL)
9271 		return NULL;
9272 
9273 #ifdef IPFILTER_LOG
9274 	softc->ipf_log_soft = ipf_log_soft_create(softc);
9275 	if (softc->ipf_log_soft == NULL) {
9276 		ipf_destroy_all(softc);
9277 		return NULL;
9278 	}
9279 #endif
9280 
9281 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9282 	if (softc->ipf_lookup_soft == NULL) {
9283 		ipf_destroy_all(softc);
9284 		return NULL;
9285 	}
9286 
9287 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9288 	if (softc->ipf_sync_soft == NULL) {
9289 		ipf_destroy_all(softc);
9290 		return NULL;
9291 	}
9292 
9293 	softc->ipf_state_soft = ipf_state_soft_create(softc);
9294 	if (softc->ipf_state_soft == NULL) {
9295 		ipf_destroy_all(softc);
9296 		return NULL;
9297 	}
9298 
9299 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9300 	if (softc->ipf_nat_soft == NULL) {
9301 		ipf_destroy_all(softc);
9302 		return NULL;
9303 	}
9304 
9305 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9306 	if (softc->ipf_frag_soft == NULL) {
9307 		ipf_destroy_all(softc);
9308 		return NULL;
9309 	}
9310 
9311 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9312 	if (softc->ipf_auth_soft == NULL) {
9313 		ipf_destroy_all(softc);
9314 		return NULL;
9315 	}
9316 
9317 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9318 	if (softc->ipf_proxy_soft == NULL) {
9319 		ipf_destroy_all(softc);
9320 		return NULL;
9321 	}
9322 
9323 	return softc;
9324 }
9325 
9326 
9327 /* ------------------------------------------------------------------------ */
9328 /* Function:   ipf_destroy_all                                              */
9329 /* Returns:    void                                                         */
9330 /* Parameters: softc(I) - pointer to soft context main structure            */
9331 /*                                                                          */
9332 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9333 /* function for each in an order that won't lead to a crash :)              */
9334 /*                                                                          */
9335 /* Every one of these functions is expected to succeed, so there is no      */
9336 /* checking of return values.                                               */
9337 /* ------------------------------------------------------------------------ */
9338 void
ipf_destroy_all(ipf_main_softc_t * softc)9339 ipf_destroy_all(ipf_main_softc_t *softc)
9340 {
9341 
9342 	if (softc->ipf_state_soft != NULL) {
9343 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9344 		softc->ipf_state_soft = NULL;
9345 	}
9346 
9347 	if (softc->ipf_nat_soft != NULL) {
9348 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9349 		softc->ipf_nat_soft = NULL;
9350 	}
9351 
9352 	if (softc->ipf_frag_soft != NULL) {
9353 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9354 		softc->ipf_frag_soft = NULL;
9355 	}
9356 
9357 	if (softc->ipf_auth_soft != NULL) {
9358 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9359 		softc->ipf_auth_soft = NULL;
9360 	}
9361 
9362 	if (softc->ipf_proxy_soft != NULL) {
9363 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9364 		softc->ipf_proxy_soft = NULL;
9365 	}
9366 
9367 	if (softc->ipf_sync_soft != NULL) {
9368 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9369 		softc->ipf_sync_soft = NULL;
9370 	}
9371 
9372 	if (softc->ipf_lookup_soft != NULL) {
9373 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9374 		softc->ipf_lookup_soft = NULL;
9375 	}
9376 
9377 #ifdef IPFILTER_LOG
9378 	if (softc->ipf_log_soft != NULL) {
9379 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9380 		softc->ipf_log_soft = NULL;
9381 	}
9382 #endif
9383 
9384 	ipf_main_soft_destroy(softc);
9385 }
9386 
9387 
9388 /* ------------------------------------------------------------------------ */
9389 /* Function:   ipf_init_all                                                 */
9390 /* Returns:    0 = success, -1 = failure                                    */
9391 /* Parameters: softc(I) - pointer to soft context main structure            */
9392 /*                                                                          */
9393 /* Work through all of the subsystems inside IPFilter and call the init     */
9394 /* function for each in an order that won't lead to a crash :)              */
9395 /* ------------------------------------------------------------------------ */
9396 int
ipf_init_all(ipf_main_softc_t * softc)9397 ipf_init_all(ipf_main_softc_t *softc)
9398 {
9399 
9400 	if (ipf_main_soft_init(softc) == -1)
9401 		return -1;
9402 
9403 #ifdef IPFILTER_LOG
9404 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9405 		return -1;
9406 #endif
9407 
9408 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9409 		return -1;
9410 
9411 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9412 		return -1;
9413 
9414 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9415 		return -1;
9416 
9417 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9418 		return -1;
9419 
9420 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9421 		return -1;
9422 
9423 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9424 		return -1;
9425 
9426 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9427 		return -1;
9428 
9429 	return 0;
9430 }
9431 
9432 
9433 /* ------------------------------------------------------------------------ */
9434 /* Function:   ipf_fini_all                                                 */
9435 /* Returns:    0 = success, -1 = failure                                    */
9436 /* Parameters: softc(I) - pointer to soft context main structure            */
9437 /*                                                                          */
9438 /* Work through all of the subsystems inside IPFilter and call the fini     */
9439 /* function for each in an order that won't lead to a crash :)              */
9440 /* ------------------------------------------------------------------------ */
9441 int
ipf_fini_all(ipf_main_softc_t * softc)9442 ipf_fini_all(ipf_main_softc_t *softc)
9443 {
9444 
9445 	ipf_token_flush(softc);
9446 
9447 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9448 		return -1;
9449 
9450 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9451 		return -1;
9452 
9453 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9454 		return -1;
9455 
9456 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9457 		return -1;
9458 
9459 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9460 		return -1;
9461 
9462 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9463 		return -1;
9464 
9465 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9466 		return -1;
9467 
9468 #ifdef IPFILTER_LOG
9469 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9470 		return -1;
9471 #endif
9472 
9473 	if (ipf_main_soft_fini(softc) == -1)
9474 		return -1;
9475 
9476 	return 0;
9477 }
9478 
9479 
9480 /* ------------------------------------------------------------------------ */
9481 /* Function:    ipf_rule_expire                                             */
9482 /* Returns:     Nil                                                         */
9483 /* Parameters:  softc(I) - pointer to soft context main structure           */
9484 /*                                                                          */
9485 /* At present this function exists just to support temporary addition of    */
9486 /* firewall rules. Both inactive and active lists are scanned for items to  */
9487 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9488 /* loaded in.                                                               */
9489 /* ------------------------------------------------------------------------ */
9490 void
ipf_rule_expire(ipf_main_softc_t * softc)9491 ipf_rule_expire(ipf_main_softc_t *softc)
9492 {
9493 	frentry_t *fr;
9494 
9495 	if ((softc->ipf_rule_explist[0] == NULL) &&
9496 	    (softc->ipf_rule_explist[1] == NULL))
9497 		return;
9498 
9499 	WRITE_ENTER(&softc->ipf_mutex);
9500 
9501 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9502 		/*
9503 		 * Because the list is kept sorted on insertion, the fist
9504 		 * one that dies in the future means no more work to do.
9505 		 */
9506 		if (fr->fr_die > softc->ipf_ticks)
9507 			break;
9508 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9509 	}
9510 
9511 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9512 		/*
9513 		 * Because the list is kept sorted on insertion, the fist
9514 		 * one that dies in the future means no more work to do.
9515 		 */
9516 		if (fr->fr_die > softc->ipf_ticks)
9517 			break;
9518 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9519 	}
9520 
9521 	RWLOCK_EXIT(&softc->ipf_mutex);
9522 }
9523 
9524 
9525 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
9526 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9527 				 i6addr_t *);
9528 
RBI_CODE(ipf_rb,host_node_t,hn_entry,ipf_ht_node_cmp)9529 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9530 
9531 
9532 /* ------------------------------------------------------------------------ */
9533 /* Function:    ipf_ht_node_cmp                                             */
9534 /* Returns:     int   - 0 == nodes are the same, ..                         */
9535 /* Parameters:  k1(I) - pointer to first key to compare                     */
9536 /*              k2(I) - pointer to second key to compare                    */
9537 /*                                                                          */
9538 /* The "key" for the node is a combination of two fields: the address       */
9539 /* family and the address itself.                                           */
9540 /*                                                                          */
9541 /* Because we're not actually interpreting the address data, it isn't       */
9542 /* necessary to convert them to/from network/host byte order. The mask is   */
9543 /* just used to remove bits that aren't significant - it doesn't matter     */
9544 /* where they are, as long as they're always in the same place.             */
9545 /*                                                                          */
9546 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9547 /* this is where individual ones will differ the most - but not true for    */
9548 /* for /48's, etc.                                                          */
9549 /* ------------------------------------------------------------------------ */
9550 static int
9551 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
9552 {
9553 	int i;
9554 
9555 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9556 	if (i != 0)
9557 		return i;
9558 
9559 	if (k1->hn_addr.adf_family == AF_INET)
9560 		return (k2->hn_addr.adf_addr.in4.s_addr -
9561 			k1->hn_addr.adf_addr.in4.s_addr);
9562 
9563 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9564 	if (i != 0)
9565 		return i;
9566 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9567 	if (i != 0)
9568 		return i;
9569 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9570 	if (i != 0)
9571 		return i;
9572 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9573 	return i;
9574 }
9575 
9576 
9577 /* ------------------------------------------------------------------------ */
9578 /* Function:    ipf_ht_node_make_key                                        */
9579 /* Returns:     Nil                                                         */
9580 /* parameters:  htp(I)    - pointer to address tracking structure           */
9581 /*              key(I)    - where to store masked address for lookup        */
9582 /*              family(I) - protocol family of address                      */
9583 /*              addr(I)   - pointer to network address                      */
9584 /*                                                                          */
9585 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9586 /* copy the address passed in into the key structure whilst masking out the */
9587 /* bits that we don't want.                                                 */
9588 /*                                                                          */
9589 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9590 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9591 /* have to be wary of that and not allow 32-128 to happen.                  */
9592 /* ------------------------------------------------------------------------ */
9593 static void
ipf_ht_node_make_key(host_track_t * htp,host_node_t * key,int family,i6addr_t * addr)9594 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9595     i6addr_t *addr)
9596 {
9597 	key->hn_addr.adf_family = family;
9598 	if (family == AF_INET) {
9599 		u_32_t mask;
9600 		int bits;
9601 
9602 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9603 		bits = htp->ht_netmask;
9604 		if (bits >= 32) {
9605 			mask = 0xffffffff;
9606 		} else {
9607 			mask = htonl(0xffffffff << (32 - bits));
9608 		}
9609 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9610 #ifdef USE_INET6
9611 	} else {
9612 		int bits = htp->ht_netmask;
9613 
9614 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9615 		if (bits > 96) {
9616 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9617 					     htonl(0xffffffff << (128 - bits));
9618 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9619 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9620 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9621 		} else if (bits > 64) {
9622 			key->hn_addr.adf_addr.i6[3] = 0;
9623 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9624 					     htonl(0xffffffff << (96 - bits));
9625 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9626 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9627 		} else if (bits > 32) {
9628 			key->hn_addr.adf_addr.i6[3] = 0;
9629 			key->hn_addr.adf_addr.i6[2] = 0;
9630 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9631 					     htonl(0xffffffff << (64 - bits));
9632 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9633 		} else {
9634 			key->hn_addr.adf_addr.i6[3] = 0;
9635 			key->hn_addr.adf_addr.i6[2] = 0;
9636 			key->hn_addr.adf_addr.i6[1] = 0;
9637 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9638 					     htonl(0xffffffff << (32 - bits));
9639 		}
9640 #endif
9641 	}
9642 }
9643 
9644 
9645 /* ------------------------------------------------------------------------ */
9646 /* Function:    ipf_ht_node_add                                             */
9647 /* Returns:     int       - 0 == success,  -1 == failure                    */
9648 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9649 /*              htp(I)    - pointer to address tracking structure           */
9650 /*              family(I) - protocol family of address                      */
9651 /*              addr(I)   - pointer to network address                      */
9652 /*                                                                          */
9653 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9654 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9655 /*                                                                          */
9656 /* After preparing the key with the address information to find, look in    */
9657 /* the red-black tree to see if the address is known. A successful call to  */
9658 /* this function can mean one of two things: a new node was added to the    */
9659 /* tree or a matching node exists and we're able to bump up its activity.   */
9660 /* ------------------------------------------------------------------------ */
9661 int
ipf_ht_node_add(ipf_main_softc_t * softc,host_track_t * htp,int family,i6addr_t * addr)9662 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9663     i6addr_t *addr)
9664 {
9665 	host_node_t *h;
9666 	host_node_t k;
9667 
9668 	ipf_ht_node_make_key(htp, &k, family, addr);
9669 
9670 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9671 	if (h == NULL) {
9672 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9673 			return -1;
9674 		KMALLOC(h, host_node_t *);
9675 		if (h == NULL) {
9676 			DT(ipf_rb_no_mem);
9677 			LBUMP(ipf_rb_no_mem);
9678 			return -1;
9679 		}
9680 
9681 		/*
9682 		 * If there was a macro to initialise the RB node then that
9683 		 * would get used here, but there isn't...
9684 		 */
9685 		bzero((char *)h, sizeof(*h));
9686 		h->hn_addr = k.hn_addr;
9687 		h->hn_addr.adf_family = k.hn_addr.adf_family;
9688 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9689 		htp->ht_cur_nodes++;
9690 	} else {
9691 		if ((htp->ht_max_per_node != 0) &&
9692 		    (h->hn_active >= htp->ht_max_per_node)) {
9693 			DT(ipf_rb_node_max);
9694 			LBUMP(ipf_rb_node_max);
9695 			return -1;
9696 		}
9697 	}
9698 
9699 	h->hn_active++;
9700 
9701 	return 0;
9702 }
9703 
9704 
9705 /* ------------------------------------------------------------------------ */
9706 /* Function:    ipf_ht_node_del                                             */
9707 /* Returns:     int       - 0 == success,  -1 == failure                    */
9708 /* parameters:  htp(I)    - pointer to address tracking structure           */
9709 /*              family(I) - protocol family of address                      */
9710 /*              addr(I)   - pointer to network address                      */
9711 /*                                                                          */
9712 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9713 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9714 /*                                                                          */
9715 /* Try and find the address passed in amongst the leaves on this tree to    */
9716 /* be friend. If found then drop the active account for that node drops by  */
9717 /* one. If that count reaches 0, it is time to free it all up.              */
9718 /* ------------------------------------------------------------------------ */
9719 int
ipf_ht_node_del(host_track_t * htp,int family,i6addr_t * addr)9720 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9721 {
9722 	host_node_t *h;
9723 	host_node_t k;
9724 
9725 	ipf_ht_node_make_key(htp, &k, family, addr);
9726 
9727 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9728 	if (h == NULL) {
9729 		return -1;
9730 	} else {
9731 		h->hn_active--;
9732 		if (h->hn_active == 0) {
9733 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9734 			htp->ht_cur_nodes--;
9735 			KFREE(h);
9736 		}
9737 	}
9738 
9739 	return 0;
9740 }
9741 
9742 
9743 /* ------------------------------------------------------------------------ */
9744 /* Function:    ipf_rb_ht_init                                              */
9745 /* Returns:     Nil                                                         */
9746 /* Parameters:  head(I) - pointer to host tracking structure                */
9747 /*                                                                          */
9748 /* Initialise the host tracking structure to be ready for use above.        */
9749 /* ------------------------------------------------------------------------ */
9750 void
ipf_rb_ht_init(host_track_t * head)9751 ipf_rb_ht_init(host_track_t *head)
9752 {
9753 	memset(head, 0, sizeof(*head));
9754 	RBI_INIT(ipf_rb, &head->ht_root);
9755 }
9756 
9757 
9758 /* ------------------------------------------------------------------------ */
9759 /* Function:    ipf_rb_ht_freenode                                          */
9760 /* Returns:     Nil                                                         */
9761 /* Parameters:  head(I) - pointer to host tracking structure                */
9762 /*              arg(I)  - additional argument from walk caller              */
9763 /*                                                                          */
9764 /* Free an actual host_node_t structure.                                    */
9765 /* ------------------------------------------------------------------------ */
9766 void
ipf_rb_ht_freenode(host_node_t * node,void * arg)9767 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9768 {
9769 	KFREE(node);
9770 }
9771 
9772 
9773 /* ------------------------------------------------------------------------ */
9774 /* Function:    ipf_rb_ht_flush                                             */
9775 /* Returns:     Nil                                                         */
9776 /* Parameters:  head(I) - pointer to host tracking structure                */
9777 /*                                                                          */
9778 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
9779 /* and free'ing each one.                                                   */
9780 /* ------------------------------------------------------------------------ */
9781 void
ipf_rb_ht_flush(host_track_t * head)9782 ipf_rb_ht_flush(host_track_t *head)
9783 {
9784 	/* XXX - May use node members after freeing the node. */
9785 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9786 }
9787 
9788 
9789 /* ------------------------------------------------------------------------ */
9790 /* Function:    ipf_slowtimer                                               */
9791 /* Returns:     Nil                                                         */
9792 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
9793 /*                                                                          */
9794 /* Slowly expire held state for fragments.  Timeouts are set * in           */
9795 /* expectation of this being called twice per second.                       */
9796 /* ------------------------------------------------------------------------ */
9797 void
ipf_slowtimer(ipf_main_softc_t * softc)9798 ipf_slowtimer(ipf_main_softc_t *softc)
9799 {
9800 
9801 	ipf_token_expire(softc);
9802 	ipf_frag_expire(softc);
9803 	ipf_state_expire(softc);
9804 	ipf_nat_expire(softc);
9805 	ipf_auth_expire(softc);
9806 	ipf_lookup_expire(softc);
9807 	ipf_rule_expire(softc);
9808 	ipf_sync_expire(softc);
9809 	softc->ipf_ticks++;
9810 #   if defined(__OpenBSD__)
9811 	timeout_add(&ipf_slowtimer_ch, hz/2);
9812 #   endif
9813 }
9814 
9815 
9816 /* ------------------------------------------------------------------------ */
9817 /* Function:    ipf_inet_mask_add                                           */
9818 /* Returns:     Nil                                                         */
9819 /* Parameters:  bits(I) - pointer to nat context information                */
9820 /*              mtab(I) - pointer to mask hash table structure              */
9821 /*                                                                          */
9822 /* When called, bits represents the mask of a new NAT rule that has just    */
9823 /* been added. This function inserts a bitmask into the array of masks to   */
9824 /* search when searching for a matching NAT rule for a packet.              */
9825 /* Prevention of duplicate masks is achieved by checking the use count for  */
9826 /* a given netmask.                                                         */
9827 /* ------------------------------------------------------------------------ */
9828 void
ipf_inet_mask_add(int bits,ipf_v4_masktab_t * mtab)9829 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9830 {
9831 	u_32_t mask;
9832 	int i, j;
9833 
9834 	mtab->imt4_masks[bits]++;
9835 	if (mtab->imt4_masks[bits] > 1)
9836 		return;
9837 
9838 	if (bits == 0)
9839 		mask = 0;
9840 	else
9841 		mask = 0xffffffff << (32 - bits);
9842 
9843 	for (i = 0; i < 33; i++) {
9844 		if (ntohl(mtab->imt4_active[i]) < mask) {
9845 			for (j = 32; j > i; j--)
9846 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9847 			mtab->imt4_active[i] = htonl(mask);
9848 			break;
9849 		}
9850 	}
9851 	mtab->imt4_max++;
9852 }
9853 
9854 
9855 /* ------------------------------------------------------------------------ */
9856 /* Function:    ipf_inet_mask_del                                           */
9857 /* Returns:     Nil                                                         */
9858 /* Parameters:  bits(I) - number of bits set in the netmask                 */
9859 /*              mtab(I) - pointer to mask hash table structure              */
9860 /*                                                                          */
9861 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
9862 /* netmasks stored inside of mtab.                                          */
9863 /* ------------------------------------------------------------------------ */
9864 void
ipf_inet_mask_del(int bits,ipf_v4_masktab_t * mtab)9865 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9866 {
9867 	u_32_t mask;
9868 	int i, j;
9869 
9870 	mtab->imt4_masks[bits]--;
9871 	if (mtab->imt4_masks[bits] > 0)
9872 		return;
9873 
9874 	mask = htonl(0xffffffff << (32 - bits));
9875 	for (i = 0; i < 33; i++) {
9876 		if (mtab->imt4_active[i] == mask) {
9877 			for (j = i + 1; j < 33; j++)
9878 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9879 			break;
9880 		}
9881 	}
9882 	mtab->imt4_max--;
9883 	ASSERT(mtab->imt4_max >= 0);
9884 }
9885 
9886 
9887 #ifdef USE_INET6
9888 /* ------------------------------------------------------------------------ */
9889 /* Function:    ipf_inet6_mask_add                                          */
9890 /* Returns:     Nil                                                         */
9891 /* Parameters:  bits(I) - number of bits set in mask                        */
9892 /*              mask(I) - pointer to mask to add                            */
9893 /*              mtab(I) - pointer to mask hash table structure              */
9894 /*                                                                          */
9895 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
9896 /* has just been added. This function inserts a bitmask into the array of   */
9897 /* masks to search when searching for a matching NAT rule for a packet.     */
9898 /* Prevention of duplicate masks is achieved by checking the use count for  */
9899 /* a given netmask.                                                         */
9900 /* ------------------------------------------------------------------------ */
9901 void
ipf_inet6_mask_add(int bits,i6addr_t * mask,ipf_v6_masktab_t * mtab)9902 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9903 {
9904 	i6addr_t zero;
9905 	int i, j;
9906 
9907 	mtab->imt6_masks[bits]++;
9908 	if (mtab->imt6_masks[bits] > 1)
9909 		return;
9910 
9911 	if (bits == 0) {
9912 		mask = &zero;
9913 		zero.i6[0] = 0;
9914 		zero.i6[1] = 0;
9915 		zero.i6[2] = 0;
9916 		zero.i6[3] = 0;
9917 	}
9918 
9919 	for (i = 0; i < 129; i++) {
9920 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
9921 			for (j = 128; j > i; j--)
9922 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9923 			mtab->imt6_active[i] = *mask;
9924 			break;
9925 		}
9926 	}
9927 	mtab->imt6_max++;
9928 }
9929 
9930 
9931 /* ------------------------------------------------------------------------ */
9932 /* Function:    ipf_inet6_mask_del                                          */
9933 /* Returns:     Nil                                                         */
9934 /* Parameters:  bits(I) - number of bits set in mask                        */
9935 /*              mask(I) - pointer to mask to remove                         */
9936 /*              mtab(I) - pointer to mask hash table structure              */
9937 /*                                                                          */
9938 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
9939 /* netmasks stored inside of mtab.                                          */
9940 /* ------------------------------------------------------------------------ */
9941 void
ipf_inet6_mask_del(int bits,i6addr_t * mask,ipf_v6_masktab_t * mtab)9942 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9943 {
9944 	i6addr_t zero;
9945 	int i, j;
9946 
9947 	mtab->imt6_masks[bits]--;
9948 	if (mtab->imt6_masks[bits] > 0)
9949 		return;
9950 
9951 	if (bits == 0)
9952 		mask = &zero;
9953 	zero.i6[0] = 0;
9954 	zero.i6[1] = 0;
9955 	zero.i6[2] = 0;
9956 	zero.i6[3] = 0;
9957 
9958 	for (i = 0; i < 129; i++) {
9959 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9960 			for (j = i + 1; j < 129; j++) {
9961 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9962 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
9963 					break;
9964 			}
9965 			break;
9966 		}
9967 	}
9968 	mtab->imt6_max--;
9969 	ASSERT(mtab->imt6_max >= 0);
9970 }
9971 #endif
9972