xref: /freebsd/sys/netpfil/ipfilter/netinet/fil.c (revision 79d23845179a534f533185763cb92032202729a7)
1 
2 /*
3  * Copyright (C) 2012 by Darren Reed.
4  *
5  * See the IPFILTER.LICENCE file for details on licencing.
6  *
7  * Copyright 2008 Sun Microsystems.
8  *
9  * $Id$
10  *
11  */
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define        KERNEL	1
16 # define        _KERNEL	1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #if defined(_KERNEL) && defined(__FreeBSD__)
23 #  if !defined(IPFILTER_LKM)
24 #   include "opt_inet6.h"
25 #  endif
26 # include <sys/filio.h>
27 #else
28 # include <sys/ioctl.h>
29 #endif
30 #if defined(__SVR4) || defined(sun) /* SOLARIS */
31 # include <sys/filio.h>
32 #endif
33 # include <sys/fcntl.h>
34 #if defined(_KERNEL)
35 # include <sys/systm.h>
36 # include <sys/file.h>
37 #else
38 # include <stdio.h>
39 # include <string.h>
40 # include <stdlib.h>
41 # include <stddef.h>
42 # include <sys/file.h>
43 # define _KERNEL
44 # include <sys/uio.h>
45 # undef _KERNEL
46 #endif
47 #if !defined(__SVR4)
48 # include <sys/mbuf.h>
49 #else
50 # include <sys/byteorder.h>
51 # if (SOLARIS2 < 5) && defined(sun)
52 #  include <sys/dditypes.h>
53 # endif
54 #endif
55 # include <sys/protosw.h>
56 #include <sys/socket.h>
57 #include <net/if.h>
58 #ifdef sun
59 # include <net/af.h>
60 #endif
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/tcp.h>
65 # include <netinet/udp.h>
66 # include <netinet/ip_icmp.h>
67 #include "netinet/ip_compat.h"
68 #ifdef	USE_INET6
69 # include <netinet/icmp6.h>
70 # if !SOLARIS && defined(_KERNEL)
71 #  include <netinet6/in6_var.h>
72 # endif
73 #endif
74 #include "netinet/ip_fil.h"
75 #include "netinet/ip_nat.h"
76 #include "netinet/ip_frag.h"
77 #include "netinet/ip_state.h"
78 #include "netinet/ip_proxy.h"
79 #include "netinet/ip_auth.h"
80 #ifdef IPFILTER_SCAN
81 # include "netinet/ip_scan.h"
82 #endif
83 #include "netinet/ip_sync.h"
84 #include "netinet/ip_lookup.h"
85 #include "netinet/ip_pool.h"
86 #include "netinet/ip_htable.h"
87 #ifdef IPFILTER_COMPILED
88 # include "netinet/ip_rules.h"
89 #endif
90 #if defined(IPFILTER_BPF) && defined(_KERNEL)
91 # include <net/bpf.h>
92 #endif
93 #if defined(__FreeBSD__)
94 # include <sys/malloc.h>
95 #endif
96 #include "netinet/ipl.h"
97 
98 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
99 # include <sys/callout.h>
100 extern struct callout ipf_slowtimer_ch;
101 #endif
102 /* END OF INCLUDES */
103 
104 
105 #ifndef	_KERNEL
106 # include "ipf.h"
107 # include "ipt.h"
108 extern	int	opts;
109 extern	int	blockreason;
110 #endif /* _KERNEL */
111 
112 #define FASTROUTE_RECURSION
113 
114 #define	LBUMP(x)	softc->x++
115 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
116 
117 static	inline int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
118 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
119 static	u_32_t		ipf_checkripso(u_char *);
120 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
121 #ifdef IPFILTER_LOG
122 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
123 #endif
124 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
125 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **,
126 					      int);
127 static	ipfunc_t	ipf_findfunc(ipfunc_t);
128 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
129 					     i6addr_t *, i6addr_t *);
130 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
131 static	int		ipf_fr_matcharray(fr_info_t *, int *);
132 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int,
133 					    void *);
134 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);
135 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
136 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
137 					 ipfgeniter_t *);
138 static	void		ipf_getstat(ipf_main_softc_t *,
139 					 struct friostat *, int);
140 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
141 static	void		ipf_group_free(frgroup_t *);
142 static	int		ipf_grpmapfini(struct ipf_main_softc_s *,
143 					    frentry_t *);
144 static	int		ipf_grpmapinit(struct ipf_main_softc_s *,
145 					    frentry_t *);
146 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
147 					   frentry_t *, int);
148 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
149 static	inline int	ipf_pr_ah(fr_info_t *);
150 static	inline void	ipf_pr_esp(fr_info_t *);
151 static	inline void	ipf_pr_gre(fr_info_t *);
152 static	inline void	ipf_pr_udp(fr_info_t *);
153 static	inline void	ipf_pr_tcp(fr_info_t *);
154 static	inline void	ipf_pr_icmp(fr_info_t *);
155 static	inline void	ipf_pr_ipv4hdr(fr_info_t *);
156 static	inline void	ipf_pr_short(fr_info_t *, int);
157 static	inline int	ipf_pr_tcpcommon(fr_info_t *);
158 static	inline int	ipf_pr_udpcommon(fr_info_t *);
159 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
160 					     int, int);
161 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
162 						    frentry_t *, int);
163 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *,
164 					  void *);
165 static	void		ipf_token_flush(ipf_main_softc_t *);
166 static	void		ipf_token_unlink(ipf_main_softc_t *,
167 					      ipftoken_t *);
168 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *,
169 						  const char *);
170 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
171 						    void **);
172 static	int		ipf_updateipid(fr_info_t *);
173 static	int		ipf_settimeout(struct ipf_main_softc_s *,
174 					    struct ipftuneable *,
175 					    ipftuneval_t *);
176 #if !defined(_KERNEL) || SOLARIS
177 static	int		ppsratecheck(struct timeval *, int *, int);
178 #endif
179 
180 
181 /*
182  * bit values for identifying presence of individual IP options
183  * All of these tables should be ordered by increasing key value on the left
184  * hand side to allow for binary searching of the array and include a trailer
185  * with a 0 for the bitmask for linear searches to easily find the end with.
186  */
187 static const	struct	optlist	ipopts[] = {
188 	{ IPOPT_NOP,	0x000001 },
189 	{ IPOPT_RR,	0x000002 },
190 	{ IPOPT_ZSU,	0x000004 },
191 	{ IPOPT_MTUP,	0x000008 },
192 	{ IPOPT_MTUR,	0x000010 },
193 	{ IPOPT_ENCODE,	0x000020 },
194 	{ IPOPT_TS,	0x000040 },
195 	{ IPOPT_TR,	0x000080 },
196 	{ IPOPT_SECURITY, 0x000100 },
197 	{ IPOPT_LSRR,	0x000200 },
198 	{ IPOPT_E_SEC,	0x000400 },
199 	{ IPOPT_CIPSO,	0x000800 },
200 	{ IPOPT_SATID,	0x001000 },
201 	{ IPOPT_SSRR,	0x002000 },
202 	{ IPOPT_ADDEXT,	0x004000 },
203 	{ IPOPT_VISA,	0x008000 },
204 	{ IPOPT_IMITD,	0x010000 },
205 	{ IPOPT_EIP,	0x020000 },
206 	{ IPOPT_FINN,	0x040000 },
207 	{ 0,		0x000000 }
208 };
209 
210 #ifdef USE_INET6
211 static const struct optlist ip6exthdr[] = {
212 	{ IPPROTO_HOPOPTS,		0x000001 },
213 	{ IPPROTO_IPV6,			0x000002 },
214 	{ IPPROTO_ROUTING,		0x000004 },
215 	{ IPPROTO_FRAGMENT,		0x000008 },
216 	{ IPPROTO_ESP,			0x000010 },
217 	{ IPPROTO_AH,			0x000020 },
218 	{ IPPROTO_NONE,			0x000040 },
219 	{ IPPROTO_DSTOPTS,		0x000080 },
220 	{ IPPROTO_MOBILITY,		0x000100 },
221 	{ 0,				0 }
222 };
223 #endif
224 
225 /*
226  * bit values for identifying presence of individual IP security options
227  */
228 static const	struct	optlist	secopt[] = {
229 	{ IPSO_CLASS_RES4,	0x01 },
230 	{ IPSO_CLASS_TOPS,	0x02 },
231 	{ IPSO_CLASS_SECR,	0x04 },
232 	{ IPSO_CLASS_RES3,	0x08 },
233 	{ IPSO_CLASS_CONF,	0x10 },
234 	{ IPSO_CLASS_UNCL,	0x20 },
235 	{ IPSO_CLASS_RES2,	0x40 },
236 	{ IPSO_CLASS_RES1,	0x80 }
237 };
238 
239 char	ipfilter_version[] = IPL_VERSION;
240 
241 int	ipf_features = 0
242 #ifdef	IPFILTER_LKM
243 		| IPF_FEAT_LKM
244 #endif
245 #ifdef	IPFILTER_LOG
246 		| IPF_FEAT_LOG
247 #endif
248 		| IPF_FEAT_LOOKUP
249 #ifdef	IPFILTER_BPF
250 		| IPF_FEAT_BPF
251 #endif
252 #ifdef	IPFILTER_COMPILED
253 		| IPF_FEAT_COMPILED
254 #endif
255 #ifdef	IPFILTER_CKSUM
256 		| IPF_FEAT_CKSUM
257 #endif
258 		| IPF_FEAT_SYNC
259 #ifdef	IPFILTER_SCAN
260 		| IPF_FEAT_SCAN
261 #endif
262 #ifdef	USE_INET6
263 		| IPF_FEAT_IPV6
264 #endif
265 	;
266 
267 
268 /*
269  * Table of functions available for use with call rules.
270  */
271 static ipfunc_resolve_t ipf_availfuncs[] = {
272 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
273 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
274 	{ "",	      NULL,	      NULL,	      NULL }
275 };
276 
277 static ipftuneable_t ipf_main_tuneables[] = {
278 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
279 		"ipf_flags",		0,	0xffffffff,
280 		stsizeof(ipf_main_softc_t, ipf_flags),
281 		0,			NULL,	NULL },
282 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
283 		"active",		0,	0,
284 		stsizeof(ipf_main_softc_t, ipf_active),
285 		IPFT_RDONLY,		NULL,	NULL },
286 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
287 		"control_forwarding",	0, 1,
288 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
289 		0,			NULL,	NULL },
290 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
291 		"update_ipid",		0,	1,
292 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
293 		0,			NULL,	NULL },
294 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
295 		"chksrc",		0,	1,
296 		stsizeof(ipf_main_softc_t, ipf_chksrc),
297 		0,			NULL,	NULL },
298 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
299 		"min_ttl",		0,	1,
300 		stsizeof(ipf_main_softc_t, ipf_minttl),
301 		0,			NULL,	NULL },
302 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
303 		"icmp_minfragmtu",	0,	1,
304 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
305 		0,			NULL,	NULL },
306 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
307 		"default_pass",		0,	0xffffffff,
308 		stsizeof(ipf_main_softc_t, ipf_pass),
309 		0,			NULL,	NULL },
310 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
311 		"tcp_idle_timeout",	1,	0x7fffffff,
312 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
313 		0,			NULL,	ipf_settimeout },
314 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
315 		"tcp_close_wait",	1,	0x7fffffff,
316 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
317 		0,			NULL,	ipf_settimeout },
318 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
319 		"tcp_last_ack",		1,	0x7fffffff,
320 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
321 		0,			NULL,	ipf_settimeout },
322 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
323 		"tcp_timeout",		1,	0x7fffffff,
324 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
325 		0,			NULL,	ipf_settimeout },
326 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
327 		"tcp_syn_sent",		1,	0x7fffffff,
328 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
329 		0,			NULL,	ipf_settimeout },
330 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
331 		"tcp_syn_received",	1,	0x7fffffff,
332 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
333 		0,			NULL,	ipf_settimeout },
334 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
335 		"tcp_closed",		1,	0x7fffffff,
336 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
337 		0,			NULL,	ipf_settimeout },
338 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
339 		"tcp_half_closed",	1,	0x7fffffff,
340 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
341 		0,			NULL,	ipf_settimeout },
342 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
343 		"tcp_time_wait",	1,	0x7fffffff,
344 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
345 		0,			NULL,	ipf_settimeout },
346 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
347 		"udp_timeout",		1,	0x7fffffff,
348 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
349 		0,			NULL,	ipf_settimeout },
350 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
351 		"udp_ack_timeout",	1,	0x7fffffff,
352 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
353 		0,			NULL,	ipf_settimeout },
354 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
355 		"icmp_timeout",		1,	0x7fffffff,
356 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
357 		0,			NULL,	ipf_settimeout },
358 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
359 		"icmp_ack_timeout",	1,	0x7fffffff,
360 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
361 		0,			NULL,	ipf_settimeout },
362 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
363 		"ip_timeout",		1,	0x7fffffff,
364 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
365 		0,			NULL,	ipf_settimeout },
366 #if defined(INSTANCES) && defined(_KERNEL)
367 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
368 		"intercept_loopback",	0,	1,
369 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
370 		0,			NULL,	ipf_set_loopback },
371 #endif
372 	{ { 0 },
373 		NULL,			0,	0,
374 		0,
375 		0,			NULL,	NULL }
376 };
377 
378 
379 /*
380  * The next section of code is a collection of small routines that set
381  * fields in the fr_info_t structure passed based on properties of the
382  * current packet.  There are different routines for the same protocol
383  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
384  * will "special" inspection for setup, is now more easily done by adding
385  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
386  * adding more code to a growing switch statement.
387  */
388 #ifdef USE_INET6
389 static	inline int	ipf_pr_ah6(fr_info_t *);
390 static	inline void	ipf_pr_esp6(fr_info_t *);
391 static	inline void	ipf_pr_gre6(fr_info_t *);
392 static	inline void	ipf_pr_udp6(fr_info_t *);
393 static	inline void	ipf_pr_tcp6(fr_info_t *);
394 static	inline void	ipf_pr_icmp6(fr_info_t *);
395 static	inline void	ipf_pr_ipv6hdr(fr_info_t *);
396 static	inline void	ipf_pr_short6(fr_info_t *, int);
397 static	inline int	ipf_pr_hopopts6(fr_info_t *);
398 static	inline int	ipf_pr_mobility6(fr_info_t *);
399 static	inline int	ipf_pr_routing6(fr_info_t *);
400 static	inline int	ipf_pr_dstopts6(fr_info_t *);
401 static	inline int	ipf_pr_fragment6(fr_info_t *);
402 static	inline struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
403 
404 
405 /* ------------------------------------------------------------------------ */
406 /* Function:    ipf_pr_short6                                               */
407 /* Returns:     void                                                        */
408 /* Parameters:  fin(I)  - pointer to packet information                     */
409 /*              xmin(I) - minimum header size                               */
410 /*                                                                          */
411 /* IPv6 Only                                                                */
412 /* This is function enforces the 'is a packet too short to be legit' rule   */
413 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
414 /* for ipf_pr_short() for more details.                                     */
415 /* ------------------------------------------------------------------------ */
416 static inline void
ipf_pr_short6(fr_info_t * fin,int xmin)417 ipf_pr_short6(fr_info_t *fin, int xmin)
418 {
419 
420 	if (fin->fin_dlen < xmin)
421 		fin->fin_flx |= FI_SHORT;
422 }
423 
424 
425 /* ------------------------------------------------------------------------ */
426 /* Function:    ipf_pr_ipv6hdr                                              */
427 /* Returns:     void                                                        */
428 /* Parameters:  fin(I) - pointer to packet information                      */
429 /*                                                                          */
430 /* IPv6 Only                                                                */
431 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
432 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
433 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
434 /* of that possibility arising.                                             */
435 /* ------------------------------------------------------------------------ */
436 static inline void
ipf_pr_ipv6hdr(fr_info_t * fin)437 ipf_pr_ipv6hdr(fr_info_t *fin)
438 {
439 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
440 	int p, go = 1, i;
441 	fr_ip_t *fi = &fin->fin_fi;
442 
443 	fin->fin_off = 0;
444 
445 	fi->fi_tos = 0;
446 	fi->fi_optmsk = 0;
447 	fi->fi_secmsk = 0;
448 	fi->fi_auth = 0;
449 
450 	p = ip6->ip6_nxt;
451 	fin->fin_crc = p;
452 	fi->fi_ttl = ip6->ip6_hlim;
453 	fi->fi_src.in6 = ip6->ip6_src;
454 	fin->fin_crc += fi->fi_src.i6[0];
455 	fin->fin_crc += fi->fi_src.i6[1];
456 	fin->fin_crc += fi->fi_src.i6[2];
457 	fin->fin_crc += fi->fi_src.i6[3];
458 	fi->fi_dst.in6 = ip6->ip6_dst;
459 	fin->fin_crc += fi->fi_dst.i6[0];
460 	fin->fin_crc += fi->fi_dst.i6[1];
461 	fin->fin_crc += fi->fi_dst.i6[2];
462 	fin->fin_crc += fi->fi_dst.i6[3];
463 	fin->fin_id = 0;
464 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
465 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
466 
467 	while (go && !(fin->fin_flx & FI_SHORT)) {
468 		switch (p)
469 		{
470 		case IPPROTO_UDP :
471 			ipf_pr_udp6(fin);
472 			go = 0;
473 			break;
474 
475 		case IPPROTO_TCP :
476 			ipf_pr_tcp6(fin);
477 			go = 0;
478 			break;
479 
480 		case IPPROTO_ICMPV6 :
481 			ipf_pr_icmp6(fin);
482 			go = 0;
483 			break;
484 
485 		case IPPROTO_GRE :
486 			ipf_pr_gre6(fin);
487 			go = 0;
488 			break;
489 
490 		case IPPROTO_HOPOPTS :
491 			p = ipf_pr_hopopts6(fin);
492 			break;
493 
494 		case IPPROTO_MOBILITY :
495 			p = ipf_pr_mobility6(fin);
496 			break;
497 
498 		case IPPROTO_DSTOPTS :
499 			p = ipf_pr_dstopts6(fin);
500 			break;
501 
502 		case IPPROTO_ROUTING :
503 			p = ipf_pr_routing6(fin);
504 			break;
505 
506 		case IPPROTO_AH :
507 			p = ipf_pr_ah6(fin);
508 			break;
509 
510 		case IPPROTO_ESP :
511 			ipf_pr_esp6(fin);
512 			go = 0;
513 			break;
514 
515 		case IPPROTO_IPV6 :
516 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
517 				if (ip6exthdr[i].ol_val == p) {
518 					fin->fin_flx |= ip6exthdr[i].ol_bit;
519 					break;
520 				}
521 			go = 0;
522 			break;
523 
524 		case IPPROTO_NONE :
525 			go = 0;
526 			break;
527 
528 		case IPPROTO_FRAGMENT :
529 			p = ipf_pr_fragment6(fin);
530 			/*
531 			 * Given that the only fragments we want to let through
532 			 * (where fin_off != 0) are those where the non-first
533 			 * fragments only have data, we can safely stop looking
534 			 * at headers if this is a non-leading fragment.
535 			 */
536 			if (fin->fin_off != 0)
537 				go = 0;
538 			break;
539 
540 		default :
541 			go = 0;
542 			break;
543 		}
544 
545 		/*
546 		 * It is important to note that at this point, for the
547 		 * extension headers (go != 0), the entire header may not have
548 		 * been pulled up when the code gets to this point.  This is
549 		 * only done for "go != 0" because the other header handlers
550 		 * will all pullup their complete header.  The other indicator
551 		 * of an incomplete packet is that this was just an extension
552 		 * header.
553 		 */
554 		if ((go != 0) && (p != IPPROTO_NONE) &&
555 		    (ipf_pr_pullup(fin, 0) == -1)) {
556 			p = IPPROTO_NONE;
557 			break;
558 		}
559 	}
560 
561 	/*
562 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
563 	 * and destroy whatever packet was here.  The caller of this function
564 	 * expects us to return if there is a problem with ipf_pullup.
565 	 */
566 	if (fin->fin_m == NULL) {
567 		ipf_main_softc_t *softc = fin->fin_main_soft;
568 
569 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
570 		return;
571 	}
572 
573 	fi->fi_p = p;
574 
575 	/*
576 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
577 	 * "go != 0" implies the above loop hasn't arrived at a layer 4 header.
578 	 */
579 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
580 		ipf_main_softc_t *softc = fin->fin_main_soft;
581 
582 		fin->fin_flx |= FI_BAD;
583 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
584 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
585 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
586 	}
587 }
588 
589 
590 /* ------------------------------------------------------------------------ */
591 /* Function:    ipf_pr_ipv6exthdr                                           */
592 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
593 /*                                 or NULL if there is a prolblem.          */
594 /* Parameters:  fin(I)      - pointer to packet information                 */
595 /*              multiple(I) - flag indicating yes/no if multiple occurances */
596 /*                            of this extension header are allowed.         */
597 /*              proto(I)    - protocol number for this extension header     */
598 /*                                                                          */
599 /* IPv6 Only                                                                */
600 /* This function embodies a number of common checks that all IPv6 extension */
601 /* headers must be subjected to.  For example, making sure the packet is    */
602 /* big enough for it to be in, checking if it is repeated and setting a     */
603 /* flag to indicate its presence.                                           */
604 /* ------------------------------------------------------------------------ */
605 static inline struct ip6_ext *
ipf_pr_ipv6exthdr(fr_info_t * fin,int multiple,int proto)606 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
607 {
608 	ipf_main_softc_t *softc = fin->fin_main_soft;
609 	struct ip6_ext *hdr;
610 	u_short shift;
611 	int i;
612 
613 	fin->fin_flx |= FI_V6EXTHDR;
614 
615 				/* 8 is default length of extension hdr */
616 	if ((fin->fin_dlen - 8) < 0) {
617 		fin->fin_flx |= FI_SHORT;
618 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
619 		return (NULL);
620 	}
621 
622 	if (ipf_pr_pullup(fin, 8) == -1) {
623 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
624 		return (NULL);
625 	}
626 
627 	hdr = fin->fin_dp;
628 	switch (proto)
629 	{
630 	case IPPROTO_FRAGMENT :
631 		shift = 8;
632 		break;
633 	default :
634 		shift = 8 + (hdr->ip6e_len << 3);
635 		break;
636 	}
637 
638 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
639 		fin->fin_flx |= FI_BAD;
640 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
641 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
642 		return (NULL);
643 	}
644 
645 	fin->fin_dp = (char *)fin->fin_dp + shift;
646 	fin->fin_dlen -= shift;
647 
648 	/*
649 	 * If we have seen a fragment header, do not set any flags to indicate
650 	 * the presence of this extension header as it has no impact on the
651 	 * end result until after it has been defragmented.
652 	 */
653 	if (fin->fin_flx & FI_FRAG)
654 		return (hdr);
655 
656 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
657 		if (ip6exthdr[i].ol_val == proto) {
658 			/*
659 			 * Most IPv6 extension headers are only allowed once.
660 			 */
661 			if ((multiple == 0) &&
662 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
663 				fin->fin_flx |= FI_BAD;
664 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
665 			} else
666 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
667 			break;
668 		}
669 
670 	return (hdr);
671 }
672 
673 
674 /* ------------------------------------------------------------------------ */
675 /* Function:    ipf_pr_hopopts6                                             */
676 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
677 /* Parameters:  fin(I) - pointer to packet information                      */
678 /*                                                                          */
679 /* IPv6 Only                                                                */
680 /* This is function checks pending hop by hop options extension header      */
681 /* ------------------------------------------------------------------------ */
682 static inline int
ipf_pr_hopopts6(fr_info_t * fin)683 ipf_pr_hopopts6(fr_info_t *fin)
684 {
685 	struct ip6_ext *hdr;
686 
687 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
688 	if (hdr == NULL)
689 		return (IPPROTO_NONE);
690 	return (hdr->ip6e_nxt);
691 }
692 
693 
694 /* ------------------------------------------------------------------------ */
695 /* Function:    ipf_pr_mobility6                                            */
696 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
697 /* Parameters:  fin(I) - pointer to packet information                      */
698 /*                                                                          */
699 /* IPv6 Only                                                                */
700 /* This is function checks the IPv6 mobility extension header               */
701 /* ------------------------------------------------------------------------ */
702 static inline int
ipf_pr_mobility6(fr_info_t * fin)703 ipf_pr_mobility6(fr_info_t *fin)
704 {
705 	struct ip6_ext *hdr;
706 
707 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
708 	if (hdr == NULL)
709 		return (IPPROTO_NONE);
710 	return (hdr->ip6e_nxt);
711 }
712 
713 
714 /* ------------------------------------------------------------------------ */
715 /* Function:    ipf_pr_routing6                                             */
716 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
717 /* Parameters:  fin(I) - pointer to packet information                      */
718 /*                                                                          */
719 /* IPv6 Only                                                                */
720 /* This is function checks pending routing extension header                 */
721 /* ------------------------------------------------------------------------ */
722 static inline int
ipf_pr_routing6(fr_info_t * fin)723 ipf_pr_routing6(fr_info_t *fin)
724 {
725 	struct ip6_routing *hdr;
726 
727 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
728 	if (hdr == NULL)
729 		return (IPPROTO_NONE);
730 
731 	switch (hdr->ip6r_type)
732 	{
733 	case 0 :
734 		/*
735 		 * Nasty extension header length?
736 		 */
737 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
738 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
739 			ipf_main_softc_t *softc = fin->fin_main_soft;
740 
741 			fin->fin_flx |= FI_BAD;
742 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
743 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
744 			return (IPPROTO_NONE);
745 		}
746 		break;
747 
748 	default :
749 		break;
750 	}
751 
752 	return (hdr->ip6r_nxt);
753 }
754 
755 
756 /* ------------------------------------------------------------------------ */
757 /* Function:    ipf_pr_fragment6                                            */
758 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
759 /* Parameters:  fin(I) - pointer to packet information                      */
760 /*                                                                          */
761 /* IPv6 Only                                                                */
762 /* Examine the IPv6 fragment header and extract fragment offset information.*/
763 /*                                                                          */
764 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
765 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
766 /* packets with a fragment header can fit into.  They are as follows:       */
767 /*                                                                          */
768 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
769 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
770 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
771 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
772 /* 5.  [IPV6][0-n EH][FH][data]                                             */
773 /*                                                                          */
774 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
775 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
776 /*                                                                          */
777 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
778 /* scenario in which they happen is in extreme circumstances that are most  */
779 /* likely to be an indication of an attack rather than normal traffic.      */
780 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
781 /* are two rules that can be used to guard against type 3 packets: L4       */
782 /* headers must always be in a packet that has the offset field set to 0    */
783 /* and no packet is allowed to overlay that where offset = 0.               */
784 /* ------------------------------------------------------------------------ */
785 static inline int
ipf_pr_fragment6(fr_info_t * fin)786 ipf_pr_fragment6(fr_info_t *fin)
787 {
788 	ipf_main_softc_t *softc = fin->fin_main_soft;
789 	struct ip6_frag *frag;
790 
791 	fin->fin_flx |= FI_FRAG;
792 
793 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
794 	if (frag == NULL) {
795 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
796 		return (IPPROTO_NONE);
797 	}
798 
799 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
800 		/*
801 		 * Any fragment that isn't the last fragment must have its
802 		 * length as a multiple of 8.
803 		 */
804 		if ((fin->fin_plen & 7) != 0) {
805 			fin->fin_flx |= FI_BAD;
806 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
807 		}
808 	}
809 
810 	fin->fin_fraghdr = frag;
811 	fin->fin_id = frag->ip6f_ident;
812 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
813 	if (fin->fin_off != 0)
814 		fin->fin_flx |= FI_FRAGBODY;
815 
816 	/*
817 	 * Jumbograms aren't handled, so the max. length is 64k
818 	 */
819 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
820 		  fin->fin_flx |= FI_BAD;
821 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
822 	}
823 
824 	/*
825 	 * We don't know where the transport layer header (or whatever is next
826 	 * is), as it could be behind destination options (amongst others) so
827 	* return the fragment header as the type of packet this is.  Note that
828 	 * this effectively disables the fragment cache for > 1 protocol at a
829 	 * time.
830 	 */
831 	return (frag->ip6f_nxt);
832 }
833 
834 
835 /* ------------------------------------------------------------------------ */
836 /* Function:    ipf_pr_dstopts6                                             */
837 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
838 /* Parameters:  fin(I) - pointer to packet information                      */
839 /*                                                                          */
840 /* IPv6 Only                                                                */
841 /* This is function checks pending destination options extension header     */
842 /* ------------------------------------------------------------------------ */
843 static inline int
ipf_pr_dstopts6(fr_info_t * fin)844 ipf_pr_dstopts6(fr_info_t *fin)
845 {
846 	ipf_main_softc_t *softc = fin->fin_main_soft;
847 	struct ip6_ext *hdr;
848 
849 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
850 	if (hdr == NULL) {
851 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
852 		return (IPPROTO_NONE);
853 	}
854 	return (hdr->ip6e_nxt);
855 }
856 
857 
858 /* ------------------------------------------------------------------------ */
859 /* Function:    ipf_pr_icmp6                                                */
860 /* Returns:     void                                                        */
861 /* Parameters:  fin(I) - pointer to packet information                      */
862 /*                                                                          */
863 /* IPv6 Only                                                                */
864 /* This routine is mainly concerned with determining the minimum valid size */
865 /* for an ICMPv6 packet.                                                    */
866 /* ------------------------------------------------------------------------ */
867 static inline void
ipf_pr_icmp6(fr_info_t * fin)868 ipf_pr_icmp6(fr_info_t *fin)
869 {
870 	int minicmpsz = sizeof(struct icmp6_hdr);
871 	struct icmp6_hdr *icmp6;
872 
873 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
874 		ipf_main_softc_t *softc = fin->fin_main_soft;
875 
876 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
877 		return;
878 	}
879 
880 	if (fin->fin_dlen > 1) {
881 		ip6_t *ip6;
882 
883 		icmp6 = fin->fin_dp;
884 
885 		fin->fin_data[0] = *(u_short *)icmp6;
886 
887 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
888 			fin->fin_flx |= FI_ICMPQUERY;
889 
890 		switch (icmp6->icmp6_type)
891 		{
892 		case ICMP6_ECHO_REPLY :
893 		case ICMP6_ECHO_REQUEST :
894 			if (fin->fin_dlen >= 6)
895 				fin->fin_data[1] = icmp6->icmp6_id;
896 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
897 			break;
898 
899 		case ICMP6_DST_UNREACH :
900 		case ICMP6_PACKET_TOO_BIG :
901 		case ICMP6_TIME_EXCEEDED :
902 		case ICMP6_PARAM_PROB :
903 			fin->fin_flx |= FI_ICMPERR;
904 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
905 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
906 				break;
907 
908 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
909 				if (ipf_coalesce(fin) != 1)
910 					return;
911 			}
912 
913 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
914 				return;
915 
916 			/*
917 			 * If the destination of this packet doesn't match the
918 			 * source of the original packet then this packet is
919 			 * not correct.
920 			 */
921 			icmp6 = fin->fin_dp;
922 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
923 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
924 				    (i6addr_t *)&ip6->ip6_src)) {
925 				fin->fin_flx |= FI_BAD;
926 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
927 			}
928 			break;
929 		default :
930 			break;
931 		}
932 	}
933 
934 	ipf_pr_short6(fin, minicmpsz);
935 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
936 		u_char p = fin->fin_p;
937 
938 		fin->fin_p = IPPROTO_ICMPV6;
939 		ipf_checkv6sum(fin);
940 		fin->fin_p = p;
941 	}
942 }
943 
944 
945 /* ------------------------------------------------------------------------ */
946 /* Function:    ipf_pr_udp6                                                 */
947 /* Returns:     void                                                        */
948 /* Parameters:  fin(I) - pointer to packet information                      */
949 /*                                                                          */
950 /* IPv6 Only                                                                */
951 /* Analyse the packet for IPv6/UDP properties.                              */
952 /* Is not expected to be called for fragmented packets.                     */
953 /* ------------------------------------------------------------------------ */
954 static inline void
ipf_pr_udp6(fr_info_t * fin)955 ipf_pr_udp6(fr_info_t *fin)
956 {
957 
958 	if (ipf_pr_udpcommon(fin) == 0) {
959 		u_char p = fin->fin_p;
960 
961 		fin->fin_p = IPPROTO_UDP;
962 		ipf_checkv6sum(fin);
963 		fin->fin_p = p;
964 	}
965 }
966 
967 
968 /* ------------------------------------------------------------------------ */
969 /* Function:    ipf_pr_tcp6                                                 */
970 /* Returns:     void                                                        */
971 /* Parameters:  fin(I) - pointer to packet information                      */
972 /*                                                                          */
973 /* IPv6 Only                                                                */
974 /* Analyse the packet for IPv6/TCP properties.                              */
975 /* Is not expected to be called for fragmented packets.                     */
976 /* ------------------------------------------------------------------------ */
977 static inline void
ipf_pr_tcp6(fr_info_t * fin)978 ipf_pr_tcp6(fr_info_t *fin)
979 {
980 
981 	if (ipf_pr_tcpcommon(fin) == 0) {
982 		u_char p = fin->fin_p;
983 
984 		fin->fin_p = IPPROTO_TCP;
985 		ipf_checkv6sum(fin);
986 		fin->fin_p = p;
987 	}
988 }
989 
990 
991 /* ------------------------------------------------------------------------ */
992 /* Function:    ipf_pr_esp6                                                 */
993 /* Returns:     void                                                        */
994 /* Parameters:  fin(I) - pointer to packet information                      */
995 /*                                                                          */
996 /* IPv6 Only                                                                */
997 /* Analyse the packet for ESP properties.                                   */
998 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
999 /* even though the newer ESP packets must also have a sequence number that  */
1000 /* is 32bits as well, it is not possible(?) to determine the version from a */
1001 /* simple packet header.                                                    */
1002 /* ------------------------------------------------------------------------ */
1003 static inline void
ipf_pr_esp6(fr_info_t * fin)1004 ipf_pr_esp6(fr_info_t *fin)
1005 {
1006 
1007 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1008 		ipf_main_softc_t *softc = fin->fin_main_soft;
1009 
1010 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1011 		return;
1012 	}
1013 }
1014 
1015 
1016 /* ------------------------------------------------------------------------ */
1017 /* Function:    ipf_pr_ah6                                                  */
1018 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1019 /* Parameters:  fin(I) - pointer to packet information                      */
1020 /*                                                                          */
1021 /* IPv6 Only                                                                */
1022 /* Analyse the packet for AH properties.                                    */
1023 /* The minimum length is taken to be the combination of all fields in the   */
1024 /* header being present and no authentication data (null algorithm used.)   */
1025 /* ------------------------------------------------------------------------ */
1026 static inline int
ipf_pr_ah6(fr_info_t * fin)1027 ipf_pr_ah6(fr_info_t *fin)
1028 {
1029 	authhdr_t *ah;
1030 
1031 	fin->fin_flx |= FI_AH;
1032 
1033 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1034 	if (ah == NULL) {
1035 		ipf_main_softc_t *softc = fin->fin_main_soft;
1036 
1037 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1038 		return (IPPROTO_NONE);
1039 	}
1040 
1041 	ipf_pr_short6(fin, sizeof(*ah));
1042 
1043 	/*
1044 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1045 	 * enough data to satisfy ah_next (the very first one.)
1046 	 */
1047 	return (ah->ah_next);
1048 }
1049 
1050 
1051 /* ------------------------------------------------------------------------ */
1052 /* Function:    ipf_pr_gre6                                                 */
1053 /* Returns:     void                                                        */
1054 /* Parameters:  fin(I) - pointer to packet information                      */
1055 /*                                                                          */
1056 /* Analyse the packet for GRE properties.                                   */
1057 /* ------------------------------------------------------------------------ */
1058 static inline void
ipf_pr_gre6(fr_info_t * fin)1059 ipf_pr_gre6(fr_info_t *fin)
1060 {
1061 	grehdr_t *gre;
1062 
1063 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1064 		ipf_main_softc_t *softc = fin->fin_main_soft;
1065 
1066 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1067 		return;
1068 	}
1069 
1070 	gre = fin->fin_dp;
1071 	if (GRE_REV(gre->gr_flags) == 1)
1072 		fin->fin_data[0] = gre->gr_call;
1073 }
1074 #endif	/* USE_INET6 */
1075 
1076 
1077 /* ------------------------------------------------------------------------ */
1078 /* Function:    ipf_pr_pullup                                               */
1079 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1080 /* Parameters:  fin(I)  - pointer to packet information                     */
1081 /*              plen(I) - length (excluding L3 header) to pullup            */
1082 /*                                                                          */
1083 /* Short inline function to cut down on code duplication to perform a call  */
1084 /* to ipf_pullup to ensure there is the required amount of data,            */
1085 /* consecutively in the packet buffer.                                      */
1086 /*                                                                          */
1087 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1088 /* points to the first byte after the complete layer 3 header, which will   */
1089 /* include all of the known extension headers for IPv6 or options for IPv4. */
1090 /*                                                                          */
1091 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1092 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1093 /* - fin_ip) to what is passed through.                                     */
1094 /* ------------------------------------------------------------------------ */
1095 int
ipf_pr_pullup(fr_info_t * fin,int plen)1096 ipf_pr_pullup(fr_info_t *fin, int plen)
1097 {
1098 	ipf_main_softc_t *softc = fin->fin_main_soft;
1099 
1100 	if (fin->fin_m != NULL) {
1101 		if (fin->fin_dp != NULL)
1102 			plen += (char *)fin->fin_dp -
1103 				((char *)fin->fin_ip + fin->fin_hlen);
1104 		plen += fin->fin_hlen;
1105 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1106 #if defined(_KERNEL)
1107 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1108 				DT1(ipf_pullup_fail, fr_info_t *, fin);
1109 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1110 				fin->fin_reason = FRB_PULLUP;
1111 				fin->fin_flx |= FI_BAD;
1112 				return (-1);
1113 			}
1114 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1115 #else
1116 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1117 			/*
1118 			 * Fake ipf_pullup failing
1119 			 */
1120 			fin->fin_reason = FRB_PULLUP;
1121 			*fin->fin_mp = NULL;
1122 			fin->fin_m = NULL;
1123 			fin->fin_ip = NULL;
1124 			fin->fin_flx |= FI_BAD;
1125 			return (-1);
1126 #endif
1127 		}
1128 	}
1129 	return (0);
1130 }
1131 
1132 
1133 /* ------------------------------------------------------------------------ */
1134 /* Function:    ipf_pr_short                                                */
1135 /* Returns:     void                                                        */
1136 /* Parameters:  fin(I)  - pointer to packet information                     */
1137 /*              xmin(I) - minimum header size                               */
1138 /*                                                                          */
1139 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1140 /* applying here is that the packet must not be fragmented within the layer */
1141 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1142 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1143 /* entire layer 4 header must be present (min).                             */
1144 /* ------------------------------------------------------------------------ */
1145 static inline void
ipf_pr_short(fr_info_t * fin,int xmin)1146 ipf_pr_short(fr_info_t *fin, int xmin)
1147 {
1148 
1149 	if (fin->fin_off == 0) {
1150 		if (fin->fin_dlen < xmin)
1151 			fin->fin_flx |= FI_SHORT;
1152 	} else if (fin->fin_off < xmin) {
1153 		fin->fin_flx |= FI_SHORT;
1154 	}
1155 }
1156 
1157 
1158 /* ------------------------------------------------------------------------ */
1159 /* Function:    ipf_pr_icmp                                                 */
1160 /* Returns:     void                                                        */
1161 /* Parameters:  fin(I) - pointer to packet information                      */
1162 /*                                                                          */
1163 /* IPv4 Only                                                                */
1164 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1165 /* except extrememly bad packets, both type and code will be present.       */
1166 /* The expected minimum size of an ICMP packet is very much dependent on    */
1167 /* the type of it.                                                          */
1168 /*                                                                          */
1169 /* XXX - other ICMP sanity checks?                                          */
1170 /* ------------------------------------------------------------------------ */
1171 static inline void
ipf_pr_icmp(fr_info_t * fin)1172 ipf_pr_icmp(fr_info_t *fin)
1173 {
1174 	ipf_main_softc_t *softc = fin->fin_main_soft;
1175 	int minicmpsz = sizeof(struct icmp);
1176 	icmphdr_t *icmp;
1177 	ip_t *oip;
1178 
1179 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1180 
1181 	if (fin->fin_off != 0) {
1182 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1183 		return;
1184 	}
1185 
1186 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1187 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1188 		return;
1189 	}
1190 
1191 	icmp = fin->fin_dp;
1192 
1193 	fin->fin_data[0] = *(u_short *)icmp;
1194 	fin->fin_data[1] = icmp->icmp_id;
1195 
1196 	switch (icmp->icmp_type)
1197 	{
1198 	case ICMP_ECHOREPLY :
1199 	case ICMP_ECHO :
1200 	/* Router discovery messaes - RFC 1256 */
1201 	case ICMP_ROUTERADVERT :
1202 	case ICMP_ROUTERSOLICIT :
1203 		fin->fin_flx |= FI_ICMPQUERY;
1204 		minicmpsz = ICMP_MINLEN;
1205 		break;
1206 	/*
1207 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1208 	 * 3 * timestamp(3 * 4)
1209 	 */
1210 	case ICMP_TSTAMP :
1211 	case ICMP_TSTAMPREPLY :
1212 		fin->fin_flx |= FI_ICMPQUERY;
1213 		minicmpsz = 20;
1214 		break;
1215 	/*
1216 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1217 	 * mask(4)
1218 	 */
1219 	case ICMP_IREQ :
1220 	case ICMP_IREQREPLY :
1221 	case ICMP_MASKREQ :
1222 	case ICMP_MASKREPLY :
1223 		fin->fin_flx |= FI_ICMPQUERY;
1224 		minicmpsz = 12;
1225 		break;
1226 	/*
1227 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1228 	 */
1229 	case ICMP_UNREACH :
1230 #ifdef icmp_nextmtu
1231 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1232 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1233 				fin->fin_flx |= FI_BAD;
1234 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1235 			}
1236 		}
1237 #endif
1238 		/* FALLTHROUGH */
1239 	case ICMP_SOURCEQUENCH :
1240 	case ICMP_REDIRECT :
1241 	case ICMP_TIMXCEED :
1242 	case ICMP_PARAMPROB :
1243 		fin->fin_flx |= FI_ICMPERR;
1244 		if (ipf_coalesce(fin) != 1) {
1245 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1246 			return;
1247 		}
1248 
1249 		/*
1250 		 * ICMP error packets should not be generated for IP
1251 		 * packets that are a fragment that isn't the first
1252 		 * fragment.
1253 		 */
1254 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1255 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1256 			fin->fin_flx |= FI_BAD;
1257 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1258 		}
1259 
1260 		/*
1261 		 * If the destination of this packet doesn't match the
1262 		 * source of the original packet then this packet is
1263 		 * not correct.
1264 		 */
1265 		if (oip->ip_src.s_addr != fin->fin_daddr) {
1266 			fin->fin_flx |= FI_BAD;
1267 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1268 		}
1269 		break;
1270 	default :
1271 		break;
1272 	}
1273 
1274 	ipf_pr_short(fin, minicmpsz);
1275 
1276 	ipf_checkv4sum(fin);
1277 }
1278 
1279 
1280 /* ------------------------------------------------------------------------ */
1281 /* Function:    ipf_pr_tcpcommon                                            */
1282 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1283 /* Parameters:  fin(I) - pointer to packet information                      */
1284 /*                                                                          */
1285 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1286 /* and make some checks with how they interact with other fields.           */
1287 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1288 /* valid and mark the packet as bad if not.                                 */
1289 /* ------------------------------------------------------------------------ */
1290 static inline int
ipf_pr_tcpcommon(fr_info_t * fin)1291 ipf_pr_tcpcommon(fr_info_t *fin)
1292 {
1293 	ipf_main_softc_t *softc = fin->fin_main_soft;
1294 	int flags, tlen;
1295 	tcphdr_t *tcp;
1296 
1297 	fin->fin_flx |= FI_TCPUDP;
1298 	if (fin->fin_off != 0) {
1299 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1300 		return (0);
1301 	}
1302 
1303 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1304 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1305 		return (-1);
1306 	}
1307 
1308 	tcp = fin->fin_dp;
1309 	if (fin->fin_dlen > 3) {
1310 		fin->fin_sport = ntohs(tcp->th_sport);
1311 		fin->fin_dport = ntohs(tcp->th_dport);
1312 	}
1313 
1314 	if ((fin->fin_flx & FI_SHORT) != 0) {
1315 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1316 		return (1);
1317 	}
1318 
1319 	/*
1320 	 * Use of the TCP data offset *must* result in a value that is at
1321 	 * least the same size as the TCP header.
1322 	 */
1323 	tlen = TCP_OFF(tcp) << 2;
1324 	if (tlen < sizeof(tcphdr_t)) {
1325 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1326 		fin->fin_flx |= FI_BAD;
1327 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1328 		return (1);
1329 	}
1330 
1331 	flags = tcp_get_flags(tcp);
1332 	fin->fin_tcpf = tcp_get_flags(tcp);
1333 
1334 	/*
1335 	 * If the urgent flag is set, then the urgent pointer must
1336 	 * also be set and vice versa.  Good TCP packets do not have
1337 	 * just one of these set.
1338 	 */
1339 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1340 		fin->fin_flx |= FI_BAD;
1341 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1342 #if 0
1343 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1344 		/*
1345 		 * Ignore this case (#if 0) as it shows up in "real"
1346 		 * traffic with bogus values in the urgent pointer field.
1347 		 */
1348 		fin->fin_flx |= FI_BAD;
1349 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1350 #endif
1351 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1352 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1353 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1354 		fin->fin_flx |= FI_BAD;
1355 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1356 #if 1
1357 	} else if (((flags & TH_SYN) != 0) &&
1358 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
1359 		/*
1360 		 * SYN with URG and PUSH set is not for normal TCP but it is
1361 		 * possible(?) with T/TCP...but who uses T/TCP?
1362 		 */
1363 		fin->fin_flx |= FI_BAD;
1364 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1365 #endif
1366 	} else if (!(flags & TH_ACK)) {
1367 		/*
1368 		 * If the ack bit isn't set, then either the SYN or
1369 		 * RST bit must be set.  If the SYN bit is set, then
1370 		 * we expect the ACK field to be 0.  If the ACK is
1371 		 * not set and if URG, PSH or FIN are set, consdier
1372 		 * that to indicate a bad TCP packet.
1373 		 */
1374 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1375 			/*
1376 			 * Cisco PIX sets the ACK field to a random value.
1377 			 * In light of this, do not set FI_BAD until a patch
1378 			 * is available from Cisco to ensure that
1379 			 * interoperability between existing systems is
1380 			 * achieved.
1381 			 */
1382 			/*fin->fin_flx |= FI_BAD*/;
1383 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1384 		} else if (!(flags & (TH_RST|TH_SYN))) {
1385 			fin->fin_flx |= FI_BAD;
1386 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1387 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1388 			fin->fin_flx |= FI_BAD;
1389 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1390 		}
1391 	}
1392 	if (fin->fin_flx & FI_BAD) {
1393 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1394 		return (1);
1395 	}
1396 
1397 	/*
1398 	 * At this point, it's not exactly clear what is to be gained by
1399 	 * marking up which TCP options are and are not present.  The one we
1400 	 * are most interested in is the TCP window scale.  This is only in
1401 	 * a SYN packet [RFC1323] so we don't need this here...?
1402 	 * Now if we were to analyse the header for passive fingerprinting,
1403 	 * then that might add some weight to adding this...
1404 	 */
1405 	if (tlen == sizeof(tcphdr_t)) {
1406 		return (0);
1407 	}
1408 
1409 	if (ipf_pr_pullup(fin, tlen) == -1) {
1410 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1411 		return (-1);
1412 	}
1413 
1414 #if 0
1415 	tcp = fin->fin_dp;
1416 	ip = fin->fin_ip;
1417 	s = (u_char *)(tcp + 1);
1418 	off = IP_HL(ip) << 2;
1419 # ifdef _KERNEL
1420 	if (fin->fin_mp != NULL) {
1421 		mb_t *m = *fin->fin_mp;
1422 
1423 		if (off + tlen > M_LEN(m))
1424 			return;
1425 	}
1426 # endif
1427 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1428 		opt = *s;
1429 		if (opt == '\0')
1430 			break;
1431 		else if (opt == TCPOPT_NOP)
1432 			ol = 1;
1433 		else {
1434 			if (tlen < 2)
1435 				break;
1436 			ol = (int)*(s + 1);
1437 			if (ol < 2 || ol > tlen)
1438 				break;
1439 		}
1440 
1441 		for (i = 9, mv = 4; mv >= 0; ) {
1442 			op = ipopts + i;
1443 			if (opt == (u_char)op->ol_val) {
1444 				optmsk |= op->ol_bit;
1445 				break;
1446 			}
1447 		}
1448 		tlen -= ol;
1449 		s += ol;
1450 	}
1451 #endif /* 0 */
1452 
1453 	return (0);
1454 }
1455 
1456 
1457 
1458 /* ------------------------------------------------------------------------ */
1459 /* Function:    ipf_pr_udpcommon                                            */
1460 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1461 /* Parameters:  fin(I) - pointer to packet information                      */
1462 /*                                                                          */
1463 /* Extract the UDP source and destination ports, if present.  If compiled   */
1464 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1465 /* ------------------------------------------------------------------------ */
1466 static inline int
ipf_pr_udpcommon(fr_info_t * fin)1467 ipf_pr_udpcommon(fr_info_t *fin)
1468 {
1469 	udphdr_t *udp;
1470 
1471 	fin->fin_flx |= FI_TCPUDP;
1472 
1473 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1474 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1475 			ipf_main_softc_t *softc = fin->fin_main_soft;
1476 
1477 			fin->fin_flx |= FI_SHORT;
1478 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1479 			return (1);
1480 		}
1481 
1482 		udp = fin->fin_dp;
1483 
1484 		fin->fin_sport = ntohs(udp->uh_sport);
1485 		fin->fin_dport = ntohs(udp->uh_dport);
1486 	}
1487 
1488 	return (0);
1489 }
1490 
1491 
1492 /* ------------------------------------------------------------------------ */
1493 /* Function:    ipf_pr_tcp                                                  */
1494 /* Returns:     void                                                        */
1495 /* Parameters:  fin(I) - pointer to packet information                      */
1496 /*                                                                          */
1497 /* IPv4 Only                                                                */
1498 /* Analyse the packet for IPv4/TCP properties.                              */
1499 /* ------------------------------------------------------------------------ */
1500 static inline void
ipf_pr_tcp(fr_info_t * fin)1501 ipf_pr_tcp(fr_info_t *fin)
1502 {
1503 
1504 	ipf_pr_short(fin, sizeof(tcphdr_t));
1505 
1506 	if (ipf_pr_tcpcommon(fin) == 0)
1507 		ipf_checkv4sum(fin);
1508 }
1509 
1510 
1511 /* ------------------------------------------------------------------------ */
1512 /* Function:    ipf_pr_udp                                                  */
1513 /* Returns:     void                                                        */
1514 /* Parameters:  fin(I) - pointer to packet information                      */
1515 /*                                                                          */
1516 /* IPv4 Only                                                                */
1517 /* Analyse the packet for IPv4/UDP properties.                              */
1518 /* ------------------------------------------------------------------------ */
1519 static inline void
ipf_pr_udp(fr_info_t * fin)1520 ipf_pr_udp(fr_info_t *fin)
1521 {
1522 
1523 	ipf_pr_short(fin, sizeof(udphdr_t));
1524 
1525 	if (ipf_pr_udpcommon(fin) == 0)
1526 		ipf_checkv4sum(fin);
1527 }
1528 
1529 
1530 /* ------------------------------------------------------------------------ */
1531 /* Function:    ipf_pr_esp                                                  */
1532 /* Returns:     void                                                        */
1533 /* Parameters:  fin(I) - pointer to packet information                      */
1534 /*                                                                          */
1535 /* Analyse the packet for ESP properties.                                   */
1536 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1537 /* even though the newer ESP packets must also have a sequence number that  */
1538 /* is 32bits as well, it is not possible(?) to determine the version from a */
1539 /* simple packet header.                                                    */
1540 /* ------------------------------------------------------------------------ */
1541 static inline void
ipf_pr_esp(fr_info_t * fin)1542 ipf_pr_esp(fr_info_t *fin)
1543 {
1544 
1545 	if (fin->fin_off == 0) {
1546 		ipf_pr_short(fin, 8);
1547 		if (ipf_pr_pullup(fin, 8) == -1) {
1548 			ipf_main_softc_t *softc = fin->fin_main_soft;
1549 
1550 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1551 		}
1552 	}
1553 }
1554 
1555 
1556 /* ------------------------------------------------------------------------ */
1557 /* Function:    ipf_pr_ah                                                   */
1558 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1559 /* Parameters:  fin(I) - pointer to packet information                      */
1560 /*                                                                          */
1561 /* Analyse the packet for AH properties.                                    */
1562 /* The minimum length is taken to be the combination of all fields in the   */
1563 /* header being present and no authentication data (null algorithm used.)   */
1564 /* ------------------------------------------------------------------------ */
1565 static inline int
ipf_pr_ah(fr_info_t * fin)1566 ipf_pr_ah(fr_info_t *fin)
1567 {
1568 	ipf_main_softc_t *softc = fin->fin_main_soft;
1569 	authhdr_t *ah;
1570 	int len;
1571 
1572 	fin->fin_flx |= FI_AH;
1573 	ipf_pr_short(fin, sizeof(*ah));
1574 
1575 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1576 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1577 		return (IPPROTO_NONE);
1578 	}
1579 
1580 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1581 		DT(fr_v4_ah_pullup_1);
1582 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1583 		return (IPPROTO_NONE);
1584 	}
1585 
1586 	ah = (authhdr_t *)fin->fin_dp;
1587 
1588 	len = (ah->ah_plen + 2) << 2;
1589 	ipf_pr_short(fin, len);
1590 	if (ipf_pr_pullup(fin, len) == -1) {
1591 		DT(fr_v4_ah_pullup_2);
1592 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1593 		return (IPPROTO_NONE);
1594 	}
1595 
1596 	/*
1597 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
1598 	 * header.
1599 	 */
1600 	fin->fin_dp = (char *)fin->fin_dp + len;
1601 	fin->fin_dlen -= len;
1602 	return (ah->ah_next);
1603 }
1604 
1605 
1606 /* ------------------------------------------------------------------------ */
1607 /* Function:    ipf_pr_gre                                                  */
1608 /* Returns:     void                                                        */
1609 /* Parameters:  fin(I) - pointer to packet information                      */
1610 /*                                                                          */
1611 /* Analyse the packet for GRE properties.                                   */
1612 /* ------------------------------------------------------------------------ */
1613 static inline void
ipf_pr_gre(fr_info_t * fin)1614 ipf_pr_gre(fr_info_t *fin)
1615 {
1616 	ipf_main_softc_t *softc = fin->fin_main_soft;
1617 	grehdr_t *gre;
1618 
1619 	ipf_pr_short(fin, sizeof(grehdr_t));
1620 
1621 	if (fin->fin_off != 0) {
1622 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1623 		return;
1624 	}
1625 
1626 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1627 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1628 		return;
1629 	}
1630 
1631 	gre = fin->fin_dp;
1632 	if (GRE_REV(gre->gr_flags) == 1)
1633 		fin->fin_data[0] = gre->gr_call;
1634 }
1635 
1636 
1637 /* ------------------------------------------------------------------------ */
1638 /* Function:    ipf_pr_ipv4hdr                                              */
1639 /* Returns:     void                                                        */
1640 /* Parameters:  fin(I) - pointer to packet information                      */
1641 /*                                                                          */
1642 /* IPv4 Only                                                                */
1643 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1644 /* Check all options present and flag their presence if any exist.          */
1645 /* ------------------------------------------------------------------------ */
1646 static inline void
ipf_pr_ipv4hdr(fr_info_t * fin)1647 ipf_pr_ipv4hdr(fr_info_t *fin)
1648 {
1649 	u_short optmsk = 0, secmsk = 0, auth = 0;
1650 	int hlen, ol, mv, p, i;
1651 	const struct optlist *op;
1652 	u_char *s, opt;
1653 	u_short off;
1654 	fr_ip_t *fi;
1655 	ip_t *ip;
1656 
1657 	fi = &fin->fin_fi;
1658 	hlen = fin->fin_hlen;
1659 
1660 	ip = fin->fin_ip;
1661 	p = ip->ip_p;
1662 	fi->fi_p = p;
1663 	fin->fin_crc = p;
1664 	fi->fi_tos = ip->ip_tos;
1665 	fin->fin_id = ntohs(ip->ip_id);
1666 	off = ntohs(ip->ip_off);
1667 
1668 	/* Get both TTL and protocol */
1669 	fi->fi_p = ip->ip_p;
1670 	fi->fi_ttl = ip->ip_ttl;
1671 
1672 	/* Zero out bits not used in IPv6 address */
1673 	fi->fi_src.i6[1] = 0;
1674 	fi->fi_src.i6[2] = 0;
1675 	fi->fi_src.i6[3] = 0;
1676 	fi->fi_dst.i6[1] = 0;
1677 	fi->fi_dst.i6[2] = 0;
1678 	fi->fi_dst.i6[3] = 0;
1679 
1680 	fi->fi_saddr = ip->ip_src.s_addr;
1681 	fin->fin_crc += fi->fi_saddr;
1682 	fi->fi_daddr = ip->ip_dst.s_addr;
1683 	fin->fin_crc += fi->fi_daddr;
1684 	if (IN_MULTICAST(ntohl(fi->fi_daddr)))
1685 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1686 
1687 	/*
1688 	 * set packet attribute flags based on the offset and
1689 	 * calculate the byte offset that it represents.
1690 	 */
1691 	off &= IP_MF|IP_OFFMASK;
1692 	if (off != 0) {
1693 		int morefrag = off & IP_MF;
1694 
1695 		fi->fi_flx |= FI_FRAG;
1696 		off &= IP_OFFMASK;
1697 		if (off == 1 && p == IPPROTO_TCP) {
1698 			fin->fin_flx |= FI_SHORT;	/* RFC 3128 */
1699 			DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1700 		}
1701 		if (off != 0) {
1702 			fin->fin_flx |= FI_FRAGBODY;
1703 			off <<= 3;
1704 			if ((off + fin->fin_dlen > 65535) ||
1705 			    (fin->fin_dlen == 0) ||
1706 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1707 				/*
1708 				 * The length of the packet, starting at its
1709 				 * offset cannot exceed 65535 (0xffff) as the
1710 				 * length of an IP packet is only 16 bits.
1711 				 *
1712 				 * Any fragment that isn't the last fragment
1713 				 * must have a length greater than 0 and it
1714 				 * must be an even multiple of 8.
1715 				 */
1716 				fi->fi_flx |= FI_BAD;
1717 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1718 			}
1719 		}
1720 	}
1721 	fin->fin_off = off;
1722 
1723 	/*
1724 	 * Call per-protocol setup and checking
1725 	 */
1726 	if (p == IPPROTO_AH) {
1727 		/*
1728 		 * Treat AH differently because we expect there to be another
1729 		 * layer 4 header after it.
1730 		 */
1731 		p = ipf_pr_ah(fin);
1732 	}
1733 
1734 	switch (p)
1735 	{
1736 	case IPPROTO_UDP :
1737 		ipf_pr_udp(fin);
1738 		break;
1739 	case IPPROTO_TCP :
1740 		ipf_pr_tcp(fin);
1741 		break;
1742 	case IPPROTO_ICMP :
1743 		ipf_pr_icmp(fin);
1744 		break;
1745 	case IPPROTO_ESP :
1746 		ipf_pr_esp(fin);
1747 		break;
1748 	case IPPROTO_GRE :
1749 		ipf_pr_gre(fin);
1750 		break;
1751 	}
1752 
1753 	ip = fin->fin_ip;
1754 	if (ip == NULL)
1755 		return;
1756 
1757 	/*
1758 	 * If it is a standard IP header (no options), set the flag fields
1759 	 * which relate to options to 0.
1760 	 */
1761 	if (hlen == sizeof(*ip)) {
1762 		fi->fi_optmsk = 0;
1763 		fi->fi_secmsk = 0;
1764 		fi->fi_auth = 0;
1765 		return;
1766 	}
1767 
1768 	/*
1769 	 * So the IP header has some IP options attached.  Walk the entire
1770 	 * list of options present with this packet and set flags to indicate
1771 	 * which ones are here and which ones are not.  For the somewhat out
1772 	 * of date and obscure security classification options, set a flag to
1773 	 * represent which classification is present.
1774 	 */
1775 	fi->fi_flx |= FI_OPTIONS;
1776 
1777 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1778 		opt = *s;
1779 		if (opt == '\0')
1780 			break;
1781 		else if (opt == IPOPT_NOP)
1782 			ol = 1;
1783 		else {
1784 			if (hlen < 2)
1785 				break;
1786 			ol = (int)*(s + 1);
1787 			if (ol < 2 || ol > hlen)
1788 				break;
1789 		}
1790 		for (i = 9, mv = 4; mv >= 0; ) {
1791 			op = ipopts + i;
1792 
1793 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1794 				u_32_t doi;
1795 
1796 				switch (opt)
1797 				{
1798 				case IPOPT_SECURITY :
1799 					if (optmsk & op->ol_bit) {
1800 						fin->fin_flx |= FI_BAD;
1801 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1802 					} else {
1803 						doi = ipf_checkripso(s);
1804 						secmsk = doi >> 16;
1805 						auth = doi & 0xffff;
1806 					}
1807 					break;
1808 
1809 				case IPOPT_CIPSO :
1810 
1811 					if (optmsk & op->ol_bit) {
1812 						fin->fin_flx |= FI_BAD;
1813 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1814 					} else {
1815 						doi = ipf_checkcipso(fin,
1816 								     s, ol);
1817 						secmsk = doi >> 16;
1818 						auth = doi & 0xffff;
1819 					}
1820 					break;
1821 				}
1822 				optmsk |= op->ol_bit;
1823 			}
1824 
1825 			if (opt < op->ol_val)
1826 				i -= mv;
1827 			else
1828 				i += mv;
1829 			mv--;
1830 		}
1831 		hlen -= ol;
1832 		s += ol;
1833 	}
1834 
1835 	/*
1836 	 *
1837 	 */
1838 	if (auth && !(auth & 0x0100))
1839 		auth &= 0xff00;
1840 	fi->fi_optmsk = optmsk;
1841 	fi->fi_secmsk = secmsk;
1842 	fi->fi_auth = auth;
1843 }
1844 
1845 
1846 /* ------------------------------------------------------------------------ */
1847 /* Function:    ipf_checkripso                                              */
1848 /* Returns:     void                                                        */
1849 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1850 /*                                                                          */
1851 /* ------------------------------------------------------------------------ */
1852 static u_32_t
ipf_checkripso(u_char * s)1853 ipf_checkripso(u_char *s)
1854 {
1855 	const struct optlist *sp;
1856 	u_short secmsk = 0, auth = 0;
1857 	u_char sec;
1858 	int j, m;
1859 
1860 	sec = *(s + 2);	/* classification */
1861 	for (j = 3, m = 2; m >= 0; ) {
1862 		sp = secopt + j;
1863 		if (sec == sp->ol_val) {
1864 			secmsk |= sp->ol_bit;
1865 			auth = *(s + 3);
1866 			auth *= 256;
1867 			auth += *(s + 4);
1868 			break;
1869 		}
1870 		if (sec < sp->ol_val)
1871 			j -= m;
1872 		else
1873 			j += m;
1874 		m--;
1875 	}
1876 
1877 	return (secmsk << 16) | auth;
1878 }
1879 
1880 
1881 /* ------------------------------------------------------------------------ */
1882 /* Function:    ipf_checkcipso                                              */
1883 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1884 /* Parameters:  fin(IO) - pointer to packet information                     */
1885 /*              s(I)    - pointer to start of CIPSO option                  */
1886 /*              ol(I)   - length of CIPSO option field                      */
1887 /*                                                                          */
1888 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1889 /* header and returns that whilst also storing the highest sensitivity      */
1890 /* value found in the fr_info_t structure.                                  */
1891 /*                                                                          */
1892 /* No attempt is made to extract the category bitmaps as these are defined  */
1893 /* by the user (rather than the protocol) and can be rather numerous on the */
1894 /* end nodes.                                                               */
1895 /* ------------------------------------------------------------------------ */
1896 static u_32_t
ipf_checkcipso(fr_info_t * fin,u_char * s,int ol)1897 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1898 {
1899 	ipf_main_softc_t *softc = fin->fin_main_soft;
1900 	fr_ip_t *fi;
1901 	u_32_t doi;
1902 	u_char *t, tag, tlen, sensitivity;
1903 	int len;
1904 
1905 	if (ol < 6 || ol > 40) {
1906 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1907 		fin->fin_flx |= FI_BAD;
1908 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1909 		return (0);
1910 	}
1911 
1912 	fi = &fin->fin_fi;
1913 	fi->fi_sensitivity = 0;
1914 	/*
1915 	 * The DOI field MUST be there.
1916 	 */
1917 	bcopy(s + 2, &doi, sizeof(doi));
1918 
1919 	t = (u_char *)s + 6;
1920 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1921 		tag = *t;
1922 		tlen = *(t + 1);
1923 		if (tlen > len || tlen < 4 || tlen > 34) {
1924 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1925 			fin->fin_flx |= FI_BAD;
1926 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1927 			return (0);
1928 		}
1929 
1930 		sensitivity = 0;
1931 		/*
1932 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1933 		 * draft (16 July 1992) that has expired.
1934 		 */
1935 		if (tag == 0) {
1936 			fin->fin_flx |= FI_BAD;
1937 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1938 			continue;
1939 		} else if (tag == 1) {
1940 			if (*(t + 2) != 0) {
1941 				fin->fin_flx |= FI_BAD;
1942 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1943 				continue;
1944 			}
1945 			sensitivity = *(t + 3);
1946 			/* Category bitmap for categories 0-239 */
1947 
1948 		} else if (tag == 4) {
1949 			if (*(t + 2) != 0) {
1950 				fin->fin_flx |= FI_BAD;
1951 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1952 				continue;
1953 			}
1954 			sensitivity = *(t + 3);
1955 			/* Enumerated categories, 16bits each, upto 15 */
1956 
1957 		} else if (tag == 5) {
1958 			if (*(t + 2) != 0) {
1959 				fin->fin_flx |= FI_BAD;
1960 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1961 				continue;
1962 			}
1963 			sensitivity = *(t + 3);
1964 			/* Range of categories (2*16bits), up to 7 pairs */
1965 
1966 		} else if (tag > 127) {
1967 			/* Custom defined DOI */
1968 			;
1969 		} else {
1970 			fin->fin_flx |= FI_BAD;
1971 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
1972 			continue;
1973 		}
1974 
1975 		if (sensitivity > fi->fi_sensitivity)
1976 			fi->fi_sensitivity = sensitivity;
1977 	}
1978 
1979 	return (doi);
1980 }
1981 
1982 
1983 /* ------------------------------------------------------------------------ */
1984 /* Function:    ipf_makefrip                                                */
1985 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
1986 /* Parameters:  hlen(I) - length of IP packet header                        */
1987 /*              ip(I)   - pointer to the IP header                          */
1988 /*              fin(IO) - pointer to packet information                     */
1989 /*                                                                          */
1990 /* Compact the IP header into a structure which contains just the info.     */
1991 /* which is useful for comparing IP headers with and store this information */
1992 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
1993 /* this function will be called with either an IPv4 or IPv6 packet.         */
1994 /* ------------------------------------------------------------------------ */
1995 int
ipf_makefrip(int hlen,ip_t * ip,fr_info_t * fin)1996 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
1997 {
1998 	ipf_main_softc_t *softc = fin->fin_main_soft;
1999 	int v;
2000 
2001 	fin->fin_depth = 0;
2002 	fin->fin_hlen = (u_short)hlen;
2003 	fin->fin_ip = ip;
2004 	fin->fin_rule = 0xffffffff;
2005 	fin->fin_group[0] = -1;
2006 	fin->fin_group[1] = '\0';
2007 	fin->fin_dp = (char *)ip + hlen;
2008 
2009 	v = fin->fin_v;
2010 	if (v == 4) {
2011 		fin->fin_plen = ntohs(ip->ip_len);
2012 		fin->fin_dlen = fin->fin_plen - hlen;
2013 		ipf_pr_ipv4hdr(fin);
2014 #ifdef	USE_INET6
2015 	} else if (v == 6) {
2016 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2017 		fin->fin_dlen = fin->fin_plen;
2018 		fin->fin_plen += hlen;
2019 
2020 		ipf_pr_ipv6hdr(fin);
2021 #endif
2022 	}
2023 	if (fin->fin_ip == NULL) {
2024 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2025 		return (-1);
2026 	}
2027 	return (0);
2028 }
2029 
2030 
2031 /* ------------------------------------------------------------------------ */
2032 /* Function:    ipf_portcheck                                               */
2033 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2034 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2035 /*              pop(I) - port number to evaluate                            */
2036 /*                                                                          */
2037 /* Perform a comparison of a port number against some other(s), using a     */
2038 /* structure with compare information stored in it.                         */
2039 /* ------------------------------------------------------------------------ */
2040 static inline int
ipf_portcheck(frpcmp_t * frp,u_32_t pop)2041 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2042 {
2043 	int err = 1;
2044 	u_32_t po;
2045 
2046 	po = frp->frp_port;
2047 
2048 	/*
2049 	 * Do opposite test to that required and continue if that succeeds.
2050 	 */
2051 	switch (frp->frp_cmp)
2052 	{
2053 	case FR_EQUAL :
2054 		if (pop != po) /* EQUAL */
2055 			err = 0;
2056 		break;
2057 	case FR_NEQUAL :
2058 		if (pop == po) /* NOTEQUAL */
2059 			err = 0;
2060 		break;
2061 	case FR_LESST :
2062 		if (pop >= po) /* LESSTHAN */
2063 			err = 0;
2064 		break;
2065 	case FR_GREATERT :
2066 		if (pop <= po) /* GREATERTHAN */
2067 			err = 0;
2068 		break;
2069 	case FR_LESSTE :
2070 		if (pop > po) /* LT or EQ */
2071 			err = 0;
2072 		break;
2073 	case FR_GREATERTE :
2074 		if (pop < po) /* GT or EQ */
2075 			err = 0;
2076 		break;
2077 	case FR_OUTRANGE :
2078 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
2079 			err = 0;
2080 		break;
2081 	case FR_INRANGE :
2082 		if (pop <= po || pop >= frp->frp_top) /* In range */
2083 			err = 0;
2084 		break;
2085 	case FR_INCRANGE :
2086 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
2087 			err = 0;
2088 		break;
2089 	default :
2090 		break;
2091 	}
2092 	return (err);
2093 }
2094 
2095 
2096 /* ------------------------------------------------------------------------ */
2097 /* Function:    ipf_tcpudpchk                                               */
2098 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2099 /* Parameters:  fda(I) - pointer to packet information                      */
2100 /*              ft(I)  - pointer to structure with comparison data          */
2101 /*                                                                          */
2102 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2103 /* structure containing information that we want to match against.          */
2104 /* ------------------------------------------------------------------------ */
2105 int
ipf_tcpudpchk(fr_ip_t * fi,frtuc_t * ft)2106 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2107 {
2108 	int err = 1;
2109 
2110 	/*
2111 	 * Both ports should *always* be in the first fragment.
2112 	 * So far, I cannot find any cases where they can not be.
2113 	 *
2114 	 * compare destination ports
2115 	 */
2116 	if (ft->ftu_dcmp)
2117 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2118 
2119 	/*
2120 	 * compare source ports
2121 	 */
2122 	if (err && ft->ftu_scmp)
2123 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2124 
2125 	/*
2126 	 * If we don't have all the TCP/UDP header, then how can we
2127 	 * expect to do any sort of match on it ?  If we were looking for
2128 	 * TCP flags, then NO match.  If not, then match (which should
2129 	 * satisfy the "short" class too).
2130 	 */
2131 	if (err && (fi->fi_p == IPPROTO_TCP)) {
2132 		if (fi->fi_flx & FI_SHORT)
2133 			return (!(ft->ftu_tcpf | ft->ftu_tcpfm));
2134 		/*
2135 		 * Match the flags ?  If not, abort this match.
2136 		 */
2137 		if (ft->ftu_tcpfm &&
2138 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2139 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2140 				 ft->ftu_tcpfm, ft->ftu_tcpf));
2141 			err = 0;
2142 		}
2143 	}
2144 	return (err);
2145 }
2146 
2147 
2148 /* ------------------------------------------------------------------------ */
2149 /* Function:    ipf_check_ipf                                               */
2150 /* Returns:     int - 0 == match, else no match                             */
2151 /* Parameters:  fin(I)     - pointer to packet information                  */
2152 /*              fr(I)      - pointer to filter rule                         */
2153 /*              portcmp(I) - flag indicating whether to attempt matching on */
2154 /*                           TCP/UDP port data.                             */
2155 /*                                                                          */
2156 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2157 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2158 /* this function.                                                           */
2159 /* ------------------------------------------------------------------------ */
2160 static inline int
ipf_check_ipf(fr_info_t * fin,frentry_t * fr,int portcmp)2161 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2162 {
2163 	u_32_t	*ld, *lm, *lip;
2164 	fripf_t *fri;
2165 	fr_ip_t *fi;
2166 	int i;
2167 
2168 	fi = &fin->fin_fi;
2169 	fri = fr->fr_ipf;
2170 	lip = (u_32_t *)fi;
2171 	lm = (u_32_t *)&fri->fri_mip;
2172 	ld = (u_32_t *)&fri->fri_ip;
2173 
2174 	/*
2175 	 * first 32 bits to check coversion:
2176 	 * IP version, TOS, TTL, protocol
2177 	 */
2178 	i = ((*lip & *lm) != *ld);
2179 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2180 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2181 	if (i)
2182 		return (1);
2183 
2184 	/*
2185 	 * Next 32 bits is a constructed bitmask indicating which IP options
2186 	 * are present (if any) in this packet.
2187 	 */
2188 	lip++, lm++, ld++;
2189 	i = ((*lip & *lm) != *ld);
2190 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2191 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2192 	if (i != 0)
2193 		return (1);
2194 
2195 	lip++, lm++, ld++;
2196 	/*
2197 	 * Unrolled loops (4 each, for 32 bits) for address checks.
2198 	 */
2199 	/*
2200 	 * Check the source address.
2201 	 */
2202 	if (fr->fr_satype == FRI_LOOKUP) {
2203 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2204 				      fi->fi_v, lip, fin->fin_plen);
2205 		if (i == -1)
2206 			return (1);
2207 		lip += 3;
2208 		lm += 3;
2209 		ld += 3;
2210 	} else {
2211 		i = ((*lip & *lm) != *ld);
2212 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2213 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2214 		if (fi->fi_v == 6) {
2215 			lip++, lm++, ld++;
2216 			i |= ((*lip & *lm) != *ld);
2217 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2218 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2219 			lip++, lm++, ld++;
2220 			i |= ((*lip & *lm) != *ld);
2221 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2222 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2223 			lip++, lm++, ld++;
2224 			i |= ((*lip & *lm) != *ld);
2225 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2226 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2227 		} else {
2228 			lip += 3;
2229 			lm += 3;
2230 			ld += 3;
2231 		}
2232 	}
2233 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2234 	if (i != 0)
2235 		return (1);
2236 
2237 	/*
2238 	 * Check the destination address.
2239 	 */
2240 	lip++, lm++, ld++;
2241 	if (fr->fr_datype == FRI_LOOKUP) {
2242 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2243 				      fi->fi_v, lip, fin->fin_plen);
2244 		if (i == -1)
2245 			return (1);
2246 		lip += 3;
2247 		lm += 3;
2248 		ld += 3;
2249 	} else {
2250 		i = ((*lip & *lm) != *ld);
2251 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2252 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2253 		if (fi->fi_v == 6) {
2254 			lip++, lm++, ld++;
2255 			i |= ((*lip & *lm) != *ld);
2256 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2257 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2258 			lip++, lm++, ld++;
2259 			i |= ((*lip & *lm) != *ld);
2260 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2261 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262 			lip++, lm++, ld++;
2263 			i |= ((*lip & *lm) != *ld);
2264 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2265 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2266 		} else {
2267 			lip += 3;
2268 			lm += 3;
2269 			ld += 3;
2270 		}
2271 	}
2272 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2273 	if (i != 0)
2274 		return (1);
2275 	/*
2276 	 * IP addresses matched.  The next 32bits contains:
2277 	 * mast of old IP header security & authentication bits.
2278 	 */
2279 	lip++, lm++, ld++;
2280 	i = (*ld - (*lip & *lm));
2281 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2282 
2283 	/*
2284 	 * Next we have 32 bits of packet flags.
2285 	 */
2286 	lip++, lm++, ld++;
2287 	i |= (*ld - (*lip & *lm));
2288 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2289 
2290 	if (i == 0) {
2291 		/*
2292 		 * If a fragment, then only the first has what we're
2293 		 * looking for here...
2294 		 */
2295 		if (portcmp) {
2296 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2297 				i = 1;
2298 		} else {
2299 			if (fr->fr_dcmp || fr->fr_scmp ||
2300 			    fr->fr_tcpf || fr->fr_tcpfm)
2301 				i = 1;
2302 			if (fr->fr_icmpm || fr->fr_icmp) {
2303 				if (((fi->fi_p != IPPROTO_ICMP) &&
2304 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
2305 				    fin->fin_off || (fin->fin_dlen < 2))
2306 					i = 1;
2307 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2308 					 fr->fr_icmp) {
2309 					FR_DEBUG(("i. %#x & %#x != %#x\n",
2310 						 fin->fin_data[0],
2311 						 fr->fr_icmpm, fr->fr_icmp));
2312 					i = 1;
2313 				}
2314 			}
2315 		}
2316 	}
2317 	return (i);
2318 }
2319 
2320 
2321 /* ------------------------------------------------------------------------ */
2322 /* Function:    ipf_scanlist                                                */
2323 /* Returns:     int - result flags of scanning filter list                  */
2324 /* Parameters:  fin(I) - pointer to packet information                      */
2325 /*              pass(I) - default result to return for filtering            */
2326 /*                                                                          */
2327 /* Check the input/output list of rules for a match to the current packet.  */
2328 /* If a match is found, the value of fr_flags from the rule becomes the     */
2329 /* return value and fin->fin_fr points to the matched rule.                 */
2330 /*                                                                          */
2331 /* This function may be called recursively upto 16 times (limit inbuilt.)   */
2332 /* When unwinding, it should finish up with fin_depth as 0.                 */
2333 /*                                                                          */
2334 /* Could be per interface, but this gets real nasty when you don't have,    */
2335 /* or can't easily change, the kernel source code to .                      */
2336 /* ------------------------------------------------------------------------ */
2337 int
ipf_scanlist(fr_info_t * fin,u_32_t pass)2338 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2339 {
2340 	ipf_main_softc_t *softc = fin->fin_main_soft;
2341 	int rulen, portcmp, off, skip;
2342 	struct frentry *fr, *fnext;
2343 	u_32_t passt, passo;
2344 
2345 	/*
2346 	 * Do not allow nesting deeper than 16 levels.
2347 	 */
2348 	if (fin->fin_depth >= 16)
2349 		return (pass);
2350 
2351 	fr = fin->fin_fr;
2352 
2353 	/*
2354 	* If there are no rules in this list, return now.
2355 	 */
2356 	if (fr == NULL)
2357 		return (pass);
2358 
2359 	skip = 0;
2360 	portcmp = 0;
2361 	fin->fin_depth++;
2362 	fin->fin_fr = NULL;
2363 	off = fin->fin_off;
2364 
2365 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2366 		portcmp = 1;
2367 
2368 	for (rulen = 0; fr; fr = fnext, rulen++) {
2369 		fnext = fr->fr_next;
2370 		if (skip != 0) {
2371 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2372 			skip--;
2373 			continue;
2374 		}
2375 
2376 		/*
2377 		 * In all checks below, a null (zero) value in the
2378 		 * filter struture is taken to mean a wildcard.
2379 		 *
2380 		 * check that we are working for the right interface
2381 		 */
2382 #ifdef	_KERNEL
2383 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2384 			continue;
2385 #else
2386 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
2387 			printf("\n");
2388 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2389 				  FR_ISPASS(pass) ? 'p' :
2390 				  FR_ISACCOUNT(pass) ? 'A' :
2391 				  FR_ISAUTH(pass) ? 'a' :
2392 				  (pass & FR_NOMATCH) ? 'n' :'b'));
2393 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2394 			continue;
2395 		FR_VERBOSE((":i"));
2396 #endif
2397 
2398 		switch (fr->fr_type)
2399 		{
2400 		case FR_T_IPF :
2401 		case FR_T_IPF_BUILTIN :
2402 			if (ipf_check_ipf(fin, fr, portcmp))
2403 				continue;
2404 			break;
2405 #if defined(IPFILTER_BPF)
2406 		case FR_T_BPFOPC :
2407 		case FR_T_BPFOPC_BUILTIN :
2408 		    {
2409 			u_char *mc;
2410 			int wlen;
2411 
2412 			if (*fin->fin_mp == NULL)
2413 				continue;
2414 			if (fin->fin_family != fr->fr_family)
2415 				continue;
2416 			mc = (u_char *)fin->fin_m;
2417 			wlen = fin->fin_dlen + fin->fin_hlen;
2418 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2419 				continue;
2420 			break;
2421 		    }
2422 #endif
2423 		case FR_T_CALLFUNC_BUILTIN :
2424 		    {
2425 			frentry_t *f;
2426 
2427 			f = (*fr->fr_func)(fin, &pass);
2428 			if (f != NULL)
2429 				fr = f;
2430 			else
2431 				continue;
2432 			break;
2433 		    }
2434 
2435 		case FR_T_IPFEXPR :
2436 		case FR_T_IPFEXPR_BUILTIN :
2437 			if (fin->fin_family != fr->fr_family)
2438 				continue;
2439 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2440 				continue;
2441 			break;
2442 
2443 		default :
2444 			break;
2445 		}
2446 
2447 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2448 			if (fin->fin_nattag == NULL)
2449 				continue;
2450 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2451 				continue;
2452 		}
2453 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2454 
2455 		passt = fr->fr_flags;
2456 
2457 		/*
2458 		 * If the rule is a "call now" rule, then call the function
2459 		 * in the rule, if it exists and use the results from that.
2460 		 * If the function pointer is bad, just make like we ignore
2461 		 * it, except for increasing the hit counter.
2462 		 */
2463 		if ((passt & FR_CALLNOW) != 0) {
2464 			frentry_t *frs;
2465 
2466 			ATOMIC_INC64(fr->fr_hits);
2467 			if ((fr->fr_func == NULL) ||
2468 			    (fr->fr_func == (ipfunc_t)-1))
2469 				continue;
2470 
2471 			frs = fin->fin_fr;
2472 			fin->fin_fr = fr;
2473 			fr = (*fr->fr_func)(fin, &passt);
2474 			if (fr == NULL) {
2475 				fin->fin_fr = frs;
2476 				continue;
2477 			}
2478 			passt = fr->fr_flags;
2479 		}
2480 		fin->fin_fr = fr;
2481 
2482 #ifdef  IPFILTER_LOG
2483 		/*
2484 		 * Just log this packet...
2485 		 */
2486 		if ((passt & FR_LOGMASK) == FR_LOG) {
2487 			if (ipf_log_pkt(fin, passt) == -1) {
2488 				if (passt & FR_LOGORBLOCK) {
2489 					DT(frb_logfail);
2490 					passt &= ~FR_CMDMASK;
2491 					passt |= FR_BLOCK|FR_QUICK;
2492 					fin->fin_reason = FRB_LOGFAIL;
2493 				}
2494 			}
2495 		}
2496 #endif /* IPFILTER_LOG */
2497 
2498 		MUTEX_ENTER(&fr->fr_lock);
2499 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2500 		fr->fr_hits++;
2501 		MUTEX_EXIT(&fr->fr_lock);
2502 		fin->fin_rule = rulen;
2503 
2504 		passo = pass;
2505 		if (FR_ISSKIP(passt)) {
2506 			skip = fr->fr_arg;
2507 			continue;
2508 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
2509 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2510 			pass = passt;
2511 		}
2512 
2513 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2514 			fin->fin_icode = fr->fr_icode;
2515 
2516 		if (fr->fr_group != -1) {
2517 			(void) strncpy(fin->fin_group,
2518 				       FR_NAME(fr, fr_group),
2519 				       strlen(FR_NAME(fr, fr_group)));
2520 		} else {
2521 			fin->fin_group[0] = '\0';
2522 		}
2523 
2524 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2525 
2526 		if (fr->fr_grphead != NULL) {
2527 			fin->fin_fr = fr->fr_grphead->fg_start;
2528 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2529 
2530 			if (FR_ISDECAPS(passt))
2531 				passt = ipf_decaps(fin, pass, fr->fr_icode);
2532 			else
2533 				passt = ipf_scanlist(fin, pass);
2534 
2535 			if (fin->fin_fr == NULL) {
2536 				fin->fin_rule = rulen;
2537 				if (fr->fr_group != -1)
2538 					(void) strncpy(fin->fin_group,
2539 						       fr->fr_names +
2540 						       fr->fr_group,
2541 						       strlen(fr->fr_names +
2542 							      fr->fr_group));
2543 				fin->fin_fr = fr;
2544 				passt = pass;
2545 			}
2546 			pass = passt;
2547 		}
2548 
2549 		if (pass & FR_QUICK) {
2550 			/*
2551 			 * Finally, if we've asked to track state for this
2552 			 * packet, set it up.  Add state for "quick" rules
2553 			 * here so that if the action fails we can consider
2554 			 * the rule to "not match" and keep on processing
2555 			 * filter rules.
2556 			 */
2557 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2558 			    !(fin->fin_flx & FI_STATE)) {
2559 				int out = fin->fin_out;
2560 
2561 				fin->fin_fr = fr;
2562 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2563 					LBUMPD(ipf_stats[out], fr_ads);
2564 				} else {
2565 					LBUMPD(ipf_stats[out], fr_bads);
2566 					pass = passo;
2567 					continue;
2568 				}
2569 			}
2570 			break;
2571 		}
2572 	}
2573 	fin->fin_depth--;
2574 	return (pass);
2575 }
2576 
2577 
2578 /* ------------------------------------------------------------------------ */
2579 /* Function:    ipf_acctpkt                                                 */
2580 /* Returns:     frentry_t* - always returns NULL                            */
2581 /* Parameters:  fin(I) - pointer to packet information                      */
2582 /*              passp(IO) - pointer to current/new filter decision (unused) */
2583 /*                                                                          */
2584 /* Checks a packet against accounting rules, if there are any for the given */
2585 /* IP protocol version.                                                     */
2586 /*                                                                          */
2587 /* N.B.: this function returns NULL to match the prototype used by other    */
2588 /* functions called from the IPFilter "mainline" in ipf_check().            */
2589 /* ------------------------------------------------------------------------ */
2590 frentry_t *
ipf_acctpkt(fr_info_t * fin,u_32_t * passp __unused)2591 ipf_acctpkt(fr_info_t *fin, u_32_t *passp __unused)
2592 {
2593 	ipf_main_softc_t *softc = fin->fin_main_soft;
2594 	char group[FR_GROUPLEN];
2595 	frentry_t *fr, *frsave;
2596 	u_32_t pass, rulen;
2597 
2598 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2599 
2600 	if (fr != NULL) {
2601 		frsave = fin->fin_fr;
2602 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2603 		rulen = fin->fin_rule;
2604 		fin->fin_fr = fr;
2605 		pass = ipf_scanlist(fin, FR_NOMATCH);
2606 		if (FR_ISACCOUNT(pass)) {
2607 			LBUMPD(ipf_stats[0], fr_acct);
2608 		}
2609 		fin->fin_fr = frsave;
2610 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2611 		fin->fin_rule = rulen;
2612 	}
2613 	return (NULL);
2614 }
2615 
2616 
2617 /* ------------------------------------------------------------------------ */
2618 /* Function:    ipf_firewall                                                */
2619 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2620 /*                           were found, returns NULL.                      */
2621 /* Parameters:  fin(I) - pointer to packet information                      */
2622 /*              passp(IO) - pointer to current/new filter decision (unused) */
2623 /*                                                                          */
2624 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2625 /* there are any matches.  The first check is to see if a match can be seen */
2626 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2627 /* matching rule is found, take any appropriate actions as defined by the   */
2628 /* rule - except logging.                                                   */
2629 /* ------------------------------------------------------------------------ */
2630 static frentry_t *
ipf_firewall(fr_info_t * fin,u_32_t * passp)2631 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2632 {
2633 	ipf_main_softc_t *softc = fin->fin_main_soft;
2634 	frentry_t *fr;
2635 	u_32_t pass;
2636 	int out;
2637 
2638 	out = fin->fin_out;
2639 	pass = *passp;
2640 
2641 	/*
2642 	 * This rule cache will only affect packets that are not being
2643 	 * statefully filtered.
2644 	 */
2645 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2646 	if (fin->fin_fr != NULL)
2647 		pass = ipf_scanlist(fin, softc->ipf_pass);
2648 
2649 	if ((pass & FR_NOMATCH)) {
2650 		LBUMPD(ipf_stats[out], fr_nom);
2651 	}
2652 	fr = fin->fin_fr;
2653 
2654 	/*
2655 	 * Apply packets per second rate-limiting to a rule as required.
2656 	 */
2657 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2658 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2659 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2660 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2661 		pass |= FR_BLOCK;
2662 		LBUMPD(ipf_stats[out], fr_ppshit);
2663 		fin->fin_reason = FRB_PPSRATE;
2664 	}
2665 
2666 	/*
2667 	 * If we fail to add a packet to the authorization queue, then we
2668 	 * drop the packet later.  However, if it was added then pretend
2669 	 * we've dropped it already.
2670 	 */
2671 	if (FR_ISAUTH(pass)) {
2672 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
2673 			DT1(frb_authnew, fr_info_t *, fin);
2674 			fin->fin_m = *fin->fin_mp = NULL;
2675 			fin->fin_reason = FRB_AUTHNEW;
2676 			fin->fin_error = 0;
2677 		} else {
2678 			IPFERROR(1);
2679 			fin->fin_error = ENOSPC;
2680 		}
2681 	}
2682 
2683 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2684 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2685 		(void) (*fr->fr_func)(fin, &pass);
2686 
2687 	/*
2688 	 * If a rule is a pre-auth rule, check again in the list of rules
2689 	 * loaded for authenticated use.  It does not particulary matter
2690 	 * if this search fails because a "preauth" result, from a rule,
2691 	 * is treated as "not a pass", hence the packet is blocked.
2692 	 */
2693 	if (FR_ISPREAUTH(pass)) {
2694 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
2695 	}
2696 
2697 	/*
2698 	 * If the rule has "keep frag" and the packet is actually a fragment,
2699 	 * then create a fragment state entry.
2700 	 */
2701 	if (pass & FR_KEEPFRAG) {
2702 		if (fin->fin_flx & FI_FRAG) {
2703 			if (ipf_frag_new(softc, fin, pass) == -1) {
2704 				LBUMP(ipf_stats[out].fr_bnfr);
2705 			} else {
2706 				LBUMP(ipf_stats[out].fr_nfr);
2707 			}
2708 		} else {
2709 			LBUMP(ipf_stats[out].fr_cfr);
2710 		}
2711 	}
2712 
2713 	fr = fin->fin_fr;
2714 	*passp = pass;
2715 
2716 	return (fr);
2717 }
2718 
2719 
2720 /* ------------------------------------------------------------------------ */
2721 /* Function:    ipf_check                                                   */
2722 /* Returns:     int -  0 == packet allowed through,                         */
2723 /*              User space:                                                 */
2724 /*                    -1 == packet blocked                                  */
2725 /*                     1 == packet not matched                              */
2726 /*                    -2 == requires authentication                         */
2727 /*              Kernel:                                                     */
2728 /*                   > 0 == filter error # for packet                       */
2729 /* Parameters: ctx(I)  - pointer to the instance context                    */
2730 /*             ip(I)   - pointer to start of IPv4/6 packet                  */
2731 /*             hlen(I) - length of header                                   */
2732 /*             ifp(I)  - pointer to interface this packet is on             */
2733 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2734 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2735 /*                       IP packet.                                         */
2736 /* Solaris:                                                                 */
2737 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2738 /*                       interface & direction.                             */
2739 /*                                                                          */
2740 /* ipf_check() is the master function for all IPFilter packet processing.   */
2741 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2742 /* authorisation (or pre-authorisation), presence of related state info.,   */
2743 /* generating log entries, IP packet accounting, routing of packets as      */
2744 /* directed by firewall rules and of course whether or not to allow the     */
2745 /* packet to be further processed by the kernel.                            */
2746 /*                                                                          */
2747 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2748 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2749 /* by "mp" changed to a new buffer.                                         */
2750 /* ------------------------------------------------------------------------ */
2751 int
ipf_check(void * ctx,ip_t * ip,int hlen,struct ifnet * ifp,int out,void * qif,mb_t ** mp)2752 ipf_check(void *ctx, ip_t *ip, int hlen, struct ifnet *ifp, int out
2753 #if defined(_KERNEL) && SOLARIS
2754 	, void* qif, mb_t **mp)
2755 #else
2756 	, mb_t **mp)
2757 #endif
2758 {
2759 	/*
2760 	 * The above really sucks, but short of writing a diff
2761 	 */
2762 	ipf_main_softc_t *softc = ctx;
2763 	fr_info_t frinfo;
2764 	fr_info_t *fin = &frinfo;
2765 	u_32_t pass = softc->ipf_pass;
2766 	frentry_t *fr = NULL;
2767 	int v = IP_V(ip);
2768 	mb_t *mc = NULL;
2769 	mb_t *m;
2770 	/*
2771 	 * The first part of ipf_check() deals with making sure that what goes
2772 	 * into the filtering engine makes some sense.  Information about the
2773 	 * the packet is distilled, collected into a fr_info_t structure and
2774 	 * the an attempt to ensure the buffer the packet is in is big enough
2775 	 * to hold all the required packet headers.
2776 	 */
2777 #ifdef	_KERNEL
2778 # if SOLARIS
2779 	qpktinfo_t *qpi = qif;
2780 
2781 #  ifdef __sparc
2782 	if ((u_int)ip & 0x3)
2783 		return (2);
2784 #  endif
2785 # else
2786 	SPL_INT(s);
2787 # endif
2788 
2789 	if (softc->ipf_running <= 0) {
2790 		return (0);
2791 	}
2792 
2793 	bzero((char *)fin, sizeof(*fin));
2794 
2795 # if SOLARIS
2796 	if (qpi->qpi_flags & QF_BROADCAST)
2797 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2798 	if (qpi->qpi_flags & QF_MULTICAST)
2799 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2800 	m = qpi->qpi_m;
2801 	fin->fin_qfm = m;
2802 	fin->fin_qpi = qpi;
2803 # else /* SOLARIS */
2804 
2805 	m = *mp;
2806 
2807 #  if defined(M_MCAST)
2808 	if ((m->m_flags & M_MCAST) != 0)
2809 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2810 #  endif
2811 #  if defined(M_MLOOP)
2812 	if ((m->m_flags & M_MLOOP) != 0)
2813 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2814 #  endif
2815 #  if defined(M_BCAST)
2816 	if ((m->m_flags & M_BCAST) != 0)
2817 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2818 #  endif
2819 #  ifdef M_CANFASTFWD
2820 	/*
2821 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2822 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2823 	 * XXX get a "can-fast-forward" filter rule.
2824 	 */
2825 	m->m_flags &= ~M_CANFASTFWD;
2826 #  endif /* M_CANFASTFWD */
2827 #  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD__)
2828 	/*
2829 	 * disable delayed checksums.
2830 	 */
2831 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2832 		in_delayed_cksum(m);
2833 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2834 	}
2835 #  endif /* CSUM_DELAY_DATA */
2836 # endif /* SOLARIS */
2837 #else
2838 	bzero((char *)fin, sizeof(*fin));
2839 	m = *mp;
2840 # if defined(M_MCAST)
2841 	if ((m->m_flags & M_MCAST) != 0)
2842 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2843 # endif
2844 # if defined(M_MLOOP)
2845 	if ((m->m_flags & M_MLOOP) != 0)
2846 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2847 # endif
2848 # if defined(M_BCAST)
2849 	if ((m->m_flags & M_BCAST) != 0)
2850 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2851 # endif
2852 #endif /* _KERNEL */
2853 
2854 	fin->fin_v = v;
2855 	fin->fin_m = m;
2856 	fin->fin_ip = ip;
2857 	fin->fin_mp = mp;
2858 	fin->fin_out = out;
2859 	fin->fin_ifp = ifp;
2860 	fin->fin_error = ENETUNREACH;
2861 	fin->fin_hlen = (u_short)hlen;
2862 	fin->fin_dp = (char *)ip + hlen;
2863 	fin->fin_main_soft = softc;
2864 
2865 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2866 
2867 	SPL_NET(s);
2868 
2869 #ifdef	USE_INET6
2870 	if (v == 6) {
2871 		LBUMP(ipf_stats[out].fr_ipv6);
2872 		/*
2873 		 * Jumbo grams are quite likely too big for internal buffer
2874 		 * structures to handle comfortably, for now, so just drop
2875 		 * them.
2876 		 */
2877 		if (((ip6_t *)ip)->ip6_plen == 0) {
2878 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2879 			pass = FR_BLOCK|FR_NOMATCH;
2880 			fin->fin_reason = FRB_JUMBO;
2881 			goto finished;
2882 		}
2883 		fin->fin_family = AF_INET6;
2884 	} else
2885 #endif
2886 	{
2887 		fin->fin_family = AF_INET;
2888 	}
2889 
2890 	if (ipf_makefrip(hlen, ip, fin) == -1) {
2891 		DT1(frb_makefrip, fr_info_t *, fin);
2892 		pass = FR_BLOCK|FR_NOMATCH;
2893 		fin->fin_reason = FRB_MAKEFRIP;
2894 		goto finished;
2895 	}
2896 
2897 	/*
2898 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2899 	 * becomes NULL and so we have no packet to free.
2900 	 */
2901 	if (*fin->fin_mp == NULL)
2902 		goto finished;
2903 
2904 	if (!out) {
2905 		if (v == 4) {
2906 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2907 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
2908 				fin->fin_flx |= FI_BADSRC;
2909 			}
2910 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2911 				LBUMPD(ipf_stats[0], fr_v4_badttl);
2912 				fin->fin_flx |= FI_LOWTTL;
2913 			}
2914 		}
2915 #ifdef USE_INET6
2916 		else  if (v == 6) {
2917 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2918 				LBUMPD(ipf_stats[0], fr_v6_badttl);
2919 				fin->fin_flx |= FI_LOWTTL;
2920 			}
2921 		}
2922 #endif
2923 	}
2924 
2925 	if (fin->fin_flx & FI_SHORT) {
2926 		LBUMPD(ipf_stats[out], fr_short);
2927 	}
2928 
2929 	READ_ENTER(&softc->ipf_mutex);
2930 
2931 	if (!out) {
2932 		switch (fin->fin_v)
2933 		{
2934 		case 4 :
2935 			if (ipf_nat_checkin(fin, &pass) == -1) {
2936 				goto filterdone;
2937 			}
2938 			break;
2939 #ifdef USE_INET6
2940 		case 6 :
2941 			if (ipf_nat6_checkin(fin, &pass) == -1) {
2942 				goto filterdone;
2943 			}
2944 			break;
2945 #endif
2946 		default :
2947 			break;
2948 		}
2949 	}
2950 	/*
2951 	 * Check auth now.
2952 	 * If a packet is found in the auth table, then skip checking
2953 	 * the access lists for permission but we do need to consider
2954 	 * the result as if it were from the ACL's.  In addition, being
2955 	 * found in the auth table means it has been seen before, so do
2956 	 * not pass it through accounting (again), lest it be counted twice.
2957 	 */
2958 	fr = ipf_auth_check(fin, &pass);
2959 	if (!out && (fr == NULL))
2960 		(void) ipf_acctpkt(fin, NULL);
2961 
2962 	if (fr == NULL) {
2963 		if ((fin->fin_flx & FI_FRAG) != 0)
2964 			fr = ipf_frag_known(fin, &pass);
2965 
2966 		if (fr == NULL)
2967 			fr = ipf_state_check(fin, &pass);
2968 	}
2969 
2970 	if ((pass & FR_NOMATCH) || (fr == NULL))
2971 		fr = ipf_firewall(fin, &pass);
2972 
2973 	/*
2974 	 * If we've asked to track state for this packet, set it up.
2975 	 * Here rather than ipf_firewall because ipf_checkauth may decide
2976 	* to return a packet for "keep state"
2977 	 */
2978 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
2979 	    !(fin->fin_flx & FI_STATE)) {
2980 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2981 			LBUMP(ipf_stats[out].fr_ads);
2982 		} else {
2983 			LBUMP(ipf_stats[out].fr_bads);
2984 			if (FR_ISPASS(pass)) {
2985 				DT(frb_stateadd);
2986 				pass &= ~FR_CMDMASK;
2987 				pass |= FR_BLOCK;
2988 				fin->fin_reason = FRB_STATEADD;
2989 			}
2990 		}
2991 	}
2992 
2993 	fin->fin_fr = fr;
2994 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
2995 		fin->fin_dif = &fr->fr_dif;
2996 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
2997 	}
2998 
2999 	/*
3000 	 * Only count/translate packets which will be passed on, out the
3001 	 * interface.
3002 	 */
3003 	if (out && FR_ISPASS(pass)) {
3004 		(void) ipf_acctpkt(fin, NULL);
3005 
3006 		switch (fin->fin_v)
3007 		{
3008 		case 4 :
3009 			if (ipf_nat_checkout(fin, &pass) == -1) {
3010 				;
3011 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3012 				if (ipf_updateipid(fin) == -1) {
3013 					DT(frb_updateipid);
3014 					LBUMP(ipf_stats[1].fr_ipud);
3015 					pass &= ~FR_CMDMASK;
3016 					pass |= FR_BLOCK;
3017 					fin->fin_reason = FRB_UPDATEIPID;
3018 				} else {
3019 					LBUMP(ipf_stats[0].fr_ipud);
3020 				}
3021 			}
3022 			break;
3023 #ifdef USE_INET6
3024 		case 6 :
3025 			(void) ipf_nat6_checkout(fin, &pass);
3026 			break;
3027 #endif
3028 		default :
3029 			break;
3030 		}
3031 	}
3032 
3033 filterdone:
3034 #ifdef	IPFILTER_LOG
3035 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3036 		(void) ipf_dolog(fin, &pass);
3037 	}
3038 #endif
3039 
3040 	/*
3041 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
3042 	 * will work when called from inside of fr_fastroute.  Although
3043 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
3044 	 * impact on code execution.
3045 	 */
3046 	fin->fin_flx &= ~FI_STATE;
3047 
3048 #if defined(FASTROUTE_RECURSION)
3049 	/*
3050 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3051 	 * a packet below can sometimes cause a recursive call into IPFilter.
3052 	 * On those platforms where that does happen, we need to hang onto
3053 	 * the filter rule just in case someone decides to remove or flush it
3054 	 * in the meantime.
3055 	 */
3056 	if (fr != NULL) {
3057 		MUTEX_ENTER(&fr->fr_lock);
3058 		fr->fr_ref++;
3059 		MUTEX_EXIT(&fr->fr_lock);
3060 	}
3061 
3062 	RWLOCK_EXIT(&softc->ipf_mutex);
3063 #endif
3064 
3065 	if ((pass & FR_RETMASK) != 0) {
3066 		/*
3067 		* Should we return an ICMP packet to indicate error
3068 		 * status passing through the packet filter ?
3069 		 * WARNING: ICMP error packets AND TCP RST packets should
3070 		 * ONLY be sent in repsonse to incoming packets.  Sending
3071 		 * them in response to outbound packets can result in a
3072 		 * panic on some operating systems.
3073 		 */
3074 		if (!out) {
3075 			if (pass & FR_RETICMP) {
3076 				int dst;
3077 
3078 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
3079 					dst = 1;
3080 				else
3081 					dst = 0;
3082 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3083 							 dst);
3084 				LBUMP(ipf_stats[0].fr_ret);
3085 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
3086 				   !(fin->fin_flx & FI_SHORT)) {
3087 				if (((fin->fin_flx & FI_OOW) != 0) ||
3088 				    (ipf_send_reset(fin) == 0)) {
3089 					LBUMP(ipf_stats[1].fr_ret);
3090 				}
3091 			}
3092 
3093 			/*
3094 			 * When using return-* with auth rules, the auth code
3095 			 * takes over disposing of this packet.
3096 			 */
3097 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3098 				DT1(frb_authcapture, fr_info_t *, fin);
3099 				fin->fin_m = *fin->fin_mp = NULL;
3100 				fin->fin_reason = FRB_AUTHCAPTURE;
3101 				m = NULL;
3102 			}
3103 		} else {
3104 			if (pass & FR_RETRST) {
3105 				fin->fin_error = ECONNRESET;
3106 			}
3107 		}
3108 	}
3109 
3110 	/*
3111 	 * After the above so that ICMP unreachables and TCP RSTs get
3112 	 * created properly.
3113 	 */
3114 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3115 		ipf_nat_uncreate(fin);
3116 
3117 	/*
3118 	 * If we didn't drop off the bottom of the list of rules (and thus
3119 	 * the 'current' rule fr is not NULL), then we may have some extra
3120 	 * instructions about what to do with a packet.
3121 	* Once we're finished return to our caller, freeing the packet if
3122 	 * we are dropping it.
3123 	 */
3124 	if (fr != NULL) {
3125 		frdest_t *fdp;
3126 
3127 		/*
3128 		 * Generate a duplicated packet first because ipf_fastroute
3129 		 * can lead to fin_m being free'd... not good.
3130 		 */
3131 		fdp = fin->fin_dif;
3132 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3133 		    (fdp->fd_ptr != (void *)-1)) {
3134 			mc = M_COPY(fin->fin_m);
3135 			if (mc != NULL)
3136 				ipf_fastroute(mc, &mc, fin, fdp);
3137 		}
3138 
3139 		fdp = fin->fin_tif;
3140 		if (!out && (pass & FR_FASTROUTE)) {
3141 			/*
3142 			 * For fastroute rule, no destination interface defined
3143 			 * so pass NULL as the frdest_t parameter
3144 			 */
3145 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3146 			m = *mp = NULL;
3147 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3148 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
3149 			/* this is for to rules: */
3150 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
3151 			m = *mp = NULL;
3152 		}
3153 
3154 #if defined(FASTROUTE_RECURSION)
3155 		(void) ipf_derefrule(softc, &fr);
3156 #endif
3157 	}
3158 #if !defined(FASTROUTE_RECURSION)
3159 	RWLOCK_EXIT(&softc->ipf_mutex);
3160 #endif
3161 
3162 finished:
3163 	if (!FR_ISPASS(pass)) {
3164 		LBUMP(ipf_stats[out].fr_block);
3165 		if (*mp != NULL) {
3166 #ifdef _KERNEL
3167 			FREE_MB_T(*mp);
3168 #endif
3169 			m = *mp = NULL;
3170 		}
3171 	} else {
3172 		LBUMP(ipf_stats[out].fr_pass);
3173 	}
3174 
3175 	SPL_X(s);
3176 
3177 	if (fin->fin_m == NULL && fin->fin_flx & FI_BAD &&
3178 	    fin->fin_reason == FRB_PULLUP) {
3179 		/* m_pullup() has freed the mbuf */
3180 		LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3181 		return (-1);
3182 	}
3183 
3184 
3185 #ifdef _KERNEL
3186 	if (FR_ISPASS(pass))
3187 		return (0);
3188 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3189 	return (fin->fin_error);
3190 #else /* _KERNEL */
3191 	if (*mp != NULL)
3192 		(*mp)->mb_ifp = fin->fin_ifp;
3193 	blockreason = fin->fin_reason;
3194 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3195 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3196 		if ((pass & FR_NOMATCH) != 0)
3197 			return (1);
3198 
3199 	if ((pass & FR_RETMASK) != 0)
3200 		switch (pass & FR_RETMASK)
3201 		{
3202 		case FR_RETRST :
3203 			return (3);
3204 		case FR_RETICMP :
3205 			return (4);
3206 		case FR_FAKEICMP :
3207 			return (5);
3208 		}
3209 
3210 	switch (pass & FR_CMDMASK)
3211 	{
3212 	case FR_PASS :
3213 		return (0);
3214 	case FR_BLOCK :
3215 		return (-1);
3216 	case FR_AUTH :
3217 		return (-2);
3218 	case FR_ACCOUNT :
3219 		return (-3);
3220 	case FR_PREAUTH :
3221 		return (-4);
3222 	}
3223 	return (2);
3224 #endif /* _KERNEL */
3225 }
3226 
3227 
3228 #ifdef	IPFILTER_LOG
3229 /* ------------------------------------------------------------------------ */
3230 /* Function:    ipf_dolog                                                   */
3231 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3232 /* Parameters:  fin(I) - pointer to packet information                      */
3233 /*              passp(IO) - pointer to current/new filter decision (unused) */
3234 /*                                                                          */
3235 /* Checks flags set to see how a packet should be logged, if it is to be    */
3236 /* logged.  Adjust statistics based on its success or not.                  */
3237 /* ------------------------------------------------------------------------ */
3238 frentry_t *
ipf_dolog(fr_info_t * fin,u_32_t * passp)3239 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3240 {
3241 	ipf_main_softc_t *softc = fin->fin_main_soft;
3242 	u_32_t pass;
3243 	int out;
3244 
3245 	out = fin->fin_out;
3246 	pass = *passp;
3247 
3248 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3249 		pass |= FF_LOGNOMATCH;
3250 		LBUMPD(ipf_stats[out], fr_npkl);
3251 		goto logit;
3252 
3253 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3254 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3255 		if ((pass & FR_LOGMASK) != FR_LOGP)
3256 			pass |= FF_LOGPASS;
3257 		LBUMPD(ipf_stats[out], fr_ppkl);
3258 		goto logit;
3259 
3260 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3261 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3262 		if ((pass & FR_LOGMASK) != FR_LOGB)
3263 			pass |= FF_LOGBLOCK;
3264 		LBUMPD(ipf_stats[out], fr_bpkl);
3265 
3266 logit:
3267 		if (ipf_log_pkt(fin, pass) == -1) {
3268 			/*
3269 			 * If the "or-block" option has been used then
3270 			 * block the packet if we failed to log it.
3271 			 */
3272 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3273 				DT1(frb_logfail2, u_int, pass);
3274 				pass &= ~FR_CMDMASK;
3275 				pass |= FR_BLOCK;
3276 				fin->fin_reason = FRB_LOGFAIL2;
3277 			}
3278 		}
3279 		*passp = pass;
3280 	}
3281 
3282 	return (fin->fin_fr);
3283 }
3284 #endif /* IPFILTER_LOG */
3285 
3286 
3287 /* ------------------------------------------------------------------------ */
3288 /* Function:    ipf_cksum                                                   */
3289 /* Returns:     u_short - IP header checksum                                */
3290 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3291 /*              len(I)  - length of buffer in bytes                         */
3292 /*                                                                          */
3293 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3294 /*                                                                          */
3295 /* N.B.: addr should be 16bit aligned.                                      */
3296 /* ------------------------------------------------------------------------ */
3297 u_short
ipf_cksum(u_short * addr,int len)3298 ipf_cksum(u_short *addr, int len)
3299 {
3300 	u_32_t sum = 0;
3301 
3302 	for (sum = 0; len > 1; len -= 2)
3303 		sum += *addr++;
3304 
3305 	/* mop up an odd byte, if necessary */
3306 	if (len == 1)
3307 		sum += *(u_char *)addr;
3308 
3309 	/*
3310 	 * add back carry outs from top 16 bits to low 16 bits
3311 	 */
3312 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
3313 	sum += (sum >> 16);			/* add carry */
3314 	return (u_short)(~sum);
3315 }
3316 
3317 
3318 /* ------------------------------------------------------------------------ */
3319 /* Function:    fr_cksum                                                    */
3320 /* Returns:     u_short - layer 4 checksum                                  */
3321 /* Parameters:  fin(I)     - pointer to packet information                  */
3322 /*              ip(I)      - pointer to IP header                           */
3323 /*              l4proto(I) - protocol to caclulate checksum for             */
3324 /*              l4hdr(I)   - pointer to layer 4 header                      */
3325 /*                                                                          */
3326 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3327 /* in the IP header "ip" to seed it.                                        */
3328 /*                                                                          */
3329 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3330 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3331 /* odd sizes.                                                               */
3332 /*                                                                          */
3333 /* Expects ip_len and ip_off to be in network byte order when called.       */
3334 /* ------------------------------------------------------------------------ */
3335 u_short
fr_cksum(fr_info_t * fin,ip_t * ip,int l4proto,void * l4hdr)3336 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3337 {
3338 	u_short *sp, slen, sumsave, *csump;
3339 	u_int sum, sum2;
3340 	int hlen;
3341 	int off;
3342 #ifdef	USE_INET6
3343 	ip6_t *ip6;
3344 #endif
3345 
3346 	csump = NULL;
3347 	sumsave = 0;
3348 	sp = NULL;
3349 	slen = 0;
3350 	hlen = 0;
3351 	sum = 0;
3352 
3353 	sum = htons((u_short)l4proto);
3354 	/*
3355 	 * Add up IP Header portion
3356 	 */
3357 #ifdef	USE_INET6
3358 	if (IP_V(ip) == 4) {
3359 #endif
3360 		hlen = IP_HL(ip) << 2;
3361 		off = hlen;
3362 		sp = (u_short *)&ip->ip_src;
3363 		sum += *sp++;	/* ip_src */
3364 		sum += *sp++;
3365 		sum += *sp++;	/* ip_dst */
3366 		sum += *sp++;
3367 		slen = fin->fin_plen - off;
3368 		sum += htons(slen);
3369 #ifdef	USE_INET6
3370 	} else if (IP_V(ip) == 6) {
3371 		mb_t *m;
3372 
3373 		m = fin->fin_m;
3374 		ip6 = (ip6_t *)ip;
3375 		off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3376 		int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3377 		return (ipf_pcksum6(m, ip6, off, len));
3378 	} else {
3379 		return (0xffff);
3380 	}
3381 #endif
3382 
3383 	switch (l4proto)
3384 	{
3385 	case IPPROTO_UDP :
3386 		csump = &((udphdr_t *)l4hdr)->uh_sum;
3387 		break;
3388 
3389 	case IPPROTO_TCP :
3390 		csump = &((tcphdr_t *)l4hdr)->th_sum;
3391 		break;
3392 	case IPPROTO_ICMP :
3393 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3394 		sum = 0;	/* Pseudo-checksum is not included */
3395 		break;
3396 #ifdef USE_INET6
3397 	case IPPROTO_ICMPV6 :
3398 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3399 		break;
3400 #endif
3401 	default :
3402 		break;
3403 	}
3404 
3405 	if (csump != NULL) {
3406 		sumsave = *csump;
3407 		*csump = 0;
3408 	}
3409 
3410 	sum2 = ipf_pcksum(fin, off, sum);
3411 	if (csump != NULL)
3412 		*csump = sumsave;
3413 	return (sum2);
3414 }
3415 
3416 
3417 /* ------------------------------------------------------------------------ */
3418 /* Function:    ipf_findgroup                                               */
3419 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3420 /* Parameters:  softc(I) - pointer to soft context main structure           */
3421 /*              group(I) - group name to search for                         */
3422 /*              unit(I)  - device to which this group belongs               */
3423 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3424 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3425 /*                         to where to add the next (last) group or where   */
3426 /*                         to delete group from.                            */
3427 /*                                                                          */
3428 /* Search amongst the defined groups for a particular group number.         */
3429 /* ------------------------------------------------------------------------ */
3430 frgroup_t *
ipf_findgroup(ipf_main_softc_t * softc,char * group,minor_t unit,int set,frgroup_t *** fgpp)3431 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3432 	frgroup_t ***fgpp)
3433 {
3434 	frgroup_t *fg, **fgp;
3435 
3436 	/*
3437 	 * Which list of groups to search in is dependent on which list of
3438 	 * rules are being operated on.
3439 	 */
3440 	fgp = &softc->ipf_groups[unit][set];
3441 
3442 	while ((fg = *fgp) != NULL) {
3443 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3444 			break;
3445 		else
3446 			fgp = &fg->fg_next;
3447 	}
3448 	if (fgpp != NULL)
3449 		*fgpp = fgp;
3450 	return (fg);
3451 }
3452 
3453 
3454 /* ------------------------------------------------------------------------ */
3455 /* Function:    ipf_group_add                                               */
3456 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3457 /*                            != NULL == pointer to the group               */
3458 /* Parameters:  softc(I) - pointer to soft context main structure           */
3459 /*              num(I)   - group number to add                              */
3460 /*              head(I)  - rule pointer that is using this as the head      */
3461 /*              flags(I) - rule flags which describe the type of rule it is */
3462 /*              unit(I)  - device to which this group will belong to        */
3463 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3464 /* Write Locks: ipf_mutex                                                   */
3465 /*                                                                          */
3466 /* Add a new group head, or if it already exists, increase the reference    */
3467 /* count to it.                                                             */
3468 /* ------------------------------------------------------------------------ */
3469 frgroup_t *
ipf_group_add(ipf_main_softc_t * softc,char * group,void * head,u_32_t flags,minor_t unit,int set)3470 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3471 	minor_t unit, int set)
3472 {
3473 	frgroup_t *fg, **fgp;
3474 	u_32_t gflags;
3475 
3476 	if (group == NULL)
3477 		return (NULL);
3478 
3479 	if (unit == IPL_LOGIPF && *group == '\0')
3480 		return (NULL);
3481 
3482 	fgp = NULL;
3483 	gflags = flags & FR_INOUT;
3484 
3485 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
3486 	if (fg != NULL) {
3487 		if (fg->fg_head == NULL && head != NULL)
3488 			fg->fg_head = head;
3489 		if (fg->fg_flags == 0)
3490 			fg->fg_flags = gflags;
3491 		else if (gflags != fg->fg_flags)
3492 			return (NULL);
3493 		fg->fg_ref++;
3494 		return (fg);
3495 	}
3496 
3497 	KMALLOC(fg, frgroup_t *);
3498 	if (fg != NULL) {
3499 		fg->fg_head = head;
3500 		fg->fg_start = NULL;
3501 		fg->fg_next = *fgp;
3502 		bcopy(group, fg->fg_name, strlen(group) + 1);
3503 		fg->fg_flags = gflags;
3504 		fg->fg_ref = 1;
3505 		fg->fg_set = &softc->ipf_groups[unit][set];
3506 		*fgp = fg;
3507 	}
3508 	return (fg);
3509 }
3510 
3511 
3512 /* ------------------------------------------------------------------------ */
3513 /* Function:    ipf_group_del                                               */
3514 /* Returns:     int      - number of rules deleted                          */
3515 /* Parameters:  softc(I) - pointer to soft context main structure           */
3516 /*              group(I) - group name to delete                             */
3517 /*              fr(I)    - filter rule from which group is referenced       */
3518 /* Write Locks: ipf_mutex                                                   */
3519 /*                                                                          */
3520 /* This function is called whenever a reference to a group is to be dropped */
3521 /* and thus its reference count needs to be lowered and the group free'd if */
3522 /* the reference count reaches zero. Passing in fr is really for the sole   */
3523 /* purpose of knowing when the head rule is being deleted.                  */
3524 /* ------------------------------------------------------------------------ */
3525 void
ipf_group_del(ipf_main_softc_t * softc,frgroup_t * group,frentry_t * fr)3526 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3527 {
3528 
3529 	if (group->fg_head == fr)
3530 		group->fg_head = NULL;
3531 
3532 	group->fg_ref--;
3533 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
3534 		ipf_group_free(group);
3535 }
3536 
3537 
3538 /* ------------------------------------------------------------------------ */
3539 /* Function:    ipf_group_free                                              */
3540 /* Returns:     Nil                                                         */
3541 /* Parameters:  group(I) - pointer to filter rule group                     */
3542 /*                                                                          */
3543 /* Remove the group from the list of groups and free it.                    */
3544 /* ------------------------------------------------------------------------ */
3545 static void
ipf_group_free(frgroup_t * group)3546 ipf_group_free(frgroup_t *group)
3547 {
3548 	frgroup_t **gp;
3549 
3550 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3551 		if (*gp == group) {
3552 			*gp = group->fg_next;
3553 			break;
3554 		}
3555 	}
3556 	KFREE(group);
3557 }
3558 
3559 
3560 /* ------------------------------------------------------------------------ */
3561 /* Function:    ipf_group_flush                                             */
3562 /* Returns:     int      - number of rules flush from group                 */
3563 /* Parameters:  softc(I) - pointer to soft context main structure           */
3564 /* Parameters:  group(I) - pointer to filter rule group                     */
3565 /*                                                                          */
3566 /* Remove all of the rules that currently are listed under the given group. */
3567 /* ------------------------------------------------------------------------ */
3568 static int
ipf_group_flush(ipf_main_softc_t * softc,frgroup_t * group)3569 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3570 {
3571 	int gone = 0;
3572 
3573 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
3574 
3575 	return (gone);
3576 }
3577 
3578 
3579 /* ------------------------------------------------------------------------ */
3580 /* Function:    ipf_getrulen                                                */
3581 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3582 /* Parameters:  softc(I) - pointer to soft context main structure           */
3583 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3584 /*              flags(I) - which set of rules to find the rule in           */
3585 /*              group(I) - group name                                       */
3586 /*              n(I)     - rule number to find                              */
3587 /*                                                                          */
3588 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3589 /* group # g doesn't exist or there are less than n rules in the group.     */
3590 /* ------------------------------------------------------------------------ */
3591 frentry_t *
ipf_getrulen(ipf_main_softc_t * softc,int unit,char * group,u_32_t n)3592 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3593 {
3594 	frentry_t *fr;
3595 	frgroup_t *fg;
3596 
3597 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3598 	if (fg == NULL)
3599 		return (NULL);
3600 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3601 		;
3602 	if (n != 0)
3603 		return (NULL);
3604 	return (fr);
3605 }
3606 
3607 
3608 /* ------------------------------------------------------------------------ */
3609 /* Function:    ipf_flushlist                                               */
3610 /* Returns:     int - >= 0 - number of flushed rules                        */
3611 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3612 /*              nfreedp(O) - pointer to int where flush count is stored     */
3613 /*              listp(I)   - pointer to list to flush pointer               */
3614 /* Write Locks: ipf_mutex                                                   */
3615 /*                                                                          */
3616 /* Recursively flush rules from the list, descending groups as they are     */
3617 /* encountered.  if a rule is the head of a group and it has lost all its   */
3618 /* group members, then also delete the group reference.  nfreedp is needed  */
3619 /* to store the accumulating count of rules removed, whereas the returned   */
3620 /* value is just the number removed from the current list.  The latter is   */
3621 /* needed to correctly adjust reference counts on rules that define groups. */
3622 /*                                                                          */
3623 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3624 /* ------------------------------------------------------------------------ */
3625 static int
ipf_flushlist(ipf_main_softc_t * softc,int * nfreedp,frentry_t ** listp)3626 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3627 {
3628 	int freed = 0;
3629 	frentry_t *fp;
3630 
3631 	while ((fp = *listp) != NULL) {
3632 		if ((fp->fr_type & FR_T_BUILTIN) ||
3633 		    !(fp->fr_flags & FR_COPIED)) {
3634 			listp = &fp->fr_next;
3635 			continue;
3636 		}
3637 		*listp = fp->fr_next;
3638 		if (fp->fr_next != NULL)
3639 			fp->fr_next->fr_pnext = fp->fr_pnext;
3640 		fp->fr_pnext = NULL;
3641 
3642 		if (fp->fr_grphead != NULL) {
3643 			freed += ipf_group_flush(softc, fp->fr_grphead);
3644 			fp->fr_names[fp->fr_grhead] = '\0';
3645 		}
3646 
3647 		if (fp->fr_icmpgrp != NULL) {
3648 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3649 			fp->fr_names[fp->fr_icmphead] = '\0';
3650 		}
3651 
3652 		if (fp->fr_srctrack.ht_max_nodes)
3653 			ipf_rb_ht_flush(&fp->fr_srctrack);
3654 
3655 		fp->fr_next = NULL;
3656 
3657 		ASSERT(fp->fr_ref > 0);
3658 		if (ipf_derefrule(softc, &fp) == 0)
3659 			freed++;
3660 	}
3661 	*nfreedp += freed;
3662 	return (freed);
3663 }
3664 
3665 
3666 /* ------------------------------------------------------------------------ */
3667 /* Function:    ipf_flush                                                   */
3668 /* Returns:     int - >= 0 - number of flushed rules                        */
3669 /* Parameters:  softc(I) - pointer to soft context main structure           */
3670 /*              unit(I)  - device for which to flush rules                  */
3671 /*              flags(I) - which set of rules to flush                      */
3672 /*                                                                          */
3673 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3674 /* and IPv6) as defined by the value of flags.                              */
3675 /* ------------------------------------------------------------------------ */
3676 int
ipf_flush(ipf_main_softc_t * softc,minor_t unit,int flags)3677 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3678 {
3679 	int flushed = 0, set;
3680 
3681 	WRITE_ENTER(&softc->ipf_mutex);
3682 
3683 	set = softc->ipf_active;
3684 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3685 		set = 1 - set;
3686 
3687 	if (flags & FR_OUTQUE) {
3688 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3689 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3690 	}
3691 	if (flags & FR_INQUE) {
3692 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3693 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3694 	}
3695 
3696 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3697 				    flags & (FR_INQUE|FR_OUTQUE));
3698 
3699 	RWLOCK_EXIT(&softc->ipf_mutex);
3700 
3701 	if (unit == IPL_LOGIPF) {
3702 		int tmp;
3703 
3704 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3705 		if (tmp >= 0)
3706 			flushed += tmp;
3707 	}
3708 	return (flushed);
3709 }
3710 
3711 
3712 /* ------------------------------------------------------------------------ */
3713 /* Function:    ipf_flush_groups                                            */
3714 /* Returns:     int - >= 0 - number of flushed rules                        */
3715 /* Parameters:  softc(I)  - soft context pointerto work with                */
3716 /*              grhead(I) - pointer to the start of the group list to flush */
3717 /*              flags(I)  - which set of rules to flush                     */
3718 /*                                                                          */
3719 /* Walk through all of the groups under the given group head and remove all */
3720 /* of those that match the flags passed in. The for loop here is bit more   */
3721 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3722 /* may end up removing not only the structure pointed to by "fg" but also   */
3723 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3724 /* removed from the group then it is necessary to start again.              */
3725 /* ------------------------------------------------------------------------ */
3726 static int
ipf_flush_groups(ipf_main_softc_t * softc,frgroup_t ** grhead,int flags)3727 ipf_flush_groups(ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3728 {
3729 	frentry_t *fr, **frp;
3730 	frgroup_t *fg, **fgp;
3731 	int flushed = 0;
3732 	int removed = 0;
3733 
3734 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
3735 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3736 			fg = fg->fg_next;
3737 		if (fg == NULL)
3738 			break;
3739 		removed = 0;
3740 		frp = &fg->fg_start;
3741 		while ((removed == 0) && ((fr = *frp) != NULL)) {
3742 			if ((fr->fr_flags & flags) == 0) {
3743 				frp = &fr->fr_next;
3744 			} else {
3745 				if (fr->fr_next != NULL)
3746 					fr->fr_next->fr_pnext = fr->fr_pnext;
3747 				*frp = fr->fr_next;
3748 				fr->fr_pnext = NULL;
3749 				fr->fr_next = NULL;
3750 				(void) ipf_derefrule(softc, &fr);
3751 				flushed++;
3752 				removed++;
3753 			}
3754 		}
3755 		if (removed == 0)
3756 			fgp = &fg->fg_next;
3757 	}
3758 	return (flushed);
3759 }
3760 
3761 
3762 /* ------------------------------------------------------------------------ */
3763 /* Function:    memstr                                                      */
3764 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3765 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3766 /*              dst(I)  - pointer to byte sequence to search                */
3767 /*              slen(I) - match length                                      */
3768 /*              dlen(I) - length available to search in                     */
3769 /*                                                                          */
3770 /* Search dst for a sequence of bytes matching those at src and extend for  */
3771 /* slen bytes.                                                              */
3772 /* ------------------------------------------------------------------------ */
3773 char *
memstr(const char * src,char * dst,size_t slen,size_t dlen)3774 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3775 {
3776 	char *s = NULL;
3777 
3778 	while (dlen >= slen) {
3779 		if (bcmp(src, dst, slen) == 0) {
3780 			s = dst;
3781 			break;
3782 		}
3783 		dst++;
3784 		dlen--;
3785 	}
3786 	return (s);
3787 }
3788 /* ------------------------------------------------------------------------ */
3789 /* Function:    ipf_fixskip                                                 */
3790 /* Returns:     Nil                                                         */
3791 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3792 /*              rp(I)        - rule added/removed with skip in it.          */
3793 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3794 /*                             depending on whether a rule was just added   */
3795 /*                             or removed.                                  */
3796 /*                                                                          */
3797 /* Adjust all the rules in a list which would have skip'd past the position */
3798 /* where we are inserting to skip to the right place given the change.      */
3799 /* ------------------------------------------------------------------------ */
3800 void
ipf_fixskip(frentry_t ** listp,frentry_t * rp,int addremove)3801 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3802 {
3803 	int rules, rn;
3804 	frentry_t *fp;
3805 
3806 	rules = 0;
3807 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3808 		rules++;
3809 
3810 	if (fp == NULL)
3811 		return;
3812 
3813 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3814 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3815 			fp->fr_arg += addremove;
3816 }
3817 
3818 
3819 #ifdef	_KERNEL
3820 /* ------------------------------------------------------------------------ */
3821 /* Function:    count4bits                                                  */
3822 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3823 /* Parameters:  ip(I) - 32bit IP address                                    */
3824 /*                                                                          */
3825 /* IPv4 ONLY                                                                */
3826 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3827 /* consecutive 1's is different to that passed, return -1, else return #    */
3828 /* of bits.                                                                 */
3829 /* ------------------------------------------------------------------------ */
3830 int
count4bits(u_32_t ip)3831 count4bits(u_32_t ip)
3832 {
3833 	u_32_t	ipn;
3834 	int	cnt = 0, i, j;
3835 
3836 	ip = ipn = ntohl(ip);
3837 	for (i = 32; i; i--, ipn *= 2)
3838 		if (ipn & 0x80000000)
3839 			cnt++;
3840 		else
3841 			break;
3842 	ipn = 0;
3843 	for (i = 32, j = cnt; i; i--, j--) {
3844 		ipn *= 2;
3845 		if (j > 0)
3846 			ipn++;
3847 	}
3848 	if (ipn == ip)
3849 		return (cnt);
3850 	return (-1);
3851 }
3852 
3853 
3854 /* ------------------------------------------------------------------------ */
3855 /* Function:    count6bits                                                  */
3856 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3857 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3858 /*                                                                          */
3859 /* IPv6 ONLY                                                                */
3860 /* count consecutive 1's in bit mask.                                       */
3861 /* ------------------------------------------------------------------------ */
3862 # ifdef USE_INET6
3863 int
count6bits(u_32_t * msk)3864 count6bits(u_32_t *msk)
3865 {
3866 	int i = 0, k;
3867 	u_32_t j;
3868 
3869 	for (k = 3; k >= 0; k--)
3870 		if (msk[k] == 0xffffffff)
3871 			i += 32;
3872 		else {
3873 			for (j = msk[k]; j; j <<= 1)
3874 				if (j & 0x80000000)
3875 					i++;
3876 		}
3877 	return (i);
3878 }
3879 # endif
3880 #endif /* _KERNEL */
3881 
3882 
3883 /* ------------------------------------------------------------------------ */
3884 /* Function:    ipf_synclist                                                */
3885 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3886 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3887 /*              ifp(I) - interface pointer for limiting sync lookups        */
3888 /* Write Locks: ipf_mutex                                                   */
3889 /*                                                                          */
3890 /* Walk through a list of filter rules and resolve any interface names into */
3891 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3892 /* used in the rule.  The interface pointer is used to limit the lookups to */
3893 /* a specific set of matching names if it is non-NULL.                      */
3894 /* Errors can occur when resolving the destination name of to/dup-to fields */
3895 /* when the name points to a pool and that pool doest not exist. If this    */
3896 /* does happen then it is necessary to check if there are any lookup refs   */
3897 /* that need to be dropped before returning with an error.                  */
3898 /* ------------------------------------------------------------------------ */
3899 static int
ipf_synclist(ipf_main_softc_t * softc,frentry_t * fr,void * ifp)3900 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3901 {
3902 	frentry_t *frt, *start = fr;
3903 	frdest_t *fdp;
3904 	char *name;
3905 	int error;
3906 	void *ifa;
3907 	int v, i;
3908 
3909 	error = 0;
3910 
3911 	for (; fr; fr = fr->fr_next) {
3912 		if (fr->fr_family == AF_INET)
3913 			v = 4;
3914 		else if (fr->fr_family == AF_INET6)
3915 			v = 6;
3916 		else
3917 			v = 0;
3918 
3919 		/*
3920 		 * Lookup all the interface names that are part of the rule.
3921 		 */
3922 		for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
3923 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3924 				continue;
3925 			if (fr->fr_ifnames[i] == -1)
3926 				continue;
3927 			name = FR_NAME(fr, fr_ifnames[i]);
3928 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3929 		}
3930 
3931 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3932 			if (fr->fr_satype != FRI_NORMAL &&
3933 			    fr->fr_satype != FRI_LOOKUP) {
3934 				ifa = ipf_resolvenic(softc, fr->fr_names +
3935 						     fr->fr_sifpidx, v);
3936 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3937 					    &fr->fr_src6, &fr->fr_smsk6);
3938 			}
3939 			if (fr->fr_datype != FRI_NORMAL &&
3940 			    fr->fr_datype != FRI_LOOKUP) {
3941 				ifa = ipf_resolvenic(softc, fr->fr_names +
3942 						     fr->fr_sifpidx, v);
3943 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
3944 					    &fr->fr_dst6, &fr->fr_dmsk6);
3945 			}
3946 		}
3947 
3948 		fdp = &fr->fr_tifs[0];
3949 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3950 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3951 			if (error != 0)
3952 				goto unwind;
3953 		}
3954 
3955 		fdp = &fr->fr_tifs[1];
3956 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3957 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3958 			if (error != 0)
3959 				goto unwind;
3960 		}
3961 
3962 		fdp = &fr->fr_dif;
3963 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3964 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3965 			if (error != 0)
3966 				goto unwind;
3967 		}
3968 
3969 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3970 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
3971 			fr->fr_srcptr = ipf_lookup_res_num(softc,
3972 							   fr->fr_srctype,
3973 							   IPL_LOGIPF,
3974 							   fr->fr_srcnum,
3975 							   &fr->fr_srcfunc);
3976 		}
3977 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3978 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
3979 			fr->fr_dstptr = ipf_lookup_res_num(softc,
3980 							   fr->fr_dsttype,
3981 							   IPL_LOGIPF,
3982 							   fr->fr_dstnum,
3983 							   &fr->fr_dstfunc);
3984 		}
3985 	}
3986 	return (0);
3987 
3988 unwind:
3989 	for (frt = start; frt != fr; fr = fr->fr_next) {
3990 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3991 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
3992 				ipf_lookup_deref(softc, frt->fr_srctype,
3993 						 frt->fr_srcptr);
3994 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3995 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
3996 				ipf_lookup_deref(softc, frt->fr_dsttype,
3997 						 frt->fr_dstptr);
3998 	}
3999 	return (error);
4000 }
4001 
4002 
4003 /* ------------------------------------------------------------------------ */
4004 /* Function:    ipf_sync                                                    */
4005 /* Returns:     void                                                        */
4006 /* Parameters:  Nil                                                         */
4007 /*                                                                          */
4008 /* ipf_sync() is called when we suspect that the interface list or          */
4009 /* information about interfaces (like IP#) has changed.  Go through all     */
4010 /* filter rules, NAT entries and the state table and check if anything      */
4011 /* needs to be changed/updated.                                             */
4012 /* ------------------------------------------------------------------------ */
4013 int
ipf_sync(ipf_main_softc_t * softc,void * ifp)4014 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4015 {
4016 	int i;
4017 
4018 #if !SOLARIS
4019 	ipf_nat_sync(softc, ifp);
4020 	ipf_state_sync(softc, ifp);
4021 	ipf_lookup_sync(softc, ifp);
4022 #endif
4023 
4024 	WRITE_ENTER(&softc->ipf_mutex);
4025 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4026 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4027 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4028 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4029 
4030 	for (i = 0; i < IPL_LOGSIZE; i++) {
4031 		frgroup_t *g;
4032 
4033 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4034 			(void) ipf_synclist(softc, g->fg_start, ifp);
4035 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4036 			(void) ipf_synclist(softc, g->fg_start, ifp);
4037 	}
4038 	RWLOCK_EXIT(&softc->ipf_mutex);
4039 
4040 	return (0);
4041 }
4042 
4043 
4044 /*
4045  * In the functions below, bcopy() is called because the pointer being
4046  * copied _from_ in this instance is a pointer to a char buf (which could
4047  * end up being unaligned) and on the kernel's local stack.
4048  */
4049 /* ------------------------------------------------------------------------ */
4050 /* Function:    copyinptr                                                   */
4051 /* Returns:     int - 0 = success, else failure                             */
4052 /* Parameters:  src(I)  - pointer to the source address                     */
4053 /*              dst(I)  - destination address                               */
4054 /*              size(I) - number of bytes to copy                           */
4055 /*                                                                          */
4056 /* Copy a block of data in from user space, given a pointer to the pointer  */
4057 /* to start copying from (src) and a pointer to where to store it (dst).    */
4058 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4059 /* ------------------------------------------------------------------------ */
4060 int
copyinptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4061 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4062 {
4063 	caddr_t ca;
4064 	int error;
4065 
4066 #if SOLARIS
4067 	error = COPYIN(src, &ca, sizeof(ca));
4068 	if (error != 0)
4069 		return (error);
4070 #else
4071 	bcopy(src, (caddr_t)&ca, sizeof(ca));
4072 #endif
4073 	error = COPYIN(ca, dst, size);
4074 	if (error != 0) {
4075 		IPFERROR(3);
4076 		error = EFAULT;
4077 	}
4078 	return (error);
4079 }
4080 
4081 
4082 /* ------------------------------------------------------------------------ */
4083 /* Function:    copyoutptr                                                  */
4084 /* Returns:     int - 0 = success, else failure                             */
4085 /* Parameters:  src(I)  - pointer to the source address                     */
4086 /*              dst(I)  - destination address                               */
4087 /*              size(I) - number of bytes to copy                           */
4088 /*                                                                          */
4089 /* Copy a block of data out to user space, given a pointer to the pointer   */
4090 /* to start copying from (src) and a pointer to where to store it (dst).    */
4091 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4092 /* ------------------------------------------------------------------------ */
4093 int
copyoutptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4094 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4095 {
4096 	caddr_t ca;
4097 	int error;
4098 
4099 	bcopy(dst, (caddr_t)&ca, sizeof(ca));
4100 	error = COPYOUT(src, ca, size);
4101 	if (error != 0) {
4102 		IPFERROR(4);
4103 		error = EFAULT;
4104 	}
4105 	return (error);
4106 }
4107 
4108 
4109 /* ------------------------------------------------------------------------ */
4110 /* Function:    ipf_lock                                                    */
4111 /* Returns:     int      - 0 = success, else error                          */
4112 /* Parameters:  data(I)  - pointer to lock value to set                     */
4113 /*              lockp(O) - pointer to location to store old lock value      */
4114 /*                                                                          */
4115 /* Get the new value for the lock integer, set it and return the old value  */
4116 /* in *lockp.                                                               */
4117 /* ------------------------------------------------------------------------ */
4118 int
ipf_lock(caddr_t data,int * lockp)4119 ipf_lock(caddr_t data, int *lockp)
4120 {
4121 	int arg, err;
4122 
4123 	err = BCOPYIN(data, &arg, sizeof(arg));
4124 	if (err != 0)
4125 		return (EFAULT);
4126 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
4127 	if (err != 0)
4128 		return (EFAULT);
4129 	*lockp = arg;
4130 	return (0);
4131 }
4132 
4133 
4134 /* ------------------------------------------------------------------------ */
4135 /* Function:    ipf_getstat                                                 */
4136 /* Returns:     Nil                                                         */
4137 /* Parameters:  softc(I) - pointer to soft context main structure           */
4138 /*              fiop(I)  - pointer to ipfilter stats structure              */
4139 /*              rev(I)   - version claim by program doing ioctl             */
4140 /*                                                                          */
4141 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4142 /* structure.                                                               */
4143 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4144 /* program is looking for. This ensure that validation of the version it    */
4145 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4146 /* allow older binaries to work but kernels without it will not.            */
4147 /* ------------------------------------------------------------------------ */
4148 /*ARGSUSED*/
4149 static void
ipf_getstat(ipf_main_softc_t * softc,friostat_t * fiop,int rev)4150 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4151 {
4152 	int i;
4153 
4154 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4155 	      sizeof(ipf_statistics_t) * 2);
4156 	fiop->f_locks[IPL_LOGSTATE] = -1;
4157 	fiop->f_locks[IPL_LOGNAT] = -1;
4158 	fiop->f_locks[IPL_LOGIPF] = -1;
4159 	fiop->f_locks[IPL_LOGAUTH] = -1;
4160 
4161 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4162 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4163 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4164 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4165 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4166 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4167 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4168 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4169 
4170 	fiop->f_ticks = softc->ipf_ticks;
4171 	fiop->f_active = softc->ipf_active;
4172 	fiop->f_froute[0] = softc->ipf_frouteok[0];
4173 	fiop->f_froute[1] = softc->ipf_frouteok[1];
4174 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4175 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
4176 
4177 	fiop->f_running = softc->ipf_running;
4178 	for (i = 0; i < IPL_LOGSIZE; i++) {
4179 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4180 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4181 	}
4182 #ifdef  IPFILTER_LOG
4183 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4184 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4185 	fiop->f_logging = 1;
4186 #else
4187 	fiop->f_log_ok = 0;
4188 	fiop->f_log_fail = 0;
4189 	fiop->f_logging = 0;
4190 #endif
4191 	fiop->f_defpass = softc->ipf_pass;
4192 	fiop->f_features = ipf_features;
4193 
4194 #ifdef IPFILTER_COMPAT
4195 	snprintf(fiop->f_version, sizeof(friostat.f_version), "IP Filter: v%d.%d.%d",
4196 		(rev / 1000000) % 100,
4197 		(rev / 10000) % 100,
4198 		(rev / 100) % 100);
4199 #else
4200 	(void)rev; /* UNUSED */
4201 	(void) strncpy(fiop->f_version, ipfilter_version,
4202 		       sizeof(fiop->f_version));
4203 #endif
4204 }
4205 
4206 
4207 #ifdef	USE_INET6
4208 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4209 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
4210 	-1,			/* 1: UNUSED */
4211 	-1,			/* 2: UNUSED */
4212 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
4213 	-1,			/* 4: ICMP_SOURCEQUENCH */
4214 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
4215 	-1,			/* 6: UNUSED */
4216 	-1,			/* 7: UNUSED */
4217 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
4218 	-1,			/* 9: UNUSED */
4219 	-1,			/* 10: UNUSED */
4220 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
4221 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
4222 	-1,			/* 13: ICMP_TSTAMP */
4223 	-1,			/* 14: ICMP_TSTAMPREPLY */
4224 	-1,			/* 15: ICMP_IREQ */
4225 	-1,			/* 16: ICMP_IREQREPLY */
4226 	-1,			/* 17: ICMP_MASKREQ */
4227 	-1,			/* 18: ICMP_MASKREPLY */
4228 };
4229 
4230 
4231 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4232 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
4233 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
4234 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
4235 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
4236 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
4237 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
4238 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
4239 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
4240 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
4241 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
4242 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
4243 	-1,				/* 11: ICMP_UNREACH_TOSNET */
4244 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
4245 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4246 };
4247 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
4248 #endif
4249 
4250 int	icmpreplytype4[ICMP_MAXTYPE + 1];
4251 
4252 
4253 /* ------------------------------------------------------------------------ */
4254 /* Function:    ipf_matchicmpqueryreply                                     */
4255 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4256 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4257 /*              ic(I)   - ICMP information                                  */
4258 /*              icmp(I) - ICMP packet header                                */
4259 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4260 /*                                                                          */
4261 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4262 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4263 /* else return 0 for no match.                                              */
4264 /* ------------------------------------------------------------------------ */
4265 int
ipf_matchicmpqueryreply(int v,icmpinfo_t * ic,icmphdr_t * icmp,int rev)4266 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4267 {
4268 	int ictype;
4269 
4270 	ictype = ic->ici_type;
4271 
4272 	if (v == 4) {
4273 		/*
4274 		 * If we matched its type on the way in, then when going out
4275 		 * it will still be the same type.
4276 		 */
4277 		if ((!rev && (icmp->icmp_type == ictype)) ||
4278 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4279 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4280 				return (1);
4281 			if (icmp->icmp_id == ic->ici_id)
4282 				return (1);
4283 		}
4284 	}
4285 #ifdef	USE_INET6
4286 	else if (v == 6) {
4287 		if ((!rev && (icmp->icmp_type == ictype)) ||
4288 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4289 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4290 				return (1);
4291 			if (icmp->icmp_id == ic->ici_id)
4292 				return (1);
4293 		}
4294 	}
4295 #endif
4296 	return (0);
4297 }
4298 
4299 
4300 /*
4301  * IFNAMES are located in the variable length field starting at
4302  * frentry.fr_names. As pointers within the struct cannot be passed
4303  * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4304  * is unused (invalid). If it is used (valid) it is an offset to the
4305  * character string of an interface name or a comment. The following
4306  * macros will assist those who follow to understand the code.
4307  */
4308 #define IPF_IFNAME_VALID(_a)	(_a != -1)
4309 #define IPF_IFNAME_INVALID(_a)	(_a == -1)
4310 #define IPF_IFNAMES_DIFFERENT(_a)	\
4311 	!((IPF_IFNAME_INVALID(fr1->_a) &&	\
4312 	IPF_IFNAME_INVALID(fr2->_a)) ||	\
4313 	(IPF_IFNAME_VALID(fr1->_a) &&	\
4314 	IPF_IFNAME_VALID(fr2->_a) &&	\
4315 	!strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4316 #define IPF_FRDEST_DIFFERENT(_a)	\
4317 	(memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr,	\
4318 	offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) ||	\
4319 	IPF_IFNAMES_DIFFERENT(_a.fd_name))
4320 
4321 
4322 /* ------------------------------------------------------------------------ */
4323 /* Function:    ipf_rule_compare                                            */
4324 /* Parameters:  fr1(I) - first rule structure to compare                    */
4325 /*              fr2(I) - second rule structure to compare                   */
4326 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4327 /*                                                                          */
4328 /* Compare two rules and return 0 if they match or a number indicating      */
4329 /* which of the individual checks failed.                                   */
4330 /* ------------------------------------------------------------------------ */
4331 static int
ipf_rule_compare(frentry_t * fr1,frentry_t * fr2)4332 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4333 {
4334 	int i;
4335 
4336 	if (fr1->fr_cksum != fr2->fr_cksum)
4337 		return (1);
4338 	if (fr1->fr_size != fr2->fr_size)
4339 		return (2);
4340 	if (fr1->fr_dsize != fr2->fr_dsize)
4341 		return (3);
4342 	if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4343 	    != 0)
4344 		return (4);
4345 	/*
4346 	 * XXX:	There is still a bug here as different rules with the
4347 	 *	the same interfaces but in a different order will compare
4348 	 *	differently. But since multiple interfaces in a rule doesn't
4349 	 *	work anyway a simple straightforward compare is performed
4350 	 *	here. Ultimately frentry_t creation will need to be
4351 	 *	revisited in ipf_y.y. While the other issue, recognition
4352 	 *	of only the first interface in a list of interfaces will
4353 	 *	need to be separately addressed along with why only four.
4354 	 */
4355 	for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4356 		/*
4357 		 * XXX:	It's either the same index or uninitialized.
4358 		 * 	We assume this because multiple interfaces
4359 		 *	referenced by the same rule doesn't work anyway.
4360 		 */
4361 		if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4362 			return (5);
4363 	}
4364 
4365 	if (IPF_FRDEST_DIFFERENT(fr_tif))
4366 		return (6);
4367 	if (IPF_FRDEST_DIFFERENT(fr_rif))
4368 		return (7);
4369 	if (IPF_FRDEST_DIFFERENT(fr_dif))
4370 		return (8);
4371 	if (!fr1->fr_data && !fr2->fr_data)
4372 		return (0);	/* move along, nothing to see here */
4373 	if (fr1->fr_data && fr2->fr_data) {
4374 		if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4375 			return (0);	/* same */
4376 	}
4377 	return (9);
4378 }
4379 
4380 
4381 /* ------------------------------------------------------------------------ */
4382 /* Function:    frrequest                                                   */
4383 /* Returns:     int - 0 == success, > 0 == errno value                      */
4384 /* Parameters:  unit(I)     - device for which this is for                  */
4385 /*              req(I)      - ioctl command (SIOC*)                         */
4386 /*              data(I)     - pointr to ioctl data                          */
4387 /*              set(I)      - 1 or 0 (filter set)                           */
4388 /*              makecopy(I) - flag indicating whether data points to a rule */
4389 /*                            in kernel space & hence doesn't need copying. */
4390 /*                                                                          */
4391 /* This function handles all the requests which operate on the list of      */
4392 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4393 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4394 /* names are resolved here and other sanity checks are made on the content  */
4395 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4396 /* then make sure they are created and initialised before exiting.          */
4397 /* ------------------------------------------------------------------------ */
4398 int
frrequest(ipf_main_softc_t * softc,int unit,ioctlcmd_t req,caddr_t data,int set,int makecopy)4399 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, caddr_t data,
4400 	int set, int makecopy)
4401 {
4402 	int error = 0, in, family, need_free = 0;
4403 	enum {	OP_ADD,		/* add rule */
4404 		OP_REM,		/* remove rule */
4405 		OP_ZERO 	/* zero statistics and counters */ }
4406 		addrem = OP_ADD;
4407 	frentry_t frd, *fp, *f, **fprev, **ftail;
4408 	void *ptr, *uptr;
4409 	u_int *p, *pp;
4410 	frgroup_t *fg;
4411 	char *group;
4412 
4413 	ptr = NULL;
4414 	fg = NULL;
4415 	fp = &frd;
4416 	if (makecopy != 0) {
4417 		bzero(fp, sizeof(frd));
4418 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4419 		if (error) {
4420 			return (error);
4421 		}
4422 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4423 			IPFERROR(6);
4424 			return (EINVAL);
4425 		}
4426 		KMALLOCS(f, frentry_t *, fp->fr_size);
4427 		if (f == NULL) {
4428 			IPFERROR(131);
4429 			return (ENOMEM);
4430 		}
4431 		bzero(f, fp->fr_size);
4432 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4433 				    fp->fr_size);
4434 		if (error) {
4435 			KFREES(f, fp->fr_size);
4436 			return (error);
4437 		}
4438 
4439 		fp = f;
4440 		f = NULL;
4441 		fp->fr_next = NULL;
4442 		fp->fr_dnext = NULL;
4443 		fp->fr_pnext = NULL;
4444 		fp->fr_pdnext = NULL;
4445 		fp->fr_grp = NULL;
4446 		fp->fr_grphead = NULL;
4447 		fp->fr_icmpgrp = NULL;
4448 		fp->fr_isc = (void *)-1;
4449 		fp->fr_ptr = NULL;
4450 		fp->fr_ref = 0;
4451 		fp->fr_flags |= FR_COPIED;
4452 	} else {
4453 		fp = (frentry_t *)data;
4454 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4455 			IPFERROR(7);
4456 			return (EINVAL);
4457 		}
4458 		fp->fr_flags &= ~FR_COPIED;
4459 	}
4460 
4461 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4462 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4463 		IPFERROR(8);
4464 		error = EINVAL;
4465 		goto donenolock;
4466 	}
4467 
4468 	family = fp->fr_family;
4469 	uptr = fp->fr_data;
4470 
4471 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4472 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4473 		addrem = OP_ADD;	/* Add rule */
4474 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4475 		addrem = OP_REM;		/* Remove rule */
4476 	else if (req == (ioctlcmd_t)SIOCZRLST)
4477 		addrem = OP_ZERO;	/* Zero statistics and counters */
4478 	else {
4479 		IPFERROR(9);
4480 		error = EINVAL;
4481 		goto donenolock;
4482 	}
4483 
4484 	/*
4485 	 * Only filter rules for IPv4 or IPv6 are accepted.
4486 	 */
4487 	if (family == AF_INET) {
4488 		/*EMPTY*/;
4489 #ifdef	USE_INET6
4490 	} else if (family == AF_INET6) {
4491 		/*EMPTY*/;
4492 #endif
4493 	} else if (family != 0) {
4494 		IPFERROR(10);
4495 		error = EINVAL;
4496 		goto donenolock;
4497 	}
4498 
4499 	/*
4500 	 * If the rule is being loaded from user space, i.e. we had to copy it
4501 	 * into kernel space, then do not trust the function pointer in the
4502 	 * rule.
4503 	 */
4504 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4505 		if (ipf_findfunc(fp->fr_func) == NULL) {
4506 			IPFERROR(11);
4507 			error = ESRCH;
4508 			goto donenolock;
4509 		}
4510 
4511 		if (addrem == OP_ADD) {
4512 			error = ipf_funcinit(softc, fp);
4513 			if (error != 0)
4514 				goto donenolock;
4515 		}
4516 	}
4517 	if ((fp->fr_flags & FR_CALLNOW) &&
4518 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4519 		IPFERROR(142);
4520 		error = ESRCH;
4521 		goto donenolock;
4522 	}
4523 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4524 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4525 		IPFERROR(143);
4526 		error = ESRCH;
4527 		goto donenolock;
4528 	}
4529 
4530 	ptr = NULL;
4531 
4532 	if (FR_ISACCOUNT(fp->fr_flags))
4533 		unit = IPL_LOGCOUNT;
4534 
4535 	/*
4536 	 * Check that each group name in the rule has a start index that
4537 	 * is valid.
4538 	 */
4539 	if (fp->fr_icmphead != -1) {
4540 		if ((fp->fr_icmphead < 0) ||
4541 		    (fp->fr_icmphead >= fp->fr_namelen)) {
4542 			IPFERROR(136);
4543 			error = EINVAL;
4544 			goto donenolock;
4545 		}
4546 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4547 			fp->fr_names[fp->fr_icmphead] = '\0';
4548 	}
4549 
4550 	if (fp->fr_grhead != -1) {
4551 		if ((fp->fr_grhead < 0) ||
4552 		    (fp->fr_grhead >= fp->fr_namelen)) {
4553 			IPFERROR(137);
4554 			error = EINVAL;
4555 			goto donenolock;
4556 		}
4557 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4558 			fp->fr_names[fp->fr_grhead] = '\0';
4559 	}
4560 
4561 	if (fp->fr_group != -1) {
4562 		if ((fp->fr_group < 0) ||
4563 		    (fp->fr_group >= fp->fr_namelen)) {
4564 			IPFERROR(138);
4565 			error = EINVAL;
4566 			goto donenolock;
4567 		}
4568 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4569 			/*
4570 			 * Allow loading rules that are in groups to cause
4571 			 * them to be created if they don't already exit.
4572 			 */
4573 			group = FR_NAME(fp, fr_group);
4574 			if (addrem == OP_ADD) {
4575 				fg = ipf_group_add(softc, group, NULL,
4576 						   fp->fr_flags, unit, set);
4577 				fp->fr_grp = fg;
4578 			} else {
4579 				fg = ipf_findgroup(softc, group, unit,
4580 						   set, NULL);
4581 				if (fg == NULL) {
4582 					IPFERROR(12);
4583 					error = ESRCH;
4584 					goto donenolock;
4585 				}
4586 			}
4587 
4588 			if (fg->fg_flags == 0) {
4589 				fg->fg_flags = fp->fr_flags & FR_INOUT;
4590 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4591 				IPFERROR(13);
4592 				error = ESRCH;
4593 				goto donenolock;
4594 			}
4595 		}
4596 	} else {
4597 		/*
4598 		 * If a rule is going to be part of a group then it does
4599 		 * not matter whether it is an in or out rule, but if it
4600 		 * isn't in a group, then it does...
4601 		 */
4602 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4603 			IPFERROR(14);
4604 			error = EINVAL;
4605 			goto donenolock;
4606 		}
4607 	}
4608 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4609 
4610 	/*
4611 	 * Work out which rule list this change is being applied to.
4612 	 */
4613 	ftail = NULL;
4614 	fprev = NULL;
4615 	if (unit == IPL_LOGAUTH) {
4616 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4617 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
4618 		    (fp->fr_dif.fd_ptr != NULL) ||
4619 		    (fp->fr_flags & FR_FASTROUTE)) {
4620 			softc->ipf_interror = 145;
4621 			error = EINVAL;
4622 			goto donenolock;
4623 		}
4624 		fprev = ipf_auth_rulehead(softc);
4625 	} else {
4626 		if (FR_ISACCOUNT(fp->fr_flags))
4627 			fprev = &softc->ipf_acct[in][set];
4628 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4629 			fprev = &softc->ipf_rules[in][set];
4630 	}
4631 	if (fprev == NULL) {
4632 		IPFERROR(15);
4633 		error = ESRCH;
4634 		goto donenolock;
4635 	}
4636 
4637 	if (fg != NULL)
4638 		fprev = &fg->fg_start;
4639 
4640 	/*
4641 	 * Copy in extra data for the rule.
4642 	 */
4643 	if (fp->fr_dsize != 0) {
4644 		if (makecopy != 0) {
4645 			KMALLOCS(ptr, void *, fp->fr_dsize);
4646 			if (ptr == NULL) {
4647 				IPFERROR(16);
4648 				error = ENOMEM;
4649 				goto donenolock;
4650 			}
4651 
4652 			/*
4653 			 * The bcopy case is for when the data is appended
4654 			 * to the rule by ipf_in_compat().
4655 			 */
4656 			if (uptr >= (void *)fp &&
4657 			    uptr < (void *)((char *)fp + fp->fr_size)) {
4658 				bcopy(uptr, ptr, fp->fr_dsize);
4659 				error = 0;
4660 			} else {
4661 				error = COPYIN(uptr, ptr, fp->fr_dsize);
4662 				if (error != 0) {
4663 					IPFERROR(17);
4664 					error = EFAULT;
4665 					goto donenolock;
4666 				}
4667 			}
4668 		} else {
4669 			ptr = uptr;
4670 		}
4671 		fp->fr_data = ptr;
4672 	} else {
4673 		fp->fr_data = NULL;
4674 	}
4675 
4676 	/*
4677 	 * Perform per-rule type sanity checks of their members.
4678 	 * All code after this needs to be aware that allocated memory
4679 	 * may need to be free'd before exiting.
4680 	 */
4681 	switch (fp->fr_type & ~FR_T_BUILTIN)
4682 	{
4683 #if defined(IPFILTER_BPF)
4684 	case FR_T_BPFOPC :
4685 		if (fp->fr_dsize == 0) {
4686 			IPFERROR(19);
4687 			error = EINVAL;
4688 			break;
4689 		}
4690 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4691 			IPFERROR(20);
4692 			error = EINVAL;
4693 			break;
4694 		}
4695 		break;
4696 #endif
4697 	case FR_T_IPF :
4698 		/*
4699 		 * Preparation for error case at the bottom of this function.
4700 		 */
4701 		if (fp->fr_datype == FRI_LOOKUP)
4702 			fp->fr_dstptr = NULL;
4703 		if (fp->fr_satype == FRI_LOOKUP)
4704 			fp->fr_srcptr = NULL;
4705 
4706 		if (fp->fr_dsize != sizeof(fripf_t)) {
4707 			IPFERROR(21);
4708 			error = EINVAL;
4709 			break;
4710 		}
4711 
4712 		/*
4713 		 * Allowing a rule with both "keep state" and "with oow" is
4714 		 * pointless because adding a state entry to the table will
4715 		 * fail with the out of window (oow) flag set.
4716 		 */
4717 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4718 			IPFERROR(22);
4719 			error = EINVAL;
4720 			break;
4721 		}
4722 
4723 		switch (fp->fr_satype)
4724 		{
4725 		case FRI_BROADCAST :
4726 		case FRI_DYNAMIC :
4727 		case FRI_NETWORK :
4728 		case FRI_NETMASKED :
4729 		case FRI_PEERADDR :
4730 			if (fp->fr_sifpidx < 0) {
4731 				IPFERROR(23);
4732 				error = EINVAL;
4733 			}
4734 			break;
4735 		case FRI_LOOKUP :
4736 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4737 						       &fp->fr_src6,
4738 						       &fp->fr_smsk6);
4739 			if (fp->fr_srcfunc == NULL) {
4740 				IPFERROR(132);
4741 				error = ESRCH;
4742 				break;
4743 			}
4744 			break;
4745 		case FRI_NORMAL :
4746 			break;
4747 		default :
4748 			IPFERROR(133);
4749 			error = EINVAL;
4750 			break;
4751 		}
4752 		if (error != 0)
4753 			break;
4754 
4755 		switch (fp->fr_datype)
4756 		{
4757 		case FRI_BROADCAST :
4758 		case FRI_DYNAMIC :
4759 		case FRI_NETWORK :
4760 		case FRI_NETMASKED :
4761 		case FRI_PEERADDR :
4762 			if (fp->fr_difpidx < 0) {
4763 				IPFERROR(24);
4764 				error = EINVAL;
4765 			}
4766 			break;
4767 		case FRI_LOOKUP :
4768 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4769 						       &fp->fr_dst6,
4770 						       &fp->fr_dmsk6);
4771 			if (fp->fr_dstfunc == NULL) {
4772 				IPFERROR(134);
4773 				error = ESRCH;
4774 			}
4775 			break;
4776 		case FRI_NORMAL :
4777 			break;
4778 		default :
4779 			IPFERROR(135);
4780 			error = EINVAL;
4781 		}
4782 		break;
4783 
4784 	case FR_T_NONE :
4785 	case FR_T_CALLFUNC :
4786 	case FR_T_COMPIPF :
4787 		break;
4788 
4789 	case FR_T_IPFEXPR :
4790 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4791 			IPFERROR(25);
4792 			error = EINVAL;
4793 		}
4794 		break;
4795 
4796 	default :
4797 		IPFERROR(26);
4798 		error = EINVAL;
4799 		break;
4800 	}
4801 	if (error != 0)
4802 		goto donenolock;
4803 
4804 	if (fp->fr_tif.fd_name != -1) {
4805 		if ((fp->fr_tif.fd_name < 0) ||
4806 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4807 			IPFERROR(139);
4808 			error = EINVAL;
4809 			goto donenolock;
4810 		}
4811 	}
4812 
4813 	if (fp->fr_dif.fd_name != -1) {
4814 		if ((fp->fr_dif.fd_name < 0) ||
4815 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4816 			IPFERROR(140);
4817 			error = EINVAL;
4818 			goto donenolock;
4819 		}
4820 	}
4821 
4822 	if (fp->fr_rif.fd_name != -1) {
4823 		if ((fp->fr_rif.fd_name < 0) ||
4824 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4825 			IPFERROR(141);
4826 			error = EINVAL;
4827 			goto donenolock;
4828 		}
4829 	}
4830 
4831 	/*
4832 	 * Lookup all the interface names that are part of the rule.
4833 	 */
4834 	error = ipf_synclist(softc, fp, NULL);
4835 	if (error != 0)
4836 		goto donenolock;
4837 	fp->fr_statecnt = 0;
4838 	if (fp->fr_srctrack.ht_max_nodes != 0)
4839 		ipf_rb_ht_init(&fp->fr_srctrack);
4840 
4841 	/*
4842 	 * Look for an existing matching filter rule, but don't include the
4843 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4844 	 * This elminates rules which are indentical being loaded.  Checksum
4845 	 * the constant part of the filter rule to make comparisons quicker
4846 	 * (this meaning no pointers are included).
4847 	 */
4848 	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4849 	for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4850 		fp->fr_cksum += *p;
4851 
4852 	WRITE_ENTER(&softc->ipf_mutex);
4853 
4854 	/*
4855 	 * Now that the filter rule lists are locked, we can walk the
4856 	 * chain of them without fear.
4857 	 */
4858 	ftail = fprev;
4859 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4860 		if (fp->fr_collect <= f->fr_collect) {
4861 			ftail = fprev;
4862 			f = NULL;
4863 			break;
4864 		}
4865 		fprev = ftail;
4866 	}
4867 
4868 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4869 		if (ipf_rule_compare(fp, f) == 0)
4870 			break;
4871 	}
4872 
4873 	/*
4874 	 * If zero'ing statistics, copy current to caller and zero.
4875 	 */
4876 	if (addrem == OP_ZERO) {
4877 		if (f == NULL) {
4878 			IPFERROR(27);
4879 			error = ESRCH;
4880 		} else {
4881 			/*
4882 			 * Copy and reduce lock because of impending copyout.
4883 			 * Well we should, but if we do then the atomicity of
4884 			 * this call and the correctness of fr_hits and
4885 			 * fr_bytes cannot be guaranteed.  As it is, this code
4886 			 * only resets them to 0 if they are successfully
4887 			 * copied out into user space.
4888 			 */
4889 			bcopy((char *)f, (char *)fp, f->fr_size);
4890 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4891 
4892 			/*
4893 			 * When we copy this rule back out, set the data
4894 			 * pointer to be what it was in user space.
4895 			 */
4896 			fp->fr_data = uptr;
4897 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4898 
4899 			if (error == 0) {
4900 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
4901 					error = COPYOUT(f->fr_data, uptr,
4902 							f->fr_dsize);
4903 					if (error == 0) {
4904 						f->fr_hits = 0;
4905 						f->fr_bytes = 0;
4906 					} else {
4907 						IPFERROR(28);
4908 						error = EFAULT;
4909 					}
4910 				}
4911 			}
4912 		}
4913 
4914 		if (makecopy != 0) {
4915 			if (ptr != NULL) {
4916 				KFREES(ptr, fp->fr_dsize);
4917 			}
4918 			KFREES(fp, fp->fr_size);
4919 		}
4920 		RWLOCK_EXIT(&softc->ipf_mutex);
4921 		return (error);
4922 	}
4923 
4924 	if (f == NULL) {
4925 		/*
4926 		 * At the end of this, ftail must point to the place where the
4927 		 * new rule is to be saved/inserted/added.
4928 		 * For SIOCAD*FR, this should be the last rule in the group of
4929 		 * rules that have equal fr_collect fields.
4930 		 * For SIOCIN*FR, ...
4931 		 */
4932 		if (req == (ioctlcmd_t)SIOCADAFR ||
4933 		    req == (ioctlcmd_t)SIOCADIFR) {
4934 
4935 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4936 				if (f->fr_collect > fp->fr_collect)
4937 					break;
4938 				ftail = &f->fr_next;
4939 				fprev = ftail;
4940 			}
4941 			ftail = fprev;
4942 			f = NULL;
4943 			ptr = NULL;
4944 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4945 			   req == (ioctlcmd_t)SIOCINIFR) {
4946 			while ((f = *fprev) != NULL) {
4947 				if (f->fr_collect >= fp->fr_collect)
4948 					break;
4949 				fprev = &f->fr_next;
4950 			}
4951   			ftail = fprev;
4952   			if (fp->fr_hits != 0) {
4953 				while (fp->fr_hits && (f = *ftail)) {
4954 					if (f->fr_collect != fp->fr_collect)
4955 						break;
4956 					fprev = ftail;
4957   					ftail = &f->fr_next;
4958 					fp->fr_hits--;
4959 				}
4960   			}
4961   			f = NULL;
4962   			ptr = NULL;
4963 		}
4964 	}
4965 
4966 	/*
4967 	 * Request to remove a rule.
4968 	 */
4969 	if (addrem == OP_REM) {
4970 		if (f == NULL) {
4971 			IPFERROR(29);
4972 			error = ESRCH;
4973 		} else {
4974 			/*
4975 			 * Do not allow activity from user space to interfere
4976 			 * with rules not loaded that way.
4977 			 */
4978 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4979 				IPFERROR(30);
4980 				error = EPERM;
4981 				goto done;
4982 			}
4983 
4984 			/*
4985 			 * Return EBUSY if the rule is being reference by
4986 			 * something else (eg state information.)
4987 			 */
4988 			if (f->fr_ref > 1) {
4989 				IPFERROR(31);
4990 				error = EBUSY;
4991 				goto done;
4992 			}
4993 #ifdef	IPFILTER_SCAN
4994 			if (f->fr_isctag != -1 &&
4995 			    (f->fr_isc != (struct ipscan *)-1))
4996 				ipf_scan_detachfr(f);
4997 #endif
4998 
4999 			if (unit == IPL_LOGAUTH) {
5000 				error = ipf_auth_precmd(softc, req, f, ftail);
5001 				goto done;
5002 			}
5003 
5004 			ipf_rule_delete(softc, f, unit, set);
5005 
5006 			need_free = makecopy;
5007 		}
5008 	} else {
5009 		/*
5010 		 * Not removing, so we must be adding/inserting a rule.
5011 		 */
5012 		if (f != NULL) {
5013 			IPFERROR(32);
5014 			error = EEXIST;
5015 			goto done;
5016 		}
5017 		if (unit == IPL_LOGAUTH) {
5018 			error = ipf_auth_precmd(softc, req, fp, ftail);
5019 			goto done;
5020 		}
5021 
5022 		MUTEX_NUKE(&fp->fr_lock);
5023 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5024 		if (fp->fr_die != 0)
5025 			ipf_rule_expire_insert(softc, fp, set);
5026 
5027 		fp->fr_hits = 0;
5028 		if (makecopy != 0)
5029 			fp->fr_ref = 1;
5030 		fp->fr_pnext = ftail;
5031 		fp->fr_next = *ftail;
5032 		if (fp->fr_next != NULL)
5033 			fp->fr_next->fr_pnext = &fp->fr_next;
5034 		*ftail = fp;
5035 		ipf_fixskip(ftail, fp, 1);
5036 
5037 		fp->fr_icmpgrp = NULL;
5038 		if (fp->fr_icmphead != -1) {
5039 			group = FR_NAME(fp, fr_icmphead);
5040 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
5041 			fp->fr_icmpgrp = fg;
5042 		}
5043 
5044 		fp->fr_grphead = NULL;
5045 		if (fp->fr_grhead != -1) {
5046 			group = FR_NAME(fp, fr_grhead);
5047 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5048 					   unit, set);
5049 			fp->fr_grphead = fg;
5050 		}
5051 	}
5052 done:
5053 	RWLOCK_EXIT(&softc->ipf_mutex);
5054 donenolock:
5055 	if (need_free || (error != 0)) {
5056 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5057 			if ((fp->fr_satype == FRI_LOOKUP) &&
5058 			    (fp->fr_srcptr != NULL))
5059 				ipf_lookup_deref(softc, fp->fr_srctype,
5060 						 fp->fr_srcptr);
5061 			if ((fp->fr_datype == FRI_LOOKUP) &&
5062 			    (fp->fr_dstptr != NULL))
5063 				ipf_lookup_deref(softc, fp->fr_dsttype,
5064 						 fp->fr_dstptr);
5065 		}
5066 		if (fp->fr_grp != NULL) {
5067 			WRITE_ENTER(&softc->ipf_mutex);
5068 			ipf_group_del(softc, fp->fr_grp, fp);
5069 			RWLOCK_EXIT(&softc->ipf_mutex);
5070 		}
5071 		if ((ptr != NULL) && (makecopy != 0)) {
5072 			KFREES(ptr, fp->fr_dsize);
5073 		}
5074 		KFREES(fp, fp->fr_size);
5075 	}
5076 	return (error);
5077 }
5078 
5079 
5080 /* ------------------------------------------------------------------------ */
5081 /* Function:   ipf_rule_delete                                              */
5082 /* Returns:    Nil                                                          */
5083 /* Parameters: softc(I) - pointer to soft context main structure            */
5084 /*             f(I)     - pointer to the rule being deleted                 */
5085 /*             ftail(I) - pointer to the pointer to f                       */
5086 /*             unit(I)  - device for which this is for                      */
5087 /*             set(I)   - 1 or 0 (filter set)                               */
5088 /*                                                                          */
5089 /* This function attempts to do what it can to delete a filter rule: remove */
5090 /* it from any linked lists and remove any groups it is responsible for.    */
5091 /* But in the end, removing a rule can only drop the reference count - we   */
5092 /* must use that as the guide for whether or not it can be freed.           */
5093 /* ------------------------------------------------------------------------ */
5094 static void
ipf_rule_delete(ipf_main_softc_t * softc,frentry_t * f,int unit,int set)5095 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5096 {
5097 
5098 	/*
5099 	 * If fr_pdnext is set, then the rule is on the expire list, so
5100 	 * remove it from there.
5101 	 */
5102 	if (f->fr_pdnext != NULL) {
5103 		*f->fr_pdnext = f->fr_dnext;
5104 		if (f->fr_dnext != NULL)
5105 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
5106 		f->fr_pdnext = NULL;
5107 		f->fr_dnext = NULL;
5108 	}
5109 
5110 	ipf_fixskip(f->fr_pnext, f, -1);
5111 	if (f->fr_pnext != NULL)
5112 		*f->fr_pnext = f->fr_next;
5113 	if (f->fr_next != NULL)
5114 		f->fr_next->fr_pnext = f->fr_pnext;
5115 	f->fr_pnext = NULL;
5116 	f->fr_next = NULL;
5117 
5118 	(void) ipf_derefrule(softc, &f);
5119 }
5120 
5121 /* ------------------------------------------------------------------------ */
5122 /* Function:   ipf_rule_expire_insert                                       */
5123 /* Returns:    Nil                                                          */
5124 /* Parameters: softc(I) - pointer to soft context main structure            */
5125 /*             f(I)     - pointer to rule to be added to expire list        */
5126 /*             set(I)   - 1 or 0 (filter set)                               */
5127 /*                                                                          */
5128 /* If the new rule has a given expiration time, insert it into the list of  */
5129 /* expiring rules with the ones to be removed first added to the front of   */
5130 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5131 /* expiration interval checks.                                              */
5132 /* ------------------------------------------------------------------------ */
5133 static void
ipf_rule_expire_insert(ipf_main_softc_t * softc,frentry_t * f,int set)5134 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5135 {
5136 	frentry_t *fr;
5137 
5138 	/*
5139 	 */
5140 
5141 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5142 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5143 	     fr = fr->fr_dnext) {
5144 		if (f->fr_die < fr->fr_die)
5145 			break;
5146 		if (fr->fr_dnext == NULL) {
5147 			/*
5148 			 * We've got to the last rule and everything
5149 			 * wanted to be expired before this new node,
5150 			 * so we have to tack it on the end...
5151 			 */
5152 			fr->fr_dnext = f;
5153 			f->fr_pdnext = &fr->fr_dnext;
5154 			fr = NULL;
5155 			break;
5156 		}
5157 	}
5158 
5159 	if (softc->ipf_rule_explist[set] == NULL) {
5160 		softc->ipf_rule_explist[set] = f;
5161 		f->fr_pdnext = &softc->ipf_rule_explist[set];
5162 	} else if (fr != NULL) {
5163 		f->fr_dnext = fr;
5164 		f->fr_pdnext = fr->fr_pdnext;
5165 		fr->fr_pdnext = &f->fr_dnext;
5166 	}
5167 }
5168 
5169 
5170 /* ------------------------------------------------------------------------ */
5171 /* Function:   ipf_findlookup                                               */
5172 /* Returns:    NULL = failure, else success                                 */
5173 /* Parameters: softc(I) - pointer to soft context main structure            */
5174 /*             unit(I)  - ipf device we want to find match for              */
5175 /*             fp(I)    - rule for which lookup is for                      */
5176 /*             addrp(I) - pointer to lookup information in address struct   */
5177 /*             maskp(O) - pointer to lookup information for storage         */
5178 /*                                                                          */
5179 /* When using pools and hash tables to store addresses for matching in      */
5180 /* rules, it is necessary to resolve both the object referred to by the     */
5181 /* name or address (and return that pointer) and also provide the means by  */
5182 /* which to determine if an address belongs to that object to make the      */
5183 /* packet matching quicker.                                                 */
5184 /* ------------------------------------------------------------------------ */
5185 static void *
ipf_findlookup(ipf_main_softc_t * softc,int unit,frentry_t * fr,i6addr_t * addrp,i6addr_t * maskp)5186 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5187 	i6addr_t *addrp, i6addr_t *maskp)
5188 {
5189 	void *ptr = NULL;
5190 
5191 	switch (addrp->iplookupsubtype)
5192 	{
5193 	case 0 :
5194 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5195 					 addrp->iplookupnum,
5196 					 &maskp->iplookupfunc);
5197 		break;
5198 	case 1 :
5199 		if (addrp->iplookupname < 0)
5200 			break;
5201 		if (addrp->iplookupname >= fr->fr_namelen)
5202 			break;
5203 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5204 					  fr->fr_names + addrp->iplookupname,
5205 					  &maskp->iplookupfunc);
5206 		break;
5207 	default :
5208 		break;
5209 	}
5210 
5211 	return (ptr);
5212 }
5213 
5214 
5215 /* ------------------------------------------------------------------------ */
5216 /* Function:    ipf_funcinit                                                */
5217 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5218 /* Parameters:  softc(I) - pointer to soft context main structure           */
5219 /*              fr(I)    - pointer to filter rule                           */
5220 /*                                                                          */
5221 /* If a rule is a call rule, then check if the function it points to needs  */
5222 /* an init function to be called now the rule has been loaded.              */
5223 /* ------------------------------------------------------------------------ */
5224 static int
ipf_funcinit(ipf_main_softc_t * softc,frentry_t * fr)5225 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5226 {
5227 	ipfunc_resolve_t *ft;
5228 	int err;
5229 
5230 	IPFERROR(34);
5231 	err = ESRCH;
5232 
5233 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5234 		if (ft->ipfu_addr == fr->fr_func) {
5235 			err = 0;
5236 			if (ft->ipfu_init != NULL)
5237 				err = (*ft->ipfu_init)(softc, fr);
5238 			break;
5239 		}
5240 	return (err);
5241 }
5242 
5243 
5244 /* ------------------------------------------------------------------------ */
5245 /* Function:    ipf_funcfini                                                */
5246 /* Returns:     Nil                                                         */
5247 /* Parameters:  softc(I) - pointer to soft context main structure           */
5248 /*              fr(I)    - pointer to filter rule                           */
5249 /*                                                                          */
5250 /* For a given filter rule, call the matching "fini" function if the rule   */
5251 /* is using a known function that would have resulted in the "init" being   */
5252 /* called for ealier.                                                       */
5253 /* ------------------------------------------------------------------------ */
5254 static void
ipf_funcfini(ipf_main_softc_t * softc,frentry_t * fr)5255 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5256 {
5257 	ipfunc_resolve_t *ft;
5258 
5259 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5260 		if (ft->ipfu_addr == fr->fr_func) {
5261 			if (ft->ipfu_fini != NULL)
5262 				(void) (*ft->ipfu_fini)(softc, fr);
5263 			break;
5264 		}
5265 }
5266 
5267 
5268 /* ------------------------------------------------------------------------ */
5269 /* Function:    ipf_findfunc                                                */
5270 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5271 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5272 /*                                                                          */
5273 /* Look for a function in the table of known functions.                     */
5274 /* ------------------------------------------------------------------------ */
5275 static ipfunc_t
ipf_findfunc(ipfunc_t funcptr)5276 ipf_findfunc(ipfunc_t funcptr)
5277 {
5278 	ipfunc_resolve_t *ft;
5279 
5280 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5281 		if (ft->ipfu_addr == funcptr)
5282 			return (funcptr);
5283 	return (NULL);
5284 }
5285 
5286 
5287 /* ------------------------------------------------------------------------ */
5288 /* Function:    ipf_resolvefunc                                             */
5289 /* Returns:     int - 0 == success, else error                              */
5290 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5291 /*                                                                          */
5292 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5293 /* This will either be the function name (if the pointer is set) or the     */
5294 /* function pointer if the name is set.  When found, fill in the other one  */
5295 /* so that the entire, complete, structure can be copied back to user space.*/
5296 /* ------------------------------------------------------------------------ */
5297 int
ipf_resolvefunc(ipf_main_softc_t * softc,void * data)5298 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5299 {
5300 	ipfunc_resolve_t res, *ft;
5301 	int error;
5302 
5303 	error = BCOPYIN(data, &res, sizeof(res));
5304 	if (error != 0) {
5305 		IPFERROR(123);
5306 		return (EFAULT);
5307 	}
5308 
5309 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5310 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5311 			if (strncmp(res.ipfu_name, ft->ipfu_name,
5312 				    sizeof(res.ipfu_name)) == 0) {
5313 				res.ipfu_addr = ft->ipfu_addr;
5314 				res.ipfu_init = ft->ipfu_init;
5315 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5316 					IPFERROR(35);
5317 					return (EFAULT);
5318 				}
5319 				return (0);
5320 			}
5321 	}
5322 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5323 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5324 			if (ft->ipfu_addr == res.ipfu_addr) {
5325 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
5326 					       sizeof(res.ipfu_name));
5327 				res.ipfu_init = ft->ipfu_init;
5328 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
5329 					IPFERROR(36);
5330 					return (EFAULT);
5331 				}
5332 				return (0);
5333 			}
5334 	}
5335 	IPFERROR(37);
5336 	return (ESRCH);
5337 }
5338 
5339 
5340 #if !defined(_KERNEL) || SOLARIS
5341 /*
5342  * From: NetBSD
5343  * ppsratecheck(): packets (or events) per second limitation.
5344  */
5345 int
ppsratecheck(struct timeval * lasttime,int * curpps,int maxpps)5346 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
5347 	/* maxpps: maximum pps allowed */
5348 {
5349 	struct timeval tv, delta;
5350 	int rv;
5351 
5352 	GETKTIME(&tv);
5353 
5354 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5355 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5356 	if (delta.tv_usec < 0) {
5357 		delta.tv_sec--;
5358 		delta.tv_usec += 1000000;
5359 	}
5360 
5361 	/*
5362 	 * check for 0,0 is so that the message will be seen at least once.
5363 	 * if more than one second have passed since the last update of
5364 	 * lasttime, reset the counter.
5365 	 *
5366 	 * we do increment *curpps even in *curpps < maxpps case, as some may
5367 	 * try to use *curpps for stat purposes as well.
5368 	 */
5369 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5370 	    delta.tv_sec >= 1) {
5371 		*lasttime = tv;
5372 		*curpps = 0;
5373 		rv = 1;
5374 	} else if (maxpps < 0)
5375 		rv = 1;
5376 	else if (*curpps < maxpps)
5377 		rv = 1;
5378 	else
5379 		rv = 0;
5380 	*curpps = *curpps + 1;
5381 
5382 	return (rv);
5383 }
5384 #endif
5385 
5386 
5387 /* ------------------------------------------------------------------------ */
5388 /* Function:    ipf_derefrule                                               */
5389 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5390 /* Parameters:  fr(I) - pointer to filter rule                              */
5391 /*                                                                          */
5392 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5393 /* free it and any associated storage space being used by it.               */
5394 /* ------------------------------------------------------------------------ */
5395 int
ipf_derefrule(ipf_main_softc_t * softc,frentry_t ** frp)5396 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5397 {
5398 	frentry_t *fr;
5399 	frdest_t *fdp;
5400 
5401 	fr = *frp;
5402 	*frp = NULL;
5403 
5404 	MUTEX_ENTER(&fr->fr_lock);
5405 	fr->fr_ref--;
5406 	if (fr->fr_ref == 0) {
5407 		MUTEX_EXIT(&fr->fr_lock);
5408 		MUTEX_DESTROY(&fr->fr_lock);
5409 
5410 		ipf_funcfini(softc, fr);
5411 
5412 		fdp = &fr->fr_tif;
5413 		if (fdp->fd_type == FRD_DSTLIST)
5414 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5415 
5416 		fdp = &fr->fr_rif;
5417 		if (fdp->fd_type == FRD_DSTLIST)
5418 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5419 
5420 		fdp = &fr->fr_dif;
5421 		if (fdp->fd_type == FRD_DSTLIST)
5422 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5423 
5424 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5425 		    fr->fr_satype == FRI_LOOKUP)
5426 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5427 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5428 		    fr->fr_datype == FRI_LOOKUP)
5429 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5430 
5431 		if (fr->fr_grp != NULL)
5432 			ipf_group_del(softc, fr->fr_grp, fr);
5433 
5434 		if (fr->fr_grphead != NULL)
5435 			ipf_group_del(softc, fr->fr_grphead, fr);
5436 
5437 		if (fr->fr_icmpgrp != NULL)
5438 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
5439 
5440 		if ((fr->fr_flags & FR_COPIED) != 0) {
5441 			if (fr->fr_dsize) {
5442 				KFREES(fr->fr_data, fr->fr_dsize);
5443 			}
5444 			KFREES(fr, fr->fr_size);
5445 			return (0);
5446 		}
5447 		return (1);
5448 	} else {
5449 		MUTEX_EXIT(&fr->fr_lock);
5450 	}
5451 	return (-1);
5452 }
5453 
5454 
5455 /* ------------------------------------------------------------------------ */
5456 /* Function:    ipf_grpmapinit                                              */
5457 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5458 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5459 /*                                                                          */
5460 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5461 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5462 /* ------------------------------------------------------------------------ */
5463 static int
ipf_grpmapinit(ipf_main_softc_t * softc,frentry_t * fr)5464 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5465 {
5466 	char name[FR_GROUPLEN];
5467 	iphtable_t *iph;
5468 
5469 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5470 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5471 	if (iph == NULL) {
5472 		IPFERROR(38);
5473 		return (ESRCH);
5474 	}
5475 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5476 		IPFERROR(39);
5477 		return (ESRCH);
5478 	}
5479 	iph->iph_ref++;
5480 	fr->fr_ptr = iph;
5481 	return (0);
5482 }
5483 
5484 
5485 /* ------------------------------------------------------------------------ */
5486 /* Function:    ipf_grpmapfini                                              */
5487 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5488 /* Parameters:  softc(I) - pointer to soft context main structure           */
5489 /*              fr(I)    - pointer to rule to release hash table for        */
5490 /*                                                                          */
5491 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5492 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5493 /* ------------------------------------------------------------------------ */
5494 static int
ipf_grpmapfini(ipf_main_softc_t * softc,frentry_t * fr)5495 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5496 {
5497 	iphtable_t *iph;
5498 	iph = fr->fr_ptr;
5499 	if (iph != NULL)
5500 		ipf_lookup_deref(softc, IPLT_HASH, iph);
5501 	return (0);
5502 }
5503 
5504 
5505 /* ------------------------------------------------------------------------ */
5506 /* Function:    ipf_srcgrpmap                                               */
5507 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5508 /* Parameters:  fin(I)    - pointer to packet information                   */
5509 /*              passp(IO) - pointer to current/new filter decision (unused) */
5510 /*                                                                          */
5511 /* Look for a rule group head in a hash table, using the source address as  */
5512 /* the key, and descend into that group and continue matching rules against */
5513 /* the packet.                                                              */
5514 /* ------------------------------------------------------------------------ */
5515 frentry_t *
ipf_srcgrpmap(fr_info_t * fin,u_32_t * passp)5516 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5517 {
5518 	frgroup_t *fg;
5519 	void *rval;
5520 
5521 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5522 				 &fin->fin_src);
5523 	if (rval == NULL)
5524 		return (NULL);
5525 
5526 	fg = rval;
5527 	fin->fin_fr = fg->fg_start;
5528 	(void) ipf_scanlist(fin, *passp);
5529 	return (fin->fin_fr);
5530 }
5531 
5532 
5533 /* ------------------------------------------------------------------------ */
5534 /* Function:    ipf_dstgrpmap                                               */
5535 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5536 /* Parameters:  fin(I)    - pointer to packet information                   */
5537 /*              passp(IO) - pointer to current/new filter decision (unused) */
5538 /*                                                                          */
5539 /* Look for a rule group head in a hash table, using the destination        */
5540 /* address as the key, and descend into that group and continue matching    */
5541 /* rules against  the packet.                                               */
5542 /* ------------------------------------------------------------------------ */
5543 frentry_t *
ipf_dstgrpmap(fr_info_t * fin,u_32_t * passp)5544 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5545 {
5546 	frgroup_t *fg;
5547 	void *rval;
5548 
5549 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5550 				 &fin->fin_dst);
5551 	if (rval == NULL)
5552 		return (NULL);
5553 
5554 	fg = rval;
5555 	fin->fin_fr = fg->fg_start;
5556 	(void) ipf_scanlist(fin, *passp);
5557 	return (fin->fin_fr);
5558 }
5559 
5560 /*
5561  * Queue functions
5562  * ===============
5563  * These functions manage objects on queues for efficient timeouts.  There
5564  * are a number of system defined queues as well as user defined timeouts.
5565  * It is expected that a lock is held in the domain in which the queue
5566  * belongs (i.e. either state or NAT) when calling any of these functions
5567  * that prevents ipf_freetimeoutqueue() from being called at the same time
5568  * as any other.
5569  */
5570 
5571 
5572 /* ------------------------------------------------------------------------ */
5573 /* Function:    ipf_addtimeoutqueue                                         */
5574 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5575 /*                               timeout queue with given interval.         */
5576 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5577 /*                           of interface queues.                           */
5578 /*              seconds(I) - timeout value in seconds for this queue.       */
5579 /*                                                                          */
5580 /* This routine first looks for a timeout queue that matches the interval   */
5581 /* being requested.  If it finds one, increments the reference counter and  */
5582 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5583 /* inserts it at the top of the list.                                       */
5584 /*                                                                          */
5585 /* Locking.                                                                 */
5586 /* It is assumed that the caller of this function has an appropriate lock   */
5587 /* held (exclusively) in the domain that encompases 'parent'.               */
5588 /* ------------------------------------------------------------------------ */
5589 ipftq_t *
ipf_addtimeoutqueue(ipf_main_softc_t * softc,ipftq_t ** parent,u_int seconds)5590 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5591 {
5592 	ipftq_t *ifq;
5593 	u_int period;
5594 
5595 	period = seconds * IPF_HZ_DIVIDE;
5596 
5597 	MUTEX_ENTER(&softc->ipf_timeoutlock);
5598 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5599 		if (ifq->ifq_ttl == period) {
5600 			/*
5601 			 * Reset the delete flag, if set, so the structure
5602 			 * gets reused rather than freed and reallocated.
5603 			 */
5604 			MUTEX_ENTER(&ifq->ifq_lock);
5605 			ifq->ifq_flags &= ~IFQF_DELETE;
5606 			ifq->ifq_ref++;
5607 			MUTEX_EXIT(&ifq->ifq_lock);
5608 			MUTEX_EXIT(&softc->ipf_timeoutlock);
5609 
5610 			return (ifq);
5611 		}
5612 	}
5613 
5614 	KMALLOC(ifq, ipftq_t *);
5615 	if (ifq != NULL) {
5616 		MUTEX_NUKE(&ifq->ifq_lock);
5617 		IPFTQ_INIT(ifq, period, "ipftq mutex");
5618 		ifq->ifq_next = *parent;
5619 		ifq->ifq_pnext = parent;
5620 		ifq->ifq_flags = IFQF_USER;
5621 		ifq->ifq_ref++;
5622 		*parent = ifq;
5623 		softc->ipf_userifqs++;
5624 	}
5625 	MUTEX_EXIT(&softc->ipf_timeoutlock);
5626 	return (ifq);
5627 }
5628 
5629 
5630 /* ------------------------------------------------------------------------ */
5631 /* Function:    ipf_deletetimeoutqueue                                      */
5632 /* Returns:     int    - new reference count value of the timeout queue     */
5633 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5634 /* Locks:       ifq->ifq_lock                                               */
5635 /*                                                                          */
5636 /* This routine must be called when we're discarding a pointer to a timeout */
5637 /* queue object, taking care of the reference counter.                      */
5638 /*                                                                          */
5639 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5640 /* check the list of user defined timeout queues and call the free function */
5641 /* below (currently commented out) to stop memory leaking.  It is done this */
5642 /* way because the locking may not be sufficient to safely do a free when   */
5643 /* this function is called.                                                 */
5644 /* ------------------------------------------------------------------------ */
5645 int
ipf_deletetimeoutqueue(ipftq_t * ifq)5646 ipf_deletetimeoutqueue(ipftq_t *ifq)
5647 {
5648 
5649 	ifq->ifq_ref--;
5650 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5651 		ifq->ifq_flags |= IFQF_DELETE;
5652 	}
5653 
5654 	return (ifq->ifq_ref);
5655 }
5656 
5657 
5658 /* ------------------------------------------------------------------------ */
5659 /* Function:    ipf_freetimeoutqueue                                        */
5660 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5661 /* Returns:     Nil                                                         */
5662 /*                                                                          */
5663 /* Locking:                                                                 */
5664 /* It is assumed that the caller of this function has an appropriate lock   */
5665 /* held (exclusively) in the domain that encompases the callers "domain".   */
5666 /* The ifq_lock for this structure should not be held.                      */
5667 /*                                                                          */
5668 /* Remove a user defined timeout queue from the list of queues it is in and */
5669 /* tidy up after this is done.                                              */
5670 /* ------------------------------------------------------------------------ */
5671 void
ipf_freetimeoutqueue(ipf_main_softc_t * softc,ipftq_t * ifq)5672 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5673 {
5674 
5675 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5676 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
5677 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5678 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5679 		       ifq->ifq_ref);
5680 		return;
5681 	}
5682 
5683 	/*
5684 	 * Remove from its position in the list.
5685 	 */
5686 	*ifq->ifq_pnext = ifq->ifq_next;
5687 	if (ifq->ifq_next != NULL)
5688 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5689 	ifq->ifq_next = NULL;
5690 	ifq->ifq_pnext = NULL;
5691 
5692 	MUTEX_DESTROY(&ifq->ifq_lock);
5693 	ATOMIC_DEC(softc->ipf_userifqs);
5694 	KFREE(ifq);
5695 }
5696 
5697 
5698 /* ------------------------------------------------------------------------ */
5699 /* Function:    ipf_deletequeueentry                                        */
5700 /* Returns:     Nil                                                         */
5701 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5702 /*                                                                          */
5703 /* Remove a tail queue entry from its queue and make it an orphan.          */
5704 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5705 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5706 /* the correct lock(s) may not be held that would make it safe to do so.    */
5707 /* ------------------------------------------------------------------------ */
5708 void
ipf_deletequeueentry(ipftqent_t * tqe)5709 ipf_deletequeueentry(ipftqent_t *tqe)
5710 {
5711 	ipftq_t *ifq;
5712 
5713 	ifq = tqe->tqe_ifq;
5714 
5715 	MUTEX_ENTER(&ifq->ifq_lock);
5716 
5717 	if (tqe->tqe_pnext != NULL) {
5718 		*tqe->tqe_pnext = tqe->tqe_next;
5719 		if (tqe->tqe_next != NULL)
5720 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5721 		else    /* we must be the tail anyway */
5722 			ifq->ifq_tail = tqe->tqe_pnext;
5723 
5724 		tqe->tqe_pnext = NULL;
5725 		tqe->tqe_ifq = NULL;
5726 	}
5727 
5728 	(void) ipf_deletetimeoutqueue(ifq);
5729 	ASSERT(ifq->ifq_ref > 0);
5730 
5731 	MUTEX_EXIT(&ifq->ifq_lock);
5732 }
5733 
5734 
5735 /* ------------------------------------------------------------------------ */
5736 /* Function:    ipf_queuefront                                              */
5737 /* Returns:     Nil                                                         */
5738 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5739 /*                                                                          */
5740 /* Move a queue entry to the front of the queue, if it isn't already there. */
5741 /* ------------------------------------------------------------------------ */
5742 void
ipf_queuefront(ipftqent_t * tqe)5743 ipf_queuefront(ipftqent_t *tqe)
5744 {
5745 	ipftq_t *ifq;
5746 
5747 	ifq = tqe->tqe_ifq;
5748 	if (ifq == NULL)
5749 		return;
5750 
5751 	MUTEX_ENTER(&ifq->ifq_lock);
5752 	if (ifq->ifq_head != tqe) {
5753 		*tqe->tqe_pnext = tqe->tqe_next;
5754 		if (tqe->tqe_next)
5755 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5756 		else
5757 			ifq->ifq_tail = tqe->tqe_pnext;
5758 
5759 		tqe->tqe_next = ifq->ifq_head;
5760 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5761 		ifq->ifq_head = tqe;
5762 		tqe->tqe_pnext = &ifq->ifq_head;
5763 	}
5764 	MUTEX_EXIT(&ifq->ifq_lock);
5765 }
5766 
5767 
5768 /* ------------------------------------------------------------------------ */
5769 /* Function:    ipf_queueback                                               */
5770 /* Returns:     Nil                                                         */
5771 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5772 /*              tqe(I)   - pointer to timeout queue entry                   */
5773 /*                                                                          */
5774 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5775 /* We use use ticks to calculate the expiration and mark for when we last   */
5776 /* touched the structure.                                                   */
5777 /* ------------------------------------------------------------------------ */
5778 void
ipf_queueback(u_long ticks,ipftqent_t * tqe)5779 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5780 {
5781 	ipftq_t *ifq;
5782 
5783 	ifq = tqe->tqe_ifq;
5784 	if (ifq == NULL)
5785 		return;
5786 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5787 	tqe->tqe_touched = ticks;
5788 
5789 	MUTEX_ENTER(&ifq->ifq_lock);
5790 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
5791 		/*
5792 		 * Remove from list
5793 		 */
5794 		*tqe->tqe_pnext = tqe->tqe_next;
5795 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5796 
5797 		/*
5798 		 * Make it the last entry.
5799 		 */
5800 		tqe->tqe_next = NULL;
5801 		tqe->tqe_pnext = ifq->ifq_tail;
5802 		*ifq->ifq_tail = tqe;
5803 		ifq->ifq_tail = &tqe->tqe_next;
5804 	}
5805 	MUTEX_EXIT(&ifq->ifq_lock);
5806 }
5807 
5808 
5809 /* ------------------------------------------------------------------------ */
5810 /* Function:    ipf_queueappend                                             */
5811 /* Returns:     Nil                                                         */
5812 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5813 /*              tqe(I)    - pointer to timeout queue entry                  */
5814 /*              ifq(I)    - pointer to timeout queue                        */
5815 /*              parent(I) - owing object pointer                            */
5816 /*                                                                          */
5817 /* Add a new item to this queue and put it on the very end.                 */
5818 /* We use use ticks to calculate the expiration and mark for when we last   */
5819 /* touched the structure.                                                   */
5820 /* ------------------------------------------------------------------------ */
5821 void
ipf_queueappend(u_long ticks,ipftqent_t * tqe,ipftq_t * ifq,void * parent)5822 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5823 {
5824 
5825 	MUTEX_ENTER(&ifq->ifq_lock);
5826 	tqe->tqe_parent = parent;
5827 	tqe->tqe_pnext = ifq->ifq_tail;
5828 	*ifq->ifq_tail = tqe;
5829 	ifq->ifq_tail = &tqe->tqe_next;
5830 	tqe->tqe_next = NULL;
5831 	tqe->tqe_ifq = ifq;
5832 	tqe->tqe_die = ticks + ifq->ifq_ttl;
5833 	tqe->tqe_touched = ticks;
5834 	ifq->ifq_ref++;
5835 	MUTEX_EXIT(&ifq->ifq_lock);
5836 }
5837 
5838 
5839 /* ------------------------------------------------------------------------ */
5840 /* Function:    ipf_movequeue                                               */
5841 /* Returns:     Nil                                                         */
5842 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5843 /*              oifp(I) - old timeout queue entry was on                    */
5844 /*              nifp(I) - new timeout queue to put entry on                 */
5845 /*                                                                          */
5846 /* Move a queue entry from one timeout queue to another timeout queue.      */
5847 /* If it notices that the current entry is already last and does not need   */
5848 /* to move queue, the return.                                               */
5849 /* ------------------------------------------------------------------------ */
5850 void
ipf_movequeue(u_long ticks,ipftqent_t * tqe,ipftq_t * oifq,ipftq_t * nifq)5851 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5852 {
5853 
5854 	/*
5855 	 * If the queue hasn't changed and we last touched this entry at the
5856 	 * same ipf time, then we're not going to achieve anything by either
5857 	 * changing the ttl or moving it on the queue.
5858 	 */
5859 	if (oifq == nifq && tqe->tqe_touched == ticks)
5860 		return;
5861 
5862 	/*
5863 	 * For any of this to be outside the lock, there is a risk that two
5864 	 * packets entering simultaneously, with one changing to a different
5865 	 * queue and one not, could end up with things in a bizarre state.
5866 	 */
5867 	MUTEX_ENTER(&oifq->ifq_lock);
5868 
5869 	tqe->tqe_touched = ticks;
5870 	tqe->tqe_die = ticks + nifq->ifq_ttl;
5871 	/*
5872 	 * Is the operation here going to be a no-op ?
5873 	 */
5874 	if (oifq == nifq) {
5875 		if ((tqe->tqe_next == NULL) ||
5876 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5877 			MUTEX_EXIT(&oifq->ifq_lock);
5878 			return;
5879 		}
5880 	}
5881 
5882 	/*
5883 	 * Remove from the old queue
5884 	 */
5885 	*tqe->tqe_pnext = tqe->tqe_next;
5886 	if (tqe->tqe_next)
5887 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5888 	else
5889 		oifq->ifq_tail = tqe->tqe_pnext;
5890 	tqe->tqe_next = NULL;
5891 
5892 	/*
5893 	 * If we're moving from one queue to another, release the
5894 	 * lock on the old queue and get a lock on the new queue.
5895 	 * For user defined queues, if we're moving off it, call
5896 	 * delete in case it can now be freed.
5897 	 */
5898 	if (oifq != nifq) {
5899 		tqe->tqe_ifq = NULL;
5900 
5901 		(void) ipf_deletetimeoutqueue(oifq);
5902 
5903 		MUTEX_EXIT(&oifq->ifq_lock);
5904 
5905 		MUTEX_ENTER(&nifq->ifq_lock);
5906 
5907 		tqe->tqe_ifq = nifq;
5908 		nifq->ifq_ref++;
5909 	}
5910 
5911 	/*
5912 	 * Add to the bottom of the new queue
5913 	 */
5914 	tqe->tqe_pnext = nifq->ifq_tail;
5915 	*nifq->ifq_tail = tqe;
5916 	nifq->ifq_tail = &tqe->tqe_next;
5917 	MUTEX_EXIT(&nifq->ifq_lock);
5918 }
5919 
5920 
5921 /* ------------------------------------------------------------------------ */
5922 /* Function:    ipf_updateipid                                              */
5923 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
5924 /* Parameters:  fin(I) - pointer to packet information                      */
5925 /*                                                                          */
5926 /* When we are doing NAT, change the IP of every packet to represent a      */
5927 /* single sequence of packets coming from the host, hiding any host         */
5928 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5929 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5930 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5931 /* has no match in the cache, return an error.                              */
5932 /* ------------------------------------------------------------------------ */
5933 static int
ipf_updateipid(fr_info_t * fin)5934 ipf_updateipid(fr_info_t *fin)
5935 {
5936 	u_short id, ido, sums;
5937 	u_32_t sumd, sum;
5938 	ip_t *ip;
5939 
5940 	ip = fin->fin_ip;
5941 	ido = ntohs(ip->ip_id);
5942 	if (fin->fin_off != 0) {
5943 		sum = ipf_frag_ipidknown(fin);
5944 		if (sum == 0xffffffff)
5945 			return (-1);
5946 		sum &= 0xffff;
5947 		id = (u_short)sum;
5948 		ip->ip_id = htons(id);
5949 	} else {
5950 		ip_fillid(ip, V_ip_random_id);
5951 		id = ntohs(ip->ip_id);
5952 		if ((fin->fin_flx & FI_FRAG) != 0)
5953 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
5954 	}
5955 
5956 	if (id == ido)
5957 		return (0);
5958 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5959 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5960 	sum += sumd;
5961 	sum = (sum >> 16) + (sum & 0xffff);
5962 	sum = (sum >> 16) + (sum & 0xffff);
5963 	sums = ~(u_short)sum;
5964 	ip->ip_sum = htons(sums);
5965 	return (0);
5966 }
5967 
5968 
5969 #ifdef	NEED_FRGETIFNAME
5970 /* ------------------------------------------------------------------------ */
5971 /* Function:    ipf_getifname                                               */
5972 /* Returns:     char *    - pointer to interface name                       */
5973 /* Parameters:  ifp(I)    - pointer to network interface                    */
5974 /*              buffer(O) - pointer to where to store interface name        */
5975 /*                                                                          */
5976 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5977 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
5978 /* as a NULL pointer then return a pointer to a static array.               */
5979 /* ------------------------------------------------------------------------ */
5980 char *
ipf_getifname(struct ifnet * ifp,char * buffer)5981 ipf_getifname(struct ifnet *ifp, char *buffer)
5982 {
5983 	static char namebuf[LIFNAMSIZ];
5984 # if SOLARIS || defined(__FreeBSD__)
5985 	int unit, space;
5986 	char temp[20];
5987 	char *s;
5988 # endif
5989 
5990 	if (buffer == NULL)
5991 		buffer = namebuf;
5992 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5993 	buffer[LIFNAMSIZ - 1] = '\0';
5994 # if SOLARIS || defined(__FreeBSD__)
5995 	for (s = buffer; *s; s++)
5996 		;
5997 	unit = ifp->if_unit;
5998 	space = LIFNAMSIZ - (s - buffer);
5999 	if ((space > 0) && (unit >= 0)) {
6000 		(void) snprintf(temp, sizeof(name), "%d", unit);
6001 		(void) strncpy(s, temp, space);
6002 	}
6003 # endif
6004 	return (buffer);
6005 }
6006 #endif
6007 
6008 
6009 /* ------------------------------------------------------------------------ */
6010 /* Function:    ipf_ioctlswitch                                             */
6011 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6012 /* Parameters:  unit(I) - device unit opened                                */
6013 /*              data(I) - pointer to ioctl data                             */
6014 /*              cmd(I)  - ioctl command                                     */
6015 /*              mode(I) - mode value                                        */
6016 /*              uid(I)  - uid making the ioctl call                         */
6017 /*              ctx(I)  - pointer to context data                           */
6018 /*                                                                          */
6019 /* Based on the value of unit, call the appropriate ioctl handler or return */
6020 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6021 /* for the device in order to execute the ioctl.  A special case is made    */
6022 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6023 /* The context data pointer is passed through as this is used as the key    */
6024 /* for locating a matching token for continued access for walking lists,    */
6025 /* etc.                                                                     */
6026 /* ------------------------------------------------------------------------ */
6027 int
ipf_ioctlswitch(ipf_main_softc_t * softc,int unit,void * data,ioctlcmd_t cmd,int mode,int uid,void * ctx)6028 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
6029 	int mode, int uid, void *ctx)
6030 {
6031 	int error = 0;
6032 
6033 	switch (cmd)
6034 	{
6035 	case SIOCIPFINTERROR :
6036 		error = BCOPYOUT(&softc->ipf_interror, data,
6037 				 sizeof(softc->ipf_interror));
6038 		if (error != 0) {
6039 			IPFERROR(40);
6040 			error = EFAULT;
6041 		}
6042 		return (error);
6043 	default :
6044 		break;
6045 	}
6046 
6047 	switch (unit)
6048 	{
6049 	case IPL_LOGIPF :
6050 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6051 		break;
6052 	case IPL_LOGNAT :
6053 		if (softc->ipf_running > 0) {
6054 			error = ipf_nat_ioctl(softc, data, cmd, mode,
6055 					      uid, ctx);
6056 		} else {
6057 			IPFERROR(42);
6058 			error = EIO;
6059 		}
6060 		break;
6061 	case IPL_LOGSTATE :
6062 		if (softc->ipf_running > 0) {
6063 			error = ipf_state_ioctl(softc, data, cmd, mode,
6064 						uid, ctx);
6065 		} else {
6066 			IPFERROR(43);
6067 			error = EIO;
6068 		}
6069 		break;
6070 	case IPL_LOGAUTH :
6071 		if (softc->ipf_running > 0) {
6072 			error = ipf_auth_ioctl(softc, data, cmd, mode,
6073 					       uid, ctx);
6074 		} else {
6075 			IPFERROR(44);
6076 			error = EIO;
6077 		}
6078 		break;
6079 	case IPL_LOGSYNC :
6080 		if (softc->ipf_running > 0) {
6081 			error = ipf_sync_ioctl(softc, data, cmd, mode,
6082 					       uid, ctx);
6083 		} else {
6084 			error = EIO;
6085 			IPFERROR(45);
6086 		}
6087 		break;
6088 	case IPL_LOGSCAN :
6089 #ifdef IPFILTER_SCAN
6090 		if (softc->ipf_running > 0)
6091 			error = ipf_scan_ioctl(softc, data, cmd, mode,
6092 					       uid, ctx);
6093 		else
6094 #endif
6095 		{
6096 			error = EIO;
6097 			IPFERROR(46);
6098 		}
6099 		break;
6100 	case IPL_LOGLOOKUP :
6101 		if (softc->ipf_running > 0) {
6102 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
6103 						 uid, ctx);
6104 		} else {
6105 			error = EIO;
6106 			IPFERROR(47);
6107 		}
6108 		break;
6109 	default :
6110 		IPFERROR(48);
6111 		error = EIO;
6112 		break;
6113 	}
6114 
6115 	return (error);
6116 }
6117 
6118 
6119 /*
6120  * This array defines the expected size of objects coming into the kernel
6121  * for the various recognised object types. The first column is flags (see
6122  * below), 2nd column is current size, 3rd column is the version number of
6123  * when the current size became current.
6124  * Flags:
6125  * 1 = minimum size, not absolute size
6126  */
6127 static const int	ipf_objbytes[IPFOBJ_COUNT][3] = {
6128 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
6129 	{ 1,	sizeof(struct friostat),	5010000 },
6130 	{ 0,	sizeof(struct fr_info),		5010000 },
6131 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
6132 	{ 0,	sizeof(struct ipfrstat),	5010000 },
6133 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
6134 	{ 0,	sizeof(struct natstat),		5010000 },
6135 	{ 0,	sizeof(struct ipstate_save),	5010000 },
6136 	{ 1,	sizeof(struct nat_save),	5010000 },
6137 	{ 0,	sizeof(struct natlookup),	5010000 },
6138 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
6139 	{ 0,	sizeof(struct ips_stat),	5010000 },
6140 	{ 0,	sizeof(struct frauth),		5010000 },
6141 	{ 0,	sizeof(struct ipftune),		4010100 },
6142 	{ 0,	sizeof(struct nat),		5010000 },
6143 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
6144 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
6145 	{ 0,	sizeof(struct ipftable),	4011400 },
6146 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
6147 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
6148 	{ 1,	0,				0	}, /* IPFEXPR */
6149 	{ 0,	0,				0	}, /* PROXYCTL */
6150 	{ 0,	sizeof (struct fripf),		5010000	}
6151 };
6152 
6153 
6154 /* ------------------------------------------------------------------------ */
6155 /* Function:    ipf_inobj                                                   */
6156 /* Returns:     int     - 0 = success, else failure                         */
6157 /* Parameters:  softc(I) - soft context pointerto work with                 */
6158 /*              data(I)  - pointer to ioctl data                            */
6159 /*              objp(O)  - where to store ipfobj structure                  */
6160 /*              ptr(I)   - pointer to data to copy out                      */
6161 /*              type(I)  - type of structure being moved                    */
6162 /*                                                                          */
6163 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6164 /* add things to check for version numbers, sizes, etc, to make it backward */
6165 /* compatible at the ABI for user land.                                     */
6166 /* If objp is not NULL then we assume that the caller wants to see what is  */
6167 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6168 /* the caller what version of ipfilter the ioctl program was written to.    */
6169 /* ------------------------------------------------------------------------ */
6170 int
ipf_inobj(ipf_main_softc_t * softc,void * data,ipfobj_t * objp,void * ptr,int type)6171 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6172 	int type)
6173 {
6174 	ipfobj_t obj;
6175 	int error;
6176 	int size;
6177 
6178 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6179 		IPFERROR(49);
6180 		return (EINVAL);
6181 	}
6182 
6183 	if (objp == NULL)
6184 		objp = &obj;
6185 	error = BCOPYIN(data, objp, sizeof(*objp));
6186 	if (error != 0) {
6187 		IPFERROR(124);
6188 		return (EFAULT);
6189 	}
6190 
6191 	if (objp->ipfo_type != type) {
6192 		IPFERROR(50);
6193 		return (EINVAL);
6194 	}
6195 
6196 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6197 		if ((ipf_objbytes[type][0] & 1) != 0) {
6198 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
6199 				IPFERROR(51);
6200 				return (EINVAL);
6201 			}
6202 			size =  ipf_objbytes[type][1];
6203 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6204 			size =  objp->ipfo_size;
6205 		} else {
6206 			IPFERROR(52);
6207 			return (EINVAL);
6208 		}
6209 		error = COPYIN(objp->ipfo_ptr, ptr, size);
6210 		if (error != 0) {
6211 			IPFERROR(55);
6212 			error = EFAULT;
6213 		}
6214 	} else {
6215 #ifdef  IPFILTER_COMPAT
6216 		error = ipf_in_compat(softc, objp, ptr, 0);
6217 #else
6218 		IPFERROR(54);
6219 		error = EINVAL;
6220 #endif
6221 	}
6222 	return (error);
6223 }
6224 
6225 
6226 /* ------------------------------------------------------------------------ */
6227 /* Function:    ipf_inobjsz                                                 */
6228 /* Returns:     int     - 0 = success, else failure                         */
6229 /* Parameters:  softc(I) - soft context pointerto work with                 */
6230 /*              data(I)  - pointer to ioctl data                            */
6231 /*              ptr(I)   - pointer to store real data in                    */
6232 /*              type(I)  - type of structure being moved                    */
6233 /*              sz(I)    - size of data to copy                             */
6234 /*                                                                          */
6235 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6236 /* but it must not be smaller than the size defined for the type and the    */
6237 /* type must allow for varied sized objects.  The extra requirement here is */
6238 /* that sz must match the size of the object being passed in - this is not  */
6239 /* not possible nor required in ipf_inobj().                                */
6240 /* ------------------------------------------------------------------------ */
6241 int
ipf_inobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6242 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6243 {
6244 	ipfobj_t obj;
6245 	int error;
6246 
6247 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6248 		IPFERROR(56);
6249 		return (EINVAL);
6250 	}
6251 
6252 	error = BCOPYIN(data, &obj, sizeof(obj));
6253 	if (error != 0) {
6254 		IPFERROR(125);
6255 		return (EFAULT);
6256 	}
6257 
6258 	if (obj.ipfo_type != type) {
6259 		IPFERROR(58);
6260 		return (EINVAL);
6261 	}
6262 
6263 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6264 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6265 		    (sz < ipf_objbytes[type][1])) {
6266 			IPFERROR(57);
6267 			return (EINVAL);
6268 		}
6269 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
6270 		if (error != 0) {
6271 			IPFERROR(61);
6272 			error = EFAULT;
6273 		}
6274 	} else {
6275 #ifdef	IPFILTER_COMPAT
6276 		error = ipf_in_compat(softc, &obj, ptr, sz);
6277 #else
6278 		IPFERROR(60);
6279 		error = EINVAL;
6280 #endif
6281 	}
6282 	return (error);
6283 }
6284 
6285 
6286 /* ------------------------------------------------------------------------ */
6287 /* Function:    ipf_outobjsz                                                */
6288 /* Returns:     int     - 0 = success, else failure                         */
6289 /* Parameters:  data(I) - pointer to ioctl data                             */
6290 /*              ptr(I)  - pointer to store real data in                     */
6291 /*              type(I) - type of structure being moved                     */
6292 /*              sz(I)   - size of data to copy                              */
6293 /*                                                                          */
6294 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6295 /* but it must not be smaller than the size defined for the type and the    */
6296 /* type must allow for varied sized objects.  The extra requirement here is */
6297 /* that sz must match the size of the object being passed in - this is not  */
6298 /* not possible nor required in ipf_outobj().                               */
6299 /* ------------------------------------------------------------------------ */
6300 int
ipf_outobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6301 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6302 {
6303 	ipfobj_t obj;
6304 	int error;
6305 
6306 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6307 		IPFERROR(62);
6308 		return (EINVAL);
6309 	}
6310 
6311 	error = BCOPYIN(data, &obj, sizeof(obj));
6312 	if (error != 0) {
6313 		IPFERROR(127);
6314 		return (EFAULT);
6315 	}
6316 
6317 	if (obj.ipfo_type != type) {
6318 		IPFERROR(63);
6319 		return (EINVAL);
6320 	}
6321 
6322 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6323 		if (((ipf_objbytes[type][0] & 1) == 0) ||
6324 		    (sz < ipf_objbytes[type][1])) {
6325 			IPFERROR(146);
6326 			return (EINVAL);
6327 		}
6328 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6329 		if (error != 0) {
6330 			IPFERROR(66);
6331 			error = EFAULT;
6332 		}
6333 	} else {
6334 #ifdef	IPFILTER_COMPAT
6335 		error = ipf_out_compat(softc, &obj, ptr);
6336 #else
6337 		IPFERROR(65);
6338 		error = EINVAL;
6339 #endif
6340 	}
6341 	return (error);
6342 }
6343 
6344 
6345 /* ------------------------------------------------------------------------ */
6346 /* Function:    ipf_outobj                                                  */
6347 /* Returns:     int     - 0 = success, else failure                         */
6348 /* Parameters:  data(I) - pointer to ioctl data                             */
6349 /*              ptr(I)  - pointer to store real data in                     */
6350 /*              type(I) - type of structure being moved                     */
6351 /*                                                                          */
6352 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6353 /* future, we add things to check for version numbers, sizes, etc, to make  */
6354 /* it backward  compatible at the ABI for user land.                        */
6355 /* ------------------------------------------------------------------------ */
6356 int
ipf_outobj(ipf_main_softc_t * softc,void * data,void * ptr,int type)6357 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6358 {
6359 	ipfobj_t obj;
6360 	int error;
6361 
6362 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6363 		IPFERROR(67);
6364 		return (EINVAL);
6365 	}
6366 
6367 	error = BCOPYIN(data, &obj, sizeof(obj));
6368 	if (error != 0) {
6369 		IPFERROR(126);
6370 		return (EFAULT);
6371 	}
6372 
6373 	if (obj.ipfo_type != type) {
6374 		IPFERROR(68);
6375 		return (EINVAL);
6376 	}
6377 
6378 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6379 		if ((ipf_objbytes[type][0] & 1) != 0) {
6380 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
6381 				IPFERROR(69);
6382 				return (EINVAL);
6383 			}
6384 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6385 			IPFERROR(70);
6386 			return (EINVAL);
6387 		}
6388 
6389 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6390 		if (error != 0) {
6391 			IPFERROR(73);
6392 			error = EFAULT;
6393 		}
6394 	} else {
6395 #ifdef	IPFILTER_COMPAT
6396 		error = ipf_out_compat(softc, &obj, ptr);
6397 #else
6398 		IPFERROR(72);
6399 		error = EINVAL;
6400 #endif
6401 	}
6402 	return (error);
6403 }
6404 
6405 
6406 /* ------------------------------------------------------------------------ */
6407 /* Function:    ipf_outobjk                                                 */
6408 /* Returns:     int     - 0 = success, else failure                         */
6409 /* Parameters:  obj(I)  - pointer to data description structure             */
6410 /*              ptr(I)  - pointer to kernel data to copy out                */
6411 /*                                                                          */
6412 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6413 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6414 /* already populated with information and now we just need to use it.       */
6415 /* There is no need for this function to have a "type" parameter as there   */
6416 /* is no point in validating information that comes from the kernel with    */
6417 /* itself.                                                                  */
6418 /* ------------------------------------------------------------------------ */
6419 int
ipf_outobjk(ipf_main_softc_t * softc,ipfobj_t * obj,void * ptr)6420 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6421 {
6422 	int type = obj->ipfo_type;
6423 	int error;
6424 
6425 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6426 		IPFERROR(147);
6427 		return (EINVAL);
6428 	}
6429 
6430 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6431 		if ((ipf_objbytes[type][0] & 1) != 0) {
6432 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
6433 				IPFERROR(148);
6434 				return (EINVAL);
6435 			}
6436 
6437 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6438 			IPFERROR(149);
6439 			return (EINVAL);
6440 		}
6441 
6442 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6443 		if (error != 0) {
6444 			IPFERROR(150);
6445 			error = EFAULT;
6446 		}
6447 	} else {
6448 #ifdef  IPFILTER_COMPAT
6449 		error = ipf_out_compat(softc, obj, ptr);
6450 #else
6451 		IPFERROR(151);
6452 		error = EINVAL;
6453 #endif
6454 	}
6455 	return (error);
6456 }
6457 
6458 
6459 /* ------------------------------------------------------------------------ */
6460 /* Function:    ipf_checkl4sum                                              */
6461 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6462 /* Parameters:  fin(I) - pointer to packet information                      */
6463 /*                                                                          */
6464 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6465 /* not possible, return without indicating a failure or success but in a    */
6466 /* way that is ditinguishable. This function should only be called by the   */
6467 /* ipf_checkv6sum() for each platform.                                      */
6468 /* ------------------------------------------------------------------------ */
6469 inline int
ipf_checkl4sum(fr_info_t * fin)6470 ipf_checkl4sum(fr_info_t *fin)
6471 {
6472 	u_short sum, hdrsum, *csump;
6473 	udphdr_t *udp;
6474 	int dosum;
6475 
6476 	/*
6477 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
6478 	 * isn't already considered "bad", then validate the checksum.  If
6479 	 * this check fails then considered the packet to be "bad".
6480 	 */
6481 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6482 		return (1);
6483 
6484 	DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6485 	if (fin->fin_out == 1) {
6486 		fin->fin_cksum = FI_CK_SUMOK;
6487 		return (0);
6488 	}
6489 
6490 	csump = NULL;
6491 	hdrsum = 0;
6492 	dosum = 0;
6493 	sum = 0;
6494 
6495 	switch (fin->fin_p)
6496 	{
6497 	case IPPROTO_TCP :
6498 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6499 		dosum = 1;
6500 		break;
6501 
6502 	case IPPROTO_UDP :
6503 		udp = fin->fin_dp;
6504 		if (udp->uh_sum != 0) {
6505 			csump = &udp->uh_sum;
6506 			dosum = 1;
6507 		}
6508 		break;
6509 
6510 #ifdef USE_INET6
6511 	case IPPROTO_ICMPV6 :
6512 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6513 		dosum = 1;
6514 		break;
6515 #endif
6516 
6517 	case IPPROTO_ICMP :
6518 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6519 		dosum = 1;
6520 		break;
6521 
6522 	default :
6523 		return (1);
6524 		/*NOTREACHED*/
6525 	}
6526 
6527 	if (csump != NULL) {
6528 		hdrsum = *csump;
6529 		if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6530 			hdrsum = 0x0000;
6531 	}
6532 
6533 	if (dosum) {
6534 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6535 	}
6536 #if !defined(_KERNEL)
6537 	if (sum == hdrsum) {
6538 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6539 	} else {
6540 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6541 	}
6542 #endif
6543 	DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6544 #ifdef USE_INET6
6545 	if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6546 #else
6547 	if (hdrsum == sum) {
6548 #endif
6549 		fin->fin_cksum = FI_CK_SUMOK;
6550 		return (0);
6551 	}
6552 	fin->fin_cksum = FI_CK_BAD;
6553 	return (-1);
6554 }
6555 
6556 
6557 /* ------------------------------------------------------------------------ */
6558 /* Function:    ipf_ifpfillv4addr                                           */
6559 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6560 /* Parameters:  atype(I)   - type of network address update to perform      */
6561 /*              sin(I)     - pointer to source of address information       */
6562 /*              mask(I)    - pointer to source of netmask information       */
6563 /*              inp(I)     - pointer to destination address store           */
6564 /*              inpmask(I) - pointer to destination netmask store           */
6565 /*                                                                          */
6566 /* Given a type of network address update (atype) to perform, copy          */
6567 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6568 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6569 /* which case the operation fails.  For all values of atype other than      */
6570 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6571 /* value.                                                                   */
6572 /* ------------------------------------------------------------------------ */
6573 int
6574 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6575 	struct in_addr *inp, struct in_addr *inpmask)
6576 {
6577 	if (inpmask != NULL && atype != FRI_NETMASKED)
6578 		inpmask->s_addr = 0xffffffff;
6579 
6580 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6581 		if (atype == FRI_NETMASKED) {
6582 			if (inpmask == NULL)
6583 				return (-1);
6584 			inpmask->s_addr = mask->sin_addr.s_addr;
6585 		}
6586 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6587 	} else {
6588 		inp->s_addr = sin->sin_addr.s_addr;
6589 	}
6590 	return (0);
6591 }
6592 
6593 
6594 #ifdef	USE_INET6
6595 /* ------------------------------------------------------------------------ */
6596 /* Function:    ipf_ifpfillv6addr                                           */
6597 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6598 /* Parameters:  atype(I)   - type of network address update to perform      */
6599 /*              sin(I)     - pointer to source of address information       */
6600 /*              mask(I)    - pointer to source of netmask information       */
6601 /*              inp(I)     - pointer to destination address store           */
6602 /*              inpmask(I) - pointer to destination netmask store           */
6603 /*                                                                          */
6604 /* Given a type of network address update (atype) to perform, copy          */
6605 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6606 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6607 /* which case the operation fails.  For all values of atype other than      */
6608 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6609 /* value.                                                                   */
6610 /* ------------------------------------------------------------------------ */
6611 int
6612 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6613 	struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6614 {
6615 	i6addr_t *src, *and;
6616 
6617 	src = (i6addr_t *)&sin->sin6_addr;
6618 	and = (i6addr_t *)&mask->sin6_addr;
6619 
6620 	if (inpmask != NULL && atype != FRI_NETMASKED) {
6621 		inpmask->i6[0] = 0xffffffff;
6622 		inpmask->i6[1] = 0xffffffff;
6623 		inpmask->i6[2] = 0xffffffff;
6624 		inpmask->i6[3] = 0xffffffff;
6625 	}
6626 
6627 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6628 		if (atype == FRI_NETMASKED) {
6629 			if (inpmask == NULL)
6630 				return (-1);
6631 			inpmask->i6[0] = and->i6[0];
6632 			inpmask->i6[1] = and->i6[1];
6633 			inpmask->i6[2] = and->i6[2];
6634 			inpmask->i6[3] = and->i6[3];
6635 		}
6636 
6637 		inp->i6[0] = src->i6[0] & and->i6[0];
6638 		inp->i6[1] = src->i6[1] & and->i6[1];
6639 		inp->i6[2] = src->i6[2] & and->i6[2];
6640 		inp->i6[3] = src->i6[3] & and->i6[3];
6641 	} else {
6642 		inp->i6[0] = src->i6[0];
6643 		inp->i6[1] = src->i6[1];
6644 		inp->i6[2] = src->i6[2];
6645 		inp->i6[3] = src->i6[3];
6646 	}
6647 	return (0);
6648 }
6649 #endif
6650 
6651 
6652 /* ------------------------------------------------------------------------ */
6653 /* Function:    ipf_matchtag                                                */
6654 /* Returns:     0 == mismatch, 1 == match.                                  */
6655 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6656 /*              tag2(I) - pointer to second tag to compare                  */
6657 /*                                                                          */
6658 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6659 /* considered to be a match or not match, respectively.  The tag is 16      */
6660 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6661 /* compare the ints instead, for speed. tag1 is the master of the           */
6662 /* comparison.  This function should only be called with both tag1 and tag2 */
6663 /* as non-NULL pointers.                                                    */
6664 /* ------------------------------------------------------------------------ */
6665 int
6666 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6667 {
6668 	if (tag1 == tag2)
6669 		return (1);
6670 
6671 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6672 		return (1);
6673 
6674 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6675 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6676 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6677 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
6678 		return (1);
6679 	return (0);
6680 }
6681 
6682 
6683 /* ------------------------------------------------------------------------ */
6684 /* Function:    ipf_coalesce                                                */
6685 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6686 /* Parameters:  fin(I) - pointer to packet information                      */
6687 /*                                                                          */
6688 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6689 /* If this call returns a failure then the buffers have also been freed.    */
6690 /* ------------------------------------------------------------------------ */
6691 int
6692 ipf_coalesce(fr_info_t *fin)
6693 {
6694 
6695 	if ((fin->fin_flx & FI_COALESCE) != 0)
6696 		return (1);
6697 
6698 	/*
6699 	 * If the mbuf pointers indicate that there is no mbuf to work with,
6700 	* return but do not indicate success or failure.
6701 	 */
6702 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
6703 		return (0);
6704 
6705 #if defined(_KERNEL)
6706 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6707 		ipf_main_softc_t *softc = fin->fin_main_soft;
6708 
6709 		DT1(frb_coalesce, fr_info_t *, fin);
6710 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6711 # if SOLARIS
6712 		FREE_MB_T(*fin->fin_mp);
6713 # endif
6714 		fin->fin_reason = FRB_COALESCE;
6715 		*fin->fin_mp = NULL;
6716 		fin->fin_m = NULL;
6717 		return (-1);
6718 	}
6719 #else
6720 	fin = fin;	/* LINT */
6721 #endif
6722 	return (1);
6723 }
6724 
6725 
6726 /*
6727  * The following table lists all of the tunable variables that can be
6728  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6729  * in the table below is as follows:
6730  *
6731  * pointer to value, name of value, minimum, maximum, size of the value's
6732  *     container, value attribute flags
6733  *
6734  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6735  * means the value can only be written to when IPFilter is loaded but disabled.
6736  * The obvious implication is if neither of these are set then the value can be
6737  * changed at any time without harm.
6738  */
6739 
6740 
6741 /* ------------------------------------------------------------------------ */
6742 /* Function:    ipf_tune_findbycookie                                       */
6743 /* Returns:     NULL = search failed, else pointer to tune struct           */
6744 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6745 /*              next(O)   - pointer to place to store the cookie for the    */
6746 /*                          "next" tuneable, if it is desired.              */
6747 /*                                                                          */
6748 /* This function is used to walk through all of the existing tunables with  */
6749 /* successive calls.  It searches the known tunables for the one which has  */
6750 /* a matching value for "cookie" - ie its address.  When returning a match, */
6751 /* the next one to be found may be returned inside next.                    */
6752 /* ------------------------------------------------------------------------ */
6753 static ipftuneable_t *
6754 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6755 {
6756 	ipftuneable_t *ta, **tap;
6757 
6758 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
6759 		if (ta == cookie) {
6760 			if (next != NULL) {
6761 				/*
6762 				 * If the next entry in the array has a name
6763 				* present, then return a pointer to it for
6764 				* where to go next, else return a pointer to
6765 				 * the dynaminc list as a key to search there
6766 				 * next.  This facilitates a weak linking of
6767 				 * the two "lists" together.
6768 				 */
6769 				if ((ta + 1)->ipft_name != NULL)
6770 					*next = ta + 1;
6771 				else
6772 					*next = ptop;
6773 			}
6774 			return (ta);
6775 		}
6776 
6777 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6778 		if (tap == cookie) {
6779 			if (next != NULL)
6780 				*next = &ta->ipft_next;
6781 			return (ta);
6782 		}
6783 
6784 	if (next != NULL)
6785 		*next = NULL;
6786 	return (NULL);
6787 }
6788 
6789 
6790 /* ------------------------------------------------------------------------ */
6791 /* Function:    ipf_tune_findbyname                                         */
6792 /* Returns:     NULL = search failed, else pointer to tune struct           */
6793 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6794 /*                                                                          */
6795 /* Search the static array of tuneables and the list of dynamic tuneables   */
6796 /* for an entry with a matching name.  If we can find one, return a pointer */
6797 /* to the matching structure.                                               */
6798 /* ------------------------------------------------------------------------ */
6799 static ipftuneable_t *
6800 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6801 {
6802 	ipftuneable_t *ta;
6803 
6804 	for (ta = top; ta != NULL; ta = ta->ipft_next)
6805 		if (!strcmp(ta->ipft_name, name)) {
6806 			return (ta);
6807 		}
6808 
6809 	return (NULL);
6810 }
6811 
6812 
6813 /* ------------------------------------------------------------------------ */
6814 /* Function:    ipf_tune_add_array                                          */
6815 /* Returns:     int - 0 == success, else failure                            */
6816 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6817 /*                                                                          */
6818 /* Appends tune structures from the array passed in (newtune) to the end of */
6819 /* the current list of "dynamic" tuneable parameters.                       */
6820 /* If any entry to be added is already present (by name) then the operation */
6821 /* is aborted - entries that have been added are removed before returning.  */
6822 /* An entry with no name (NULL) is used as the indication that the end of   */
6823 /* the array has been reached.                                              */
6824 /* ------------------------------------------------------------------------ */
6825 int
6826 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6827 {
6828 	ipftuneable_t *nt, *dt;
6829 	int error = 0;
6830 
6831 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
6832 		error = ipf_tune_add(softc, nt);
6833 		if (error != 0) {
6834 			for (dt = newtune; dt != nt; dt++) {
6835 				(void) ipf_tune_del(softc, dt);
6836 			}
6837 		}
6838 	}
6839 
6840 	return (error);
6841 }
6842 
6843 
6844 /* ------------------------------------------------------------------------ */
6845 /* Function:    ipf_tune_array_link                                         */
6846 /* Returns:     0 == success, -1 == failure                                 */
6847 /* Parameters:  softc(I) - soft context pointerto work with                 */
6848 /*              array(I) - pointer to an array of tuneables                 */
6849 /*                                                                          */
6850 /* Given an array of tunables (array), append them to the current list of   */
6851 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
6852 /* the array for being appended to the list, initialise all of the next     */
6853 /* pointers so we don't need to walk parts of it with ++ and others with    */
6854 /* next. The array is expected to have an entry with a NULL name as the     */
6855 /* terminator. Trying to add an array with no non-NULL names will return as */
6856 /* a failure.                                                               */
6857 /* ------------------------------------------------------------------------ */
6858 int
6859 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6860 {
6861 	ipftuneable_t *t, **p;
6862 
6863 	t = array;
6864 	if (t->ipft_name == NULL)
6865 		return (-1);
6866 
6867 	for (; t[1].ipft_name != NULL; t++)
6868 		t[0].ipft_next = &t[1];
6869 	t->ipft_next = NULL;
6870 
6871 	/*
6872 	 * Since a pointer to the last entry isn't kept, we need to find it
6873 	 * each time we want to add new variables to the list.
6874 	 */
6875 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6876 		if (t->ipft_name == NULL)
6877 			break;
6878 	*p = array;
6879 
6880 	return (0);
6881 }
6882 
6883 
6884 /* ------------------------------------------------------------------------ */
6885 /* Function:    ipf_tune_array_unlink                                       */
6886 /* Returns:     0 == success, -1 == failure                                 */
6887 /* Parameters:  softc(I) - soft context pointerto work with                 */
6888 /*              array(I) - pointer to an array of tuneables                 */
6889 /*                                                                          */
6890 /* ------------------------------------------------------------------------ */
6891 int
6892 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6893 {
6894 	ipftuneable_t *t, **p;
6895 
6896 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6897 		if (t == array)
6898 			break;
6899 	if (t == NULL)
6900 		return (-1);
6901 
6902 	for (; t[1].ipft_name != NULL; t++)
6903 		;
6904 
6905 	*p = t->ipft_next;
6906 
6907 	return (0);
6908 }
6909 
6910 
6911 /* ------------------------------------------------------------------------ */
6912 /* Function:   ipf_tune_array_copy                                          */
6913 /* Returns:    NULL = failure, else pointer to new array                    */
6914 /* Parameters: base(I)     - pointer to structure base                      */
6915 /*             size(I)     - size of the array at template                  */
6916 /*             template(I) - original array to copy                         */
6917 /*                                                                          */
6918 /* Allocate memory for a new set of tuneable values and copy everything     */
6919 /* from template into the new region of memory.  The new region is full of  */
6920 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
6921 /*                                                                          */
6922 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
6923 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
6924 /* location of the tuneable value inside the structure pointed to by base.  */
6925 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
6926 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
6927 /* ipftp_void that points to the stored value.                              */
6928 /* ------------------------------------------------------------------------ */
6929 ipftuneable_t *
6930 ipf_tune_array_copy(void *base, size_t size, ipftuneable_t *template)
6931 {
6932 	ipftuneable_t *copy;
6933 	int i;
6934 
6935 
6936 	KMALLOCS(copy, ipftuneable_t *, size);
6937 	if (copy == NULL) {
6938 		return (NULL);
6939 	}
6940 	bcopy(template, copy, size);
6941 
6942 	for (i = 0; copy[i].ipft_name; i++) {
6943 		copy[i].ipft_una.ipftp_offset += (u_long)base;
6944 		copy[i].ipft_next = copy + i + 1;
6945 	}
6946 
6947 	return (copy);
6948 }
6949 
6950 
6951 /* ------------------------------------------------------------------------ */
6952 /* Function:    ipf_tune_add                                                */
6953 /* Returns:     int - 0 == success, else failure                            */
6954 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
6955 /*                                                                          */
6956 /* Appends tune structures from the array passed in (newtune) to the end of */
6957 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
6958 /* owner of the object is not expected to ever change "ipft_next".          */
6959 /* ------------------------------------------------------------------------ */
6960 int
6961 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6962 {
6963 	ipftuneable_t *ta, **tap;
6964 
6965 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
6966 	if (ta != NULL) {
6967 		IPFERROR(74);
6968 		return (EEXIST);
6969 	}
6970 
6971 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
6972 		;
6973 
6974 	newtune->ipft_next = NULL;
6975 	*tap = newtune;
6976 	return (0);
6977 }
6978 
6979 
6980 /* ------------------------------------------------------------------------ */
6981 /* Function:    ipf_tune_del                                                */
6982 /* Returns:     int - 0 == success, else failure                            */
6983 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
6984 /*                        current dynamic tuneables                         */
6985 /*                                                                          */
6986 /* Search for the tune structure, by pointer, in the list of those that are */
6987 /* dynamically added at run time.  If found, adjust the list so that this   */
6988 /* structure is no longer part of it.                                       */
6989 /* ------------------------------------------------------------------------ */
6990 int
6991 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6992 {
6993 	ipftuneable_t *ta, **tap;
6994 	int error = 0;
6995 
6996 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
6997 	     tap = &ta->ipft_next) {
6998 		if (ta == oldtune) {
6999 			*tap = oldtune->ipft_next;
7000 			oldtune->ipft_next = NULL;
7001 			break;
7002 		}
7003 	}
7004 
7005 	if (ta == NULL) {
7006 		error = ESRCH;
7007 		IPFERROR(75);
7008 	}
7009 	return (error);
7010 }
7011 
7012 
7013 /* ------------------------------------------------------------------------ */
7014 /* Function:    ipf_tune_del_array                                          */
7015 /* Returns:     int - 0 == success, else failure                            */
7016 /* Parameters:  oldtune - pointer to tuneables array                        */
7017 /*                                                                          */
7018 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7019 /* tunables.  If one entry should fail to be found, an error will be        */
7020 /* returned and no further ones removed.                                    */
7021 /* An entry with a NULL name is used as the indicator of the last entry in  */
7022 /* the array.                                                               */
7023 /* ------------------------------------------------------------------------ */
7024 int
7025 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7026 {
7027 	ipftuneable_t *ot;
7028 	int error = 0;
7029 
7030 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7031 		error = ipf_tune_del(softc, ot);
7032 		if (error != 0)
7033 			break;
7034 	}
7035 
7036 	return (error);
7037 
7038 }
7039 
7040 
7041 /* ------------------------------------------------------------------------ */
7042 /* Function:    ipf_tune                                                    */
7043 /* Returns:     int - 0 == success, else failure                            */
7044 /* Parameters:  cmd(I)  - ioctl command number                              */
7045 /*              data(I) - pointer to ioctl data structure                   */
7046 /*                                                                          */
7047 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7048 /* three ioctls provide the means to access and control global variables    */
7049 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7050 /* changed without rebooting, reloading or recompiling.  The initialisation */
7051 /* and 'destruction' routines of the various components of ipfilter are all */
7052 /* each responsible for handling their own values being too big.            */
7053 /* ------------------------------------------------------------------------ */
7054 int
7055 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
7056 {
7057 	ipftuneable_t *ta;
7058 	ipftune_t tu;
7059 	void *cookie;
7060 	int error;
7061 
7062 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7063 	if (error != 0)
7064 		return (error);
7065 
7066 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7067 	cookie = tu.ipft_cookie;
7068 	ta = NULL;
7069 
7070 	switch (cmd)
7071 	{
7072 	case SIOCIPFGETNEXT :
7073 		/*
7074 		 * If cookie is non-NULL, assume it to be a pointer to the last
7075 		* entry we looked at, so find it (if possible) and return a
7076 		 * pointer to the next one after it.  The last entry in the
7077 		 * the table is a NULL entry, so when we get to it, set cookie
7078 		* to NULL and return that, indicating end of list, erstwhile
7079 		 * if we come in with cookie set to NULL, we are starting anew
7080 		 * at the front of the list.
7081 		 */
7082 		if (cookie != NULL) {
7083 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7084 						   cookie, &tu.ipft_cookie);
7085 		} else {
7086 			ta = softc->ipf_tuners;
7087 			tu.ipft_cookie = ta + 1;
7088 		}
7089 		if (ta != NULL) {
7090 			/*
7091 			 * Entry found, but does the data pointed to by that
7092 			 * row fit in what we can return?
7093 			 */
7094 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7095 				IPFERROR(76);
7096 				return (EINVAL);
7097 			}
7098 
7099 			tu.ipft_vlong = 0;
7100 			if (ta->ipft_sz == sizeof(u_long))
7101 				tu.ipft_vlong = *ta->ipft_plong;
7102 			else if (ta->ipft_sz == sizeof(u_int))
7103 				tu.ipft_vint = *ta->ipft_pint;
7104 			else if (ta->ipft_sz == sizeof(u_short))
7105 				tu.ipft_vshort = *ta->ipft_pshort;
7106 			else if (ta->ipft_sz == sizeof(u_char))
7107 				tu.ipft_vchar = *ta->ipft_pchar;
7108 
7109 			tu.ipft_sz = ta->ipft_sz;
7110 			tu.ipft_min = ta->ipft_min;
7111 			tu.ipft_max = ta->ipft_max;
7112 			tu.ipft_flags = ta->ipft_flags;
7113 			bcopy(ta->ipft_name, tu.ipft_name,
7114 			      MIN(sizeof(tu.ipft_name),
7115 				  strlen(ta->ipft_name) + 1));
7116 		}
7117 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7118 		break;
7119 
7120 	case SIOCIPFGET :
7121 	case SIOCIPFSET :
7122 		/*
7123 		 * Search by name or by cookie value for a particular entry
7124 		 * in the tuning parameter table.
7125 		 */
7126 		IPFERROR(77);
7127 		error = ESRCH;
7128 		if (cookie != NULL) {
7129 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7130 						   cookie, NULL);
7131 			if (ta != NULL)
7132 				error = 0;
7133 		} else if (tu.ipft_name[0] != '\0') {
7134 			ta = ipf_tune_findbyname(softc->ipf_tuners,
7135 						 tu.ipft_name);
7136 			if (ta != NULL)
7137 				error = 0;
7138 		}
7139 		if (error != 0)
7140 			break;
7141 
7142 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7143 			/*
7144 			 * Fetch the tuning parameters for a particular value
7145 			 */
7146 			tu.ipft_vlong = 0;
7147 			if (ta->ipft_sz == sizeof(u_long))
7148 				tu.ipft_vlong = *ta->ipft_plong;
7149 			else if (ta->ipft_sz == sizeof(u_int))
7150 				tu.ipft_vint = *ta->ipft_pint;
7151 			else if (ta->ipft_sz == sizeof(u_short))
7152 				tu.ipft_vshort = *ta->ipft_pshort;
7153 			else if (ta->ipft_sz == sizeof(u_char))
7154 				tu.ipft_vchar = *ta->ipft_pchar;
7155 			tu.ipft_cookie = ta;
7156 			tu.ipft_sz = ta->ipft_sz;
7157 			tu.ipft_min = ta->ipft_min;
7158 			tu.ipft_max = ta->ipft_max;
7159 			tu.ipft_flags = ta->ipft_flags;
7160 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7161 
7162 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7163 			/*
7164 			 * Set an internal parameter.  The hard part here is
7165 			 * getting the new value safely and correctly out of
7166 			 * the kernel (given we only know its size, not type.)
7167 			 */
7168 			u_long in;
7169 
7170 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7171 			    (softc->ipf_running > 0)) {
7172 				IPFERROR(78);
7173 				error = EBUSY;
7174 				break;
7175 			}
7176 
7177 			in = tu.ipft_vlong;
7178 			if (in < ta->ipft_min || in > ta->ipft_max) {
7179 				IPFERROR(79);
7180 				error = EINVAL;
7181 				break;
7182 			}
7183 
7184 			if (ta->ipft_func != NULL) {
7185 				SPL_INT(s);
7186 
7187 				SPL_NET(s);
7188 				error = (*ta->ipft_func)(softc, ta,
7189 							 &tu.ipft_un);
7190 				SPL_X(s);
7191 
7192 			} else if (ta->ipft_sz == sizeof(u_long)) {
7193 				tu.ipft_vlong = *ta->ipft_plong;
7194 				*ta->ipft_plong = in;
7195 
7196 			} else if (ta->ipft_sz == sizeof(u_int)) {
7197 				tu.ipft_vint = *ta->ipft_pint;
7198 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
7199 
7200 			} else if (ta->ipft_sz == sizeof(u_short)) {
7201 				tu.ipft_vshort = *ta->ipft_pshort;
7202 				*ta->ipft_pshort = (u_short)(in & 0xffff);
7203 
7204 			} else if (ta->ipft_sz == sizeof(u_char)) {
7205 				tu.ipft_vchar = *ta->ipft_pchar;
7206 				*ta->ipft_pchar = (u_char)(in & 0xff);
7207 			}
7208 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7209 		}
7210 		break;
7211 
7212 	default :
7213 		IPFERROR(80);
7214 		error = EINVAL;
7215 		break;
7216 	}
7217 
7218 	return (error);
7219 }
7220 
7221 
7222 /* ------------------------------------------------------------------------ */
7223 /* Function:    ipf_zerostats                                               */
7224 /* Returns:     int - 0 = success, else failure                             */
7225 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7226 /*                                                                          */
7227 /* Copies the current statistics out to userspace and then zero's the       */
7228 /* current ones in the kernel. The lock is only held across the bzero() as  */
7229 /* the copyout may result in paging (ie network activity.)                  */
7230 /* ------------------------------------------------------------------------ */
7231 int
7232 ipf_zerostats(ipf_main_softc_t *softc, caddr_t data)
7233 {
7234 	friostat_t fio;
7235 	ipfobj_t obj;
7236 	int error;
7237 
7238 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7239 	if (error != 0)
7240 		return (error);
7241 	ipf_getstat(softc, &fio, obj.ipfo_rev);
7242 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7243 	if (error != 0)
7244 		return (error);
7245 
7246 	WRITE_ENTER(&softc->ipf_mutex);
7247 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7248 	RWLOCK_EXIT(&softc->ipf_mutex);
7249 
7250 	return (0);
7251 }
7252 
7253 
7254 /* ------------------------------------------------------------------------ */
7255 /* Function:    ipf_resolvedest                                             */
7256 /* Returns:     Nil                                                         */
7257 /* Parameters:  softc(I) - pointer to soft context main structure           */
7258 /*              base(I)  - where strings are stored                         */
7259 /*              fdp(IO)  - pointer to destination information to resolve    */
7260 /*              v(I)     - IP protocol version to match                     */
7261 /*                                                                          */
7262 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7263 /* if a matching name can be found for the particular IP protocol version   */
7264 /* then store the interface pointer in the frdest struct.  If no match is   */
7265 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7266 /* indicate there is no information at all in the structure.                */
7267 /* ------------------------------------------------------------------------ */
7268 int
7269 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7270 {
7271 	int errval = 0;
7272 	void *ifp;
7273 
7274 	ifp = NULL;
7275 
7276 	if (fdp->fd_name != -1) {
7277 		if (fdp->fd_type == FRD_DSTLIST) {
7278 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7279 						  IPLT_DSTLIST,
7280 						  base + fdp->fd_name,
7281 						  NULL);
7282 			if (ifp == NULL) {
7283 				IPFERROR(144);
7284 				errval = ESRCH;
7285 			}
7286 		} else {
7287 			ifp = GETIFP(base + fdp->fd_name, v);
7288 			if (ifp == NULL)
7289 				ifp = (void *)-1;
7290 		}
7291 	}
7292 	fdp->fd_ptr = ifp;
7293 
7294 	return (errval);
7295 }
7296 
7297 
7298 /* ------------------------------------------------------------------------ */
7299 /* Function:    ipf_resolvenic                                              */
7300 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7301 /*                      pointer to interface structure for NIC              */
7302 /* Parameters:  softc(I)- pointer to soft context main structure            */
7303 /*              name(I) - complete interface name                           */
7304 /*              v(I)    - IP protocol version                               */
7305 /*                                                                          */
7306 /* Look for a network interface structure that firstly has a matching name  */
7307 /* to that passed in and that is also being used for that IP protocol       */
7308 /* version (necessary on some platforms where there are separate listings   */
7309 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7310 /* ------------------------------------------------------------------------ */
7311 void *
7312 ipf_resolvenic(ipf_main_softc_t *softc __unused, char *name, int v)
7313 {
7314 	void *nic;
7315 
7316 	if (name[0] == '\0')
7317 		return (NULL);
7318 
7319 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7320 		return (NULL);
7321 	}
7322 
7323 	nic = GETIFP(name, v);
7324 	if (nic == NULL)
7325 		nic = (void *)-1;
7326 	return (nic);
7327 }
7328 
7329 
7330 /* ------------------------------------------------------------------------ */
7331 /* Function:    ipf_token_expire                                            */
7332 /* Returns:     None.                                                       */
7333 /* Parameters:  softc(I) - pointer to soft context main structure           */
7334 /*                                                                          */
7335 /* This function is run every ipf tick to see if there are any tokens that  */
7336 /* have been held for too long and need to be freed up.                     */
7337 /* ------------------------------------------------------------------------ */
7338 void
7339 ipf_token_expire(ipf_main_softc_t *softc)
7340 {
7341 	ipftoken_t *it;
7342 
7343 	WRITE_ENTER(&softc->ipf_tokens);
7344 	while ((it = softc->ipf_token_head) != NULL) {
7345 		if (it->ipt_die > softc->ipf_ticks)
7346 			break;
7347 
7348 		ipf_token_deref(softc, it);
7349 	}
7350 	RWLOCK_EXIT(&softc->ipf_tokens);
7351 }
7352 
7353 
7354 /* ------------------------------------------------------------------------ */
7355 /* Function:    ipf_token_flush                                             */
7356 /* Returns:     None.                                                       */
7357 /* Parameters:  softc(I) - pointer to soft context main structure           */
7358 /*                                                                          */
7359 /* Loop through all of the existing tokens and call deref to see if they    */
7360 /* can be freed. Normally a function like this might just loop on           */
7361 /* ipf_token_head but there is a chance that a token might have a ref count */
7362 /* of greater than one and in that case the reference would drop twice      */
7363 /* by code that is only entitled to drop it once.                           */
7364 /* ------------------------------------------------------------------------ */
7365 static void
7366 ipf_token_flush(ipf_main_softc_t *softc)
7367 {
7368 	ipftoken_t *it, *next;
7369 
7370 	WRITE_ENTER(&softc->ipf_tokens);
7371 	for (it = softc->ipf_token_head; it != NULL; it = next) {
7372 		next = it->ipt_next;
7373 		(void) ipf_token_deref(softc, it);
7374 	}
7375 	RWLOCK_EXIT(&softc->ipf_tokens);
7376 }
7377 
7378 
7379 /* ------------------------------------------------------------------------ */
7380 /* Function:    ipf_token_del                                               */
7381 /* Returns:     int     - 0 = success, else error                           */
7382 /* Parameters:  softc(I)- pointer to soft context main structure            */
7383 /*              type(I) - the token type to match                           */
7384 /*              uid(I)  - uid owning the token                              */
7385 /*              ptr(I)  - context pointer for the token                     */
7386 /*                                                                          */
7387 /* This function looks for a token in the current list that matches up      */
7388 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7389 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7390 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7391 /* enables debugging to distinguish between the two paths that ultimately   */
7392 /* lead to a token to be deleted.                                           */
7393 /* ------------------------------------------------------------------------ */
7394 int
7395 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7396 {
7397 	ipftoken_t *it;
7398 	int error;
7399 
7400 	IPFERROR(82);
7401 	error = ESRCH;
7402 
7403 	WRITE_ENTER(&softc->ipf_tokens);
7404 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7405 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
7406 		    uid == it->ipt_uid) {
7407 			it->ipt_complete = 2;
7408 			ipf_token_deref(softc, it);
7409 			error = 0;
7410 			break;
7411 		}
7412 	}
7413 	RWLOCK_EXIT(&softc->ipf_tokens);
7414 
7415 	return (error);
7416 }
7417 
7418 
7419 /* ------------------------------------------------------------------------ */
7420 /* Function:    ipf_token_mark_complete                                     */
7421 /* Returns:     None.                                                       */
7422 /* Parameters:  token(I) - pointer to token structure                       */
7423 /*                                                                          */
7424 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7425 /* ------------------------------------------------------------------------ */
7426 void
7427 ipf_token_mark_complete(ipftoken_t *token)
7428 {
7429 	if (token->ipt_complete == 0)
7430 		token->ipt_complete = 1;
7431 }
7432 
7433 
7434 /* ------------------------------------------------------------------------ */
7435 /* Function:    ipf_token_find                                               */
7436 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7437 /* Parameters:  softc(I)- pointer to soft context main structure            */
7438 /*              type(I) - the token type to match                           */
7439 /*              uid(I)  - uid owning the token                              */
7440 /*              ptr(I)  - context pointer for the token                     */
7441 /*                                                                          */
7442 /* This function looks for a live token in the list of current tokens that  */
7443 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7444 /* allocated.  If one is found then it is moved to the top of the list of   */
7445 /* currently active tokens.                                                 */
7446 /* ------------------------------------------------------------------------ */
7447 ipftoken_t *
7448 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7449 {
7450 	ipftoken_t *it, *new;
7451 
7452 	KMALLOC(new, ipftoken_t *);
7453 	if (new != NULL)
7454 		bzero((char *)new, sizeof(*new));
7455 
7456 	WRITE_ENTER(&softc->ipf_tokens);
7457 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7458 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7459 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
7460 			break;
7461 	}
7462 
7463 	if (it == NULL) {
7464 		it = new;
7465 		new = NULL;
7466 		if (it == NULL) {
7467 			RWLOCK_EXIT(&softc->ipf_tokens);
7468 			return (NULL);
7469 		}
7470 		it->ipt_ctx = ptr;
7471 		it->ipt_uid = uid;
7472 		it->ipt_type = type;
7473 		it->ipt_ref = 1;
7474 	} else {
7475 		if (new != NULL) {
7476 			KFREE(new);
7477 			new = NULL;
7478 		}
7479 
7480 		if (it->ipt_complete > 0)
7481 			it = NULL;
7482 		else
7483 			ipf_token_unlink(softc, it);
7484 	}
7485 
7486 	if (it != NULL) {
7487 		it->ipt_pnext = softc->ipf_token_tail;
7488 		*softc->ipf_token_tail = it;
7489 		softc->ipf_token_tail = &it->ipt_next;
7490 		it->ipt_next = NULL;
7491 		it->ipt_ref++;
7492 
7493 		it->ipt_die = softc->ipf_ticks + 20;
7494 	}
7495 
7496 	RWLOCK_EXIT(&softc->ipf_tokens);
7497 
7498 	return (it);
7499 }
7500 
7501 
7502 /* ------------------------------------------------------------------------ */
7503 /* Function:    ipf_token_unlink                                            */
7504 /* Returns:     None.                                                       */
7505 /* Parameters:  softc(I) - pointer to soft context main structure           */
7506 /*              token(I) - pointer to token structure                       */
7507 /* Write Locks: ipf_tokens                                                  */
7508 /*                                                                          */
7509 /* This function unlinks a token structure from the linked list of tokens   */
7510 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7511 /* but the tail does due to the linked list implementation.                 */
7512 /* ------------------------------------------------------------------------ */
7513 static void
7514 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7515 {
7516 
7517 	if (softc->ipf_token_tail == &token->ipt_next)
7518 		softc->ipf_token_tail = token->ipt_pnext;
7519 
7520 	*token->ipt_pnext = token->ipt_next;
7521 	if (token->ipt_next != NULL)
7522 		token->ipt_next->ipt_pnext = token->ipt_pnext;
7523 	token->ipt_next = NULL;
7524 	token->ipt_pnext = NULL;
7525 }
7526 
7527 
7528 /* ------------------------------------------------------------------------ */
7529 /* Function:    ipf_token_deref                                             */
7530 /* Returns:     int      - 0 == token freed, else reference count           */
7531 /* Parameters:  softc(I) - pointer to soft context main structure           */
7532 /*              token(I) - pointer to token structure                       */
7533 /* Write Locks: ipf_tokens                                                  */
7534 /*                                                                          */
7535 /* Drop the reference count on the token structure and if it drops to zero, */
7536 /* call the dereference function for the token type because it is then      */
7537 /* possible to free the token data structure.                               */
7538 /* ------------------------------------------------------------------------ */
7539 int
7540 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7541 {
7542 	void *data, **datap;
7543 
7544 	ASSERT(token->ipt_ref > 0);
7545 	token->ipt_ref--;
7546 	if (token->ipt_ref > 0)
7547 		return (token->ipt_ref);
7548 
7549 	data = token->ipt_data;
7550 	datap = &data;
7551 
7552 	if ((data != NULL) && (data != (void *)-1)) {
7553 		switch (token->ipt_type)
7554 		{
7555 		case IPFGENITER_IPF :
7556 			(void) ipf_derefrule(softc, (frentry_t **)datap);
7557 			break;
7558 		case IPFGENITER_IPNAT :
7559 			WRITE_ENTER(&softc->ipf_nat);
7560 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7561 			RWLOCK_EXIT(&softc->ipf_nat);
7562 			break;
7563 		case IPFGENITER_NAT :
7564 			ipf_nat_deref(softc, (nat_t **)datap);
7565 			break;
7566 		case IPFGENITER_STATE :
7567 			ipf_state_deref(softc, (ipstate_t **)datap);
7568 			break;
7569 		case IPFGENITER_FRAG :
7570 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7571 			break;
7572 		case IPFGENITER_NATFRAG :
7573 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7574 			break;
7575 		case IPFGENITER_HOSTMAP :
7576 			WRITE_ENTER(&softc->ipf_nat);
7577 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7578 			RWLOCK_EXIT(&softc->ipf_nat);
7579 			break;
7580 		default :
7581 			ipf_lookup_iterderef(softc, token->ipt_type, data);
7582 			break;
7583 		}
7584 	}
7585 
7586 	ipf_token_unlink(softc, token);
7587 	KFREE(token);
7588 	return (0);
7589 }
7590 
7591 
7592 /* ------------------------------------------------------------------------ */
7593 /* Function:    ipf_nextrule                                                */
7594 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7595 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7596 /*              fr(I)       - pointer to filter rule                        */
7597 /*              out(I)      - 1 == out rules, 0 == input rules              */
7598 /*                                                                          */
7599 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7600 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7601 /* last rule in the list. When walking rule lists, it is either input or    */
7602 /* output rules that are returned, never both.                              */
7603 /* ------------------------------------------------------------------------ */
7604 static frentry_t *
7605 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit, frentry_t *fr,
7606 	int out)
7607 {
7608 	frentry_t *next;
7609 	frgroup_t *fg;
7610 
7611 	if (fr != NULL && fr->fr_group != -1) {
7612 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7613 				   unit, active, NULL);
7614 		if (fg != NULL)
7615 			fg = fg->fg_next;
7616 	} else {
7617 		fg = softc->ipf_groups[unit][active];
7618 	}
7619 
7620 	while (fg != NULL) {
7621 		next = fg->fg_start;
7622 		while (next != NULL) {
7623 			if (out) {
7624 				if (next->fr_flags & FR_OUTQUE)
7625 					return (next);
7626 			} else if (next->fr_flags & FR_INQUE) {
7627 				return (next);
7628 			}
7629 			next = next->fr_next;
7630 		}
7631 		if (next == NULL)
7632 			fg = fg->fg_next;
7633 	}
7634 
7635 	return (NULL);
7636 }
7637 
7638 /* ------------------------------------------------------------------------ */
7639 /* Function:    ipf_getnextrule                                             */
7640 /* Returns:     int - 0 = success, else error                               */
7641 /* Parameters:  softc(I)- pointer to soft context main structure            */
7642 /*              t(I)   - pointer to destination information to resolve      */
7643 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7644 /*                                                                          */
7645 /* This function's first job is to bring in the ipfruleiter_t structure via */
7646 /* the ipfobj_t structure to determine what should be the next rule to      */
7647 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7648 /* find the 'next rule'.  This may include searching rule group lists or    */
7649 /* just be as simple as looking at the 'next' field in the rule structure.  */
7650 /* When we have found the rule to return, increase its reference count and  */
7651 /* if we used an existing rule to get here, decrease its reference count.   */
7652 /* ------------------------------------------------------------------------ */
7653 int
7654 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7655 {
7656 	frentry_t *fr, *next, zero;
7657 	ipfruleiter_t it;
7658 	int error, out;
7659 	frgroup_t *fg;
7660 	ipfobj_t obj;
7661 	int predict;
7662 	char *dst;
7663 	int unit;
7664 
7665 	if (t == NULL || ptr == NULL) {
7666 		IPFERROR(84);
7667 		return (EFAULT);
7668 	}
7669 
7670 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7671 	if (error != 0)
7672 		return (error);
7673 
7674 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7675 		IPFERROR(85);
7676 		return (EINVAL);
7677 	}
7678 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
7679 		IPFERROR(86);
7680 		return (EINVAL);
7681 	}
7682 	if (it.iri_nrules == 0) {
7683 		IPFERROR(87);
7684 		return (ENOSPC);
7685 	}
7686 	if (it.iri_rule == NULL) {
7687 		IPFERROR(88);
7688 		return (EFAULT);
7689 	}
7690 
7691 	fg = NULL;
7692 	fr = t->ipt_data;
7693 	if ((it.iri_inout & F_OUT) != 0)
7694 		out = 1;
7695 	else
7696 		out = 0;
7697 	if ((it.iri_inout & F_ACIN) != 0)
7698 		unit = IPL_LOGCOUNT;
7699 	else
7700 		unit = IPL_LOGIPF;
7701 
7702 	READ_ENTER(&softc->ipf_mutex);
7703 	if (fr == NULL) {
7704 		if (*it.iri_group == '\0') {
7705 			if (unit == IPL_LOGCOUNT) {
7706 				next = softc->ipf_acct[out][it.iri_active];
7707 			} else {
7708 				next = softc->ipf_rules[out][it.iri_active];
7709 			}
7710 			if (next == NULL)
7711 				next = ipf_nextrule(softc, it.iri_active,
7712 						    unit, NULL, out);
7713 		} else {
7714 			fg = ipf_findgroup(softc, it.iri_group, unit,
7715 					   it.iri_active, NULL);
7716 			if (fg != NULL)
7717 				next = fg->fg_start;
7718 			else
7719 				next = NULL;
7720 		}
7721 	} else {
7722 		next = fr->fr_next;
7723 		if (next == NULL)
7724 			next = ipf_nextrule(softc, it.iri_active, unit,
7725 					    fr, out);
7726 	}
7727 
7728 	if (next != NULL && next->fr_next != NULL)
7729 		predict = 1;
7730 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7731 		predict = 1;
7732 	else
7733 		predict = 0;
7734 
7735 	if (fr != NULL)
7736 		(void) ipf_derefrule(softc, &fr);
7737 
7738 	obj.ipfo_type = IPFOBJ_FRENTRY;
7739 	dst = (char *)it.iri_rule;
7740 
7741 	if (next != NULL) {
7742 		obj.ipfo_size = next->fr_size;
7743 		MUTEX_ENTER(&next->fr_lock);
7744 		next->fr_ref++;
7745 		MUTEX_EXIT(&next->fr_lock);
7746 		t->ipt_data = next;
7747 	} else {
7748 		obj.ipfo_size = sizeof(frentry_t);
7749 		bzero(&zero, sizeof(zero));
7750 		next = &zero;
7751 		t->ipt_data = NULL;
7752 	}
7753 	it.iri_rule = predict ? next : NULL;
7754 	if (predict == 0)
7755 		ipf_token_mark_complete(t);
7756 
7757 	RWLOCK_EXIT(&softc->ipf_mutex);
7758 
7759 	obj.ipfo_ptr = dst;
7760 	error = ipf_outobjk(softc, &obj, next);
7761 	if (error == 0 && t->ipt_data != NULL) {
7762 		dst += obj.ipfo_size;
7763 		if (next->fr_data != NULL) {
7764 			ipfobj_t dobj;
7765 
7766 			if (next->fr_type == FR_T_IPFEXPR)
7767 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
7768 			else
7769 				dobj.ipfo_type = IPFOBJ_FRIPF;
7770 			dobj.ipfo_size = next->fr_dsize;
7771 			dobj.ipfo_rev = obj.ipfo_rev;
7772 			dobj.ipfo_ptr = dst;
7773 			error = ipf_outobjk(softc, &dobj, next->fr_data);
7774 		}
7775 	}
7776 
7777 	if ((fr != NULL) && (next == &zero))
7778 		(void) ipf_derefrule(softc, &fr);
7779 
7780 	return (error);
7781 }
7782 
7783 
7784 /* ------------------------------------------------------------------------ */
7785 /* Function:    ipf_frruleiter                                              */
7786 /* Returns:     int - 0 = success, else error                               */
7787 /* Parameters:  softc(I)- pointer to soft context main structure            */
7788 /*              data(I) - the token type to match                           */
7789 /*              uid(I)  - uid owning the token                              */
7790 /*              ptr(I)  - context pointer for the token                     */
7791 /*                                                                          */
7792 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
7793 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7794 /* the process doing the ioctl and use that to ask for the next rule.       */
7795 /* ------------------------------------------------------------------------ */
7796 static int
7797 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7798 {
7799 	ipftoken_t *token;
7800 	ipfruleiter_t it;
7801 	ipfobj_t obj;
7802 	int error;
7803 
7804 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7805 	if (token != NULL) {
7806 		error = ipf_getnextrule(softc, token, data);
7807 		WRITE_ENTER(&softc->ipf_tokens);
7808 		ipf_token_deref(softc, token);
7809 		RWLOCK_EXIT(&softc->ipf_tokens);
7810 	} else {
7811 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7812 		if (error != 0)
7813 			return (error);
7814 		it.iri_rule = NULL;
7815 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7816 	}
7817 
7818 	return (error);
7819 }
7820 
7821 
7822 /* ------------------------------------------------------------------------ */
7823 /* Function:    ipf_geniter                                                 */
7824 /* Returns:     int - 0 = success, else error                               */
7825 /* Parameters:  softc(I) - pointer to soft context main structure           */
7826 /*              token(I) - pointer to ipftoken_t structure                  */
7827 /*              itp(I)   - pointer to iterator data                         */
7828 /*                                                                          */
7829 /* Decide which iterator function to call using information passed through  */
7830 /* the ipfgeniter_t structure at itp.                                       */
7831 /* ------------------------------------------------------------------------ */
7832 static int
7833 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7834 {
7835 	int error;
7836 
7837 	switch (itp->igi_type)
7838 	{
7839 	case IPFGENITER_FRAG :
7840 		error = ipf_frag_pkt_next(softc, token, itp);
7841 		break;
7842 	default :
7843 		IPFERROR(92);
7844 		error = EINVAL;
7845 		break;
7846 	}
7847 
7848 	return (error);
7849 }
7850 
7851 
7852 /* ------------------------------------------------------------------------ */
7853 /* Function:    ipf_genericiter                                             */
7854 /* Returns:     int - 0 = success, else error                               */
7855 /* Parameters:  softc(I)- pointer to soft context main structure            */
7856 /*              data(I) - the token type to match                           */
7857 /*              uid(I)  - uid owning the token                              */
7858 /*              ptr(I)  - context pointer for the token                     */
7859 /*                                                                          */
7860 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
7861 /* ------------------------------------------------------------------------ */
7862 int
7863 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7864 {
7865 	ipftoken_t *token;
7866 	ipfgeniter_t iter;
7867 	int error;
7868 
7869 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7870 	if (error != 0)
7871 		return (error);
7872 
7873 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7874 	if (token != NULL) {
7875 		token->ipt_subtype = iter.igi_type;
7876 		error = ipf_geniter(softc, token, &iter);
7877 		WRITE_ENTER(&softc->ipf_tokens);
7878 		ipf_token_deref(softc, token);
7879 		RWLOCK_EXIT(&softc->ipf_tokens);
7880 	} else {
7881 		IPFERROR(93);
7882 		error = 0;
7883 	}
7884 
7885 	return (error);
7886 }
7887 
7888 
7889 /* ------------------------------------------------------------------------ */
7890 /* Function:    ipf_ipf_ioctl                                               */
7891 /* Returns:     int - 0 = success, else error                               */
7892 /* Parameters:  softc(I)- pointer to soft context main structure            */
7893 /*              data(I) - the token type to match                           */
7894 /*              cmd(I)  - the ioctl command number                          */
7895 /*              mode(I) - mode flags for the ioctl                          */
7896 /*              uid(I)  - uid owning the token                              */
7897 /*              ptr(I)  - context pointer for the token                     */
7898 /*                                                                          */
7899 /* This function handles all of the ioctl command that are actually issued  */
7900 /* to the /dev/ipl device.                                                  */
7901 /* ------------------------------------------------------------------------ */
7902 int
7903 ipf_ipf_ioctl(ipf_main_softc_t *softc, caddr_t data, ioctlcmd_t cmd, int mode,
7904 	int uid, void *ctx)
7905 {
7906 	friostat_t fio;
7907 	int error, tmp;
7908 	ipfobj_t obj;
7909 	SPL_INT(s);
7910 
7911 	switch (cmd)
7912 	{
7913 	case SIOCFRENB :
7914 		if (!(mode & FWRITE)) {
7915 			IPFERROR(94);
7916 			error = EPERM;
7917 		} else {
7918 			error = BCOPYIN(data, &tmp, sizeof(tmp));
7919 			if (error != 0) {
7920 				IPFERROR(95);
7921 				error = EFAULT;
7922 				break;
7923 			}
7924 
7925 			WRITE_ENTER(&softc->ipf_global);
7926 			if (tmp) {
7927 				if (softc->ipf_running > 0)
7928 					error = 0;
7929 				else
7930 					error = ipfattach(softc);
7931 				if (error == 0)
7932 					softc->ipf_running = 1;
7933 				else
7934 					(void) ipfdetach(softc);
7935 			} else {
7936 				if (softc->ipf_running == 1)
7937 					error = ipfdetach(softc);
7938 				else
7939 					error = 0;
7940 				if (error == 0)
7941 					softc->ipf_running = -1;
7942 			}
7943 			RWLOCK_EXIT(&softc->ipf_global);
7944 		}
7945 		break;
7946 
7947 	case SIOCIPFSET :
7948 		if (!(mode & FWRITE)) {
7949 			IPFERROR(96);
7950 			error = EPERM;
7951 			break;
7952 		}
7953 		/* FALLTHRU */
7954 	case SIOCIPFGETNEXT :
7955 	case SIOCIPFGET :
7956 		error = ipf_ipftune(softc, cmd, (void *)data);
7957 		break;
7958 
7959 	case SIOCSETFF :
7960 		if (!(mode & FWRITE)) {
7961 			IPFERROR(97);
7962 			error = EPERM;
7963 		} else {
7964 			error = BCOPYIN(data, &softc->ipf_flags,
7965 					sizeof(softc->ipf_flags));
7966 			if (error != 0) {
7967 				IPFERROR(98);
7968 				error = EFAULT;
7969 			}
7970 		}
7971 		break;
7972 
7973 	case SIOCGETFF :
7974 		error = BCOPYOUT(&softc->ipf_flags, data,
7975 				 sizeof(softc->ipf_flags));
7976 		if (error != 0) {
7977 			IPFERROR(99);
7978 			error = EFAULT;
7979 		}
7980 		break;
7981 
7982 	case SIOCFUNCL :
7983 		error = ipf_resolvefunc(softc, (void *)data);
7984 		break;
7985 
7986 	case SIOCINAFR :
7987 	case SIOCRMAFR :
7988 	case SIOCADAFR :
7989 	case SIOCZRLST :
7990 		if (!(mode & FWRITE)) {
7991 			IPFERROR(100);
7992 			error = EPERM;
7993 		} else {
7994 			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
7995 					  softc->ipf_active, 1);
7996 		}
7997 		break;
7998 
7999 	case SIOCINIFR :
8000 	case SIOCRMIFR :
8001 	case SIOCADIFR :
8002 		if (!(mode & FWRITE)) {
8003 			IPFERROR(101);
8004 			error = EPERM;
8005 		} else {
8006 			error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8007 					  1 - softc->ipf_active, 1);
8008 		}
8009 		break;
8010 
8011 	case SIOCSWAPA :
8012 		if (!(mode & FWRITE)) {
8013 			IPFERROR(102);
8014 			error = EPERM;
8015 		} else {
8016 			WRITE_ENTER(&softc->ipf_mutex);
8017 			error = BCOPYOUT(&softc->ipf_active, data,
8018 					 sizeof(softc->ipf_active));
8019 			if (error != 0) {
8020 				IPFERROR(103);
8021 				error = EFAULT;
8022 			} else {
8023 				softc->ipf_active = 1 - softc->ipf_active;
8024 			}
8025 			RWLOCK_EXIT(&softc->ipf_mutex);
8026 		}
8027 		break;
8028 
8029 	case SIOCGETFS :
8030 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
8031 				  IPFOBJ_IPFSTAT);
8032 		if (error != 0)
8033 			break;
8034 		ipf_getstat(softc, &fio, obj.ipfo_rev);
8035 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8036 		break;
8037 
8038 	case SIOCFRZST :
8039 		if (!(mode & FWRITE)) {
8040 			IPFERROR(104);
8041 			error = EPERM;
8042 		} else
8043 			error = ipf_zerostats(softc, (caddr_t)data);
8044 		break;
8045 
8046 	case SIOCIPFFL :
8047 		if (!(mode & FWRITE)) {
8048 			IPFERROR(105);
8049 			error = EPERM;
8050 		} else {
8051 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8052 			if (!error) {
8053 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8054 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8055 				if (error != 0) {
8056 					IPFERROR(106);
8057 					error = EFAULT;
8058 				}
8059 			} else {
8060 				IPFERROR(107);
8061 				error = EFAULT;
8062 			}
8063 		}
8064 		break;
8065 
8066 #ifdef USE_INET6
8067 	case SIOCIPFL6 :
8068 		if (!(mode & FWRITE)) {
8069 			IPFERROR(108);
8070 			error = EPERM;
8071 		} else {
8072 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8073 			if (!error) {
8074 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8075 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
8076 				if (error != 0) {
8077 					IPFERROR(109);
8078 					error = EFAULT;
8079 				}
8080 			} else {
8081 				IPFERROR(110);
8082 				error = EFAULT;
8083 			}
8084 		}
8085 		break;
8086 #endif
8087 
8088 	case SIOCSTLCK :
8089 		if (!(mode & FWRITE)) {
8090 			IPFERROR(122);
8091 			error = EPERM;
8092 		} else {
8093 			error = BCOPYIN(data, &tmp, sizeof(tmp));
8094 			if (error == 0) {
8095 				ipf_state_setlock(softc->ipf_state_soft, tmp);
8096 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8097 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8098 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8099 			} else {
8100 				IPFERROR(111);
8101 				error = EFAULT;
8102 			}
8103 		}
8104 		break;
8105 
8106 #ifdef	IPFILTER_LOG
8107 	case SIOCIPFFB :
8108 		if (!(mode & FWRITE)) {
8109 			IPFERROR(112);
8110 			error = EPERM;
8111 		} else {
8112 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
8113 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
8114 			if (error) {
8115 				IPFERROR(113);
8116 				error = EFAULT;
8117 			}
8118 		}
8119 		break;
8120 #endif /* IPFILTER_LOG */
8121 
8122 	case SIOCFRSYN :
8123 		if (!(mode & FWRITE)) {
8124 			IPFERROR(114);
8125 			error = EPERM;
8126 		} else {
8127 			WRITE_ENTER(&softc->ipf_global);
8128 #if (SOLARIS && defined(_KERNEL)) && !defined(INSTANCES)
8129 			error = ipfsync();
8130 #else
8131 			ipf_sync(softc, NULL);
8132 			error = 0;
8133 #endif
8134 			RWLOCK_EXIT(&softc->ipf_global);
8135 
8136 		}
8137 		break;
8138 
8139 	case SIOCGFRST :
8140 		error = ipf_outobj(softc, (void *)data,
8141 				   ipf_frag_stats(softc->ipf_frag_soft),
8142 				   IPFOBJ_FRAGSTAT);
8143 		break;
8144 
8145 #ifdef	IPFILTER_LOG
8146 	case FIONREAD :
8147 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8148 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
8149 		break;
8150 #endif
8151 
8152 	case SIOCIPFITER :
8153 		SPL_SCHED(s);
8154 		error = ipf_frruleiter(softc, data, uid, ctx);
8155 		SPL_X(s);
8156 		break;
8157 
8158 	case SIOCGENITER :
8159 		SPL_SCHED(s);
8160 		error = ipf_genericiter(softc, data, uid, ctx);
8161 		SPL_X(s);
8162 		break;
8163 
8164 	case SIOCIPFDELTOK :
8165 		error = BCOPYIN(data, &tmp, sizeof(tmp));
8166 		if (error == 0) {
8167 			SPL_SCHED(s);
8168 			error = ipf_token_del(softc, tmp, uid, ctx);
8169 			SPL_X(s);
8170 		}
8171 		break;
8172 
8173 	default :
8174 		IPFERROR(115);
8175 		error = EINVAL;
8176 		break;
8177 	}
8178 
8179 	return (error);
8180 }
8181 
8182 
8183 /* ------------------------------------------------------------------------ */
8184 /* Function:    ipf_decaps                                                  */
8185 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8186 /*                           flags indicating packet filtering decision.    */
8187 /* Parameters:  fin(I)     - pointer to packet information                  */
8188 /*              pass(I)    - IP protocol version to match                   */
8189 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8190 /*                                                                          */
8191 /* This function is called for packets that are wrapt up in other packets,  */
8192 /* for example, an IP packet that is the entire data segment for another IP */
8193 /* packet.  If the basic constraints for this are satisfied, change the     */
8194 /* buffer to point to the start of the inner packet and start processing    */
8195 /* rules belonging to the head group this rule specifies.                   */
8196 /* ------------------------------------------------------------------------ */
8197 u_32_t
8198 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8199 {
8200 	fr_info_t fin2, *fino = NULL;
8201 	int elen, hlen, nh;
8202 	grehdr_t gre;
8203 	ip_t *ip;
8204 	mb_t *m;
8205 
8206 	if ((fin->fin_flx & FI_COALESCE) == 0)
8207 		if (ipf_coalesce(fin) == -1)
8208 			goto cantdecaps;
8209 
8210 	m = fin->fin_m;
8211 	hlen = fin->fin_hlen;
8212 
8213 	switch (fin->fin_p)
8214 	{
8215 	case IPPROTO_UDP :
8216 		/*
8217 		 * In this case, the specific protocol being decapsulated
8218 		 * inside UDP frames comes from the rule.
8219 		 */
8220 		nh = fin->fin_fr->fr_icode;
8221 		break;
8222 
8223 	case IPPROTO_GRE :	/* 47 */
8224 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8225 		hlen += sizeof(grehdr_t);
8226 		if (gre.gr_R|gre.gr_s)
8227 			goto cantdecaps;
8228 		if (gre.gr_C)
8229 			hlen += 4;
8230 		if (gre.gr_K)
8231 			hlen += 4;
8232 		if (gre.gr_S)
8233 			hlen += 4;
8234 
8235 		nh = IPPROTO_IP;
8236 
8237 		/*
8238 		 * If the routing options flag is set, validate that it is
8239 		 * there and bounce over it.
8240 		 */
8241 #if 0
8242 		/* This is really heavy weight and lots of room for error, */
8243 		/* so for now, put it off and get the simple stuff right.  */
8244 		if (gre.gr_R) {
8245 			u_char off, len, *s;
8246 			u_short af;
8247 			int end;
8248 
8249 			end = 0;
8250 			s = fin->fin_dp;
8251 			s += hlen;
8252 			aplen = fin->fin_plen - hlen;
8253 			while (aplen > 3) {
8254 				af = (s[0] << 8) | s[1];
8255 				off = s[2];
8256 				len = s[3];
8257 				aplen -= 4;
8258 				s += 4;
8259 				if (af == 0 && len == 0) {
8260 					end = 1;
8261 					break;
8262 				}
8263 				if (aplen < len)
8264 					break;
8265 				s += len;
8266 				aplen -= len;
8267 			}
8268 			if (end != 1)
8269 				goto cantdecaps;
8270 			hlen = s - (u_char *)fin->fin_dp;
8271 		}
8272 #endif
8273 		break;
8274 
8275 #ifdef IPPROTO_IPIP
8276 	case IPPROTO_IPIP :	/* 4 */
8277 #endif
8278 		nh = IPPROTO_IP;
8279 		break;
8280 
8281 	default :	/* Includes ESP, AH is special for IPv4 */
8282 		goto cantdecaps;
8283 	}
8284 
8285 	switch (nh)
8286 	{
8287 	case IPPROTO_IP :
8288 	case IPPROTO_IPV6 :
8289 		break;
8290 	default :
8291 		goto cantdecaps;
8292 	}
8293 
8294 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8295 	fino = fin;
8296 	fin = &fin2;
8297 	elen = hlen;
8298 #if SOLARIS && defined(_KERNEL)
8299 	m->b_rptr += elen;
8300 #else
8301 	m->m_data += elen;
8302 	m->m_len -= elen;
8303 #endif
8304 	fin->fin_plen -= elen;
8305 
8306 	ip = (ip_t *)((char *)fin->fin_ip + elen);
8307 
8308 	/*
8309 	 * Make sure we have at least enough data for the network layer
8310 	 * header.
8311 	 */
8312 	if (IP_V(ip) == 4)
8313 		hlen = IP_HL(ip) << 2;
8314 #ifdef USE_INET6
8315 	else if (IP_V(ip) == 6)
8316 		hlen = sizeof(ip6_t);
8317 #endif
8318 	else
8319 		goto cantdecaps2;
8320 
8321 	if (fin->fin_plen < hlen)
8322 		goto cantdecaps2;
8323 
8324 	fin->fin_dp = (char *)ip + hlen;
8325 
8326 	if (IP_V(ip) == 4) {
8327 		/*
8328 		 * Perform IPv4 header checksum validation.
8329 		 */
8330 		if (ipf_cksum((u_short *)ip, hlen))
8331 			goto cantdecaps2;
8332 	}
8333 
8334 	if (ipf_makefrip(hlen, ip, fin) == -1) {
8335 cantdecaps2:
8336 		if (m != NULL) {
8337 #if SOLARIS && defined(_KERNEL)
8338 			m->b_rptr -= elen;
8339 #else
8340 			m->m_data -= elen;
8341 			m->m_len += elen;
8342 #endif
8343 		}
8344 cantdecaps:
8345 		DT1(frb_decapfrip, fr_info_t *, fin);
8346 		pass &= ~FR_CMDMASK;
8347 		pass |= FR_BLOCK|FR_QUICK;
8348 		fin->fin_reason = FRB_DECAPFRIP;
8349 		return (-1);
8350 	}
8351 
8352 	pass = ipf_scanlist(fin, pass);
8353 
8354 	/*
8355 	 * Copy the packet filter "result" fields out of the fr_info_t struct
8356 	 * that is local to the decapsulation processing and back into the
8357 	 * one we were called with.
8358 	 */
8359 	fino->fin_flx = fin->fin_flx;
8360 	fino->fin_rev = fin->fin_rev;
8361 	fino->fin_icode = fin->fin_icode;
8362 	fino->fin_rule = fin->fin_rule;
8363 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8364 	fino->fin_fr = fin->fin_fr;
8365 	fino->fin_error = fin->fin_error;
8366 	fino->fin_mp = fin->fin_mp;
8367 	fino->fin_m = fin->fin_m;
8368 	m = fin->fin_m;
8369 	if (m != NULL) {
8370 #if SOLARIS && defined(_KERNEL)
8371 		m->b_rptr -= elen;
8372 #else
8373 		m->m_data -= elen;
8374 		m->m_len += elen;
8375 #endif
8376 	}
8377 	return (pass);
8378 }
8379 
8380 
8381 /* ------------------------------------------------------------------------ */
8382 /* Function:    ipf_matcharray_load                                         */
8383 /* Returns:     int         - 0 = success, else error                       */
8384 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8385 /*              data(I)     - pointer to ioctl data                         */
8386 /*              objp(I)     - ipfobj_t structure to load data into          */
8387 /*              arrayptr(I) - pointer to location to store array pointer    */
8388 /*                                                                          */
8389 /* This function loads in a mathing array through the ipfobj_t struct that  */
8390 /* describes it.  Sanity checking and array size limitations are enforced   */
8391 /* in this function to prevent userspace from trying to load in something   */
8392 /* that is insanely big.  Once the size of the array is known, the memory   */
8393 /* required is malloc'd and returned through changing *arrayptr.  The       */
8394 /* contents of the array are verified before returning.  Only in the event  */
8395 /* of a successful call is the caller required to free up the malloc area.  */
8396 /* ------------------------------------------------------------------------ */
8397 int
8398 ipf_matcharray_load(ipf_main_softc_t *softc, caddr_t data, ipfobj_t *objp,
8399 	int **arrayptr)
8400 {
8401 	int arraysize, *array, error;
8402 
8403 	*arrayptr = NULL;
8404 
8405 	error = BCOPYIN(data, objp, sizeof(*objp));
8406 	if (error != 0) {
8407 		IPFERROR(116);
8408 		return (EFAULT);
8409 	}
8410 
8411 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8412 		IPFERROR(117);
8413 		return (EINVAL);
8414 	}
8415 
8416 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8417 	    (objp->ipfo_size > 1024)) {
8418 		IPFERROR(118);
8419 		return (EINVAL);
8420 	}
8421 
8422 	arraysize = objp->ipfo_size * sizeof(*array);
8423 	KMALLOCS(array, int *, arraysize);
8424 	if (array == NULL) {
8425 		IPFERROR(119);
8426 		return (ENOMEM);
8427 	}
8428 
8429 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
8430 	if (error != 0) {
8431 		KFREES(array, arraysize);
8432 		IPFERROR(120);
8433 		return (EFAULT);
8434 	}
8435 
8436 	if (ipf_matcharray_verify(array, arraysize) != 0) {
8437 		KFREES(array, arraysize);
8438 		IPFERROR(121);
8439 		return (EINVAL);
8440 	}
8441 
8442 	*arrayptr = array;
8443 	return (0);
8444 }
8445 
8446 
8447 /* ------------------------------------------------------------------------ */
8448 /* Function:    ipf_matcharray_verify                                       */
8449 /* Returns:     Nil                                                         */
8450 /* Parameters:  array(I)     - pointer to matching array                    */
8451 /*              arraysize(I) - number of elements in the array              */
8452 /*                                                                          */
8453 /* Verify the contents of a matching array by stepping through each element */
8454 /* in it.  The actual commands in the array are not verified for            */
8455 /* correctness, only that all of the sizes are correctly within limits.     */
8456 /* ------------------------------------------------------------------------ */
8457 int
8458 ipf_matcharray_verify(int *array, int arraysize)
8459 {
8460 	int i, nelem, maxidx;
8461 	ipfexp_t *e;
8462 
8463 	nelem = arraysize / sizeof(*array);
8464 
8465 	/*
8466 	 * Currently, it makes no sense to have an array less than 6
8467 	 * elements long - the initial size at the from, a single operation
8468 	 * (minimum 4 in length) and a trailer, for a total of 6.
8469 	 */
8470 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8471 		return (-1);
8472 	}
8473 
8474 	/*
8475 	 * Verify the size of data pointed to by array with how long
8476 	 * the array claims to be itself.
8477 	 */
8478 	if (array[0] * sizeof(*array) != arraysize) {
8479 		return (-1);
8480 	}
8481 
8482 	maxidx = nelem - 1;
8483 	/*
8484 	 * The last opcode in this array should be an IPF_EXP_END.
8485 	 */
8486 	if (array[maxidx] != IPF_EXP_END) {
8487 		return (-1);
8488 	}
8489 
8490 	for (i = 1; i < maxidx; ) {
8491 		e = (ipfexp_t *)(array + i);
8492 
8493 		/*
8494 		 * The length of the bits to check must be at least 1
8495 		 * (or else there is nothing to comapre with!) and it
8496 		 * cannot exceed the length of the data present.
8497 		 */
8498 		if ((e->ipfe_size < 1 ) ||
8499 		    (e->ipfe_size + i > maxidx)) {
8500 			return (-1);
8501 		}
8502 		i += e->ipfe_size;
8503 	}
8504 	return (0);
8505 }
8506 
8507 
8508 /* ------------------------------------------------------------------------ */
8509 /* Function:    ipf_fr_matcharray                                           */
8510 /* Returns:     int      - 0 = match failed, else positive match            */
8511 /* Parameters:  fin(I)   - pointer to packet information                    */
8512 /*              array(I) - pointer to matching array                        */
8513 /*                                                                          */
8514 /* This function is used to apply a matching array against a packet and     */
8515 /* return an indication of whether or not the packet successfully matches   */
8516 /* all of the commands in it.                                               */
8517 /* ------------------------------------------------------------------------ */
8518 static int
8519 ipf_fr_matcharray(fr_info_t *fin, int *array)
8520 {
8521 	int i, n, *x, rv, p;
8522 	ipfexp_t *e;
8523 
8524 	rv = 0;
8525 	n = array[0];
8526 	x = array + 1;
8527 
8528 	for (; n > 0; x += 3 + x[3], rv = 0) {
8529 		e = (ipfexp_t *)x;
8530 		if (e->ipfe_cmd == IPF_EXP_END)
8531 			break;
8532 		n -= e->ipfe_size;
8533 
8534 		/*
8535 		 * The upper 16 bits currently store the protocol value.
8536 		 * This is currently used with TCP and UDP port compares and
8537 		 * allows "tcp.port = 80" without requiring an explicit
8538 		 " "ip.pr = tcp" first.
8539 		 */
8540 		p = e->ipfe_cmd >> 16;
8541 		if ((p != 0) && (p != fin->fin_p))
8542 			break;
8543 
8544 		switch (e->ipfe_cmd)
8545 		{
8546 		case IPF_EXP_IP_PR :
8547 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8548 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
8549 			}
8550 			break;
8551 
8552 		case IPF_EXP_IP_SRCADDR :
8553 			if (fin->fin_v != 4)
8554 				break;
8555 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8556 				rv |= ((fin->fin_saddr &
8557 					e->ipfe_arg0[i * 2 + 1]) ==
8558 				       e->ipfe_arg0[i * 2]);
8559 			}
8560 			break;
8561 
8562 		case IPF_EXP_IP_DSTADDR :
8563 			if (fin->fin_v != 4)
8564 				break;
8565 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8566 				rv |= ((fin->fin_daddr &
8567 					e->ipfe_arg0[i * 2 + 1]) ==
8568 				       e->ipfe_arg0[i * 2]);
8569 			}
8570 			break;
8571 
8572 		case IPF_EXP_IP_ADDR :
8573 			if (fin->fin_v != 4)
8574 				break;
8575 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8576 				rv |= ((fin->fin_saddr &
8577 					e->ipfe_arg0[i * 2 + 1]) ==
8578 				       e->ipfe_arg0[i * 2]) ||
8579 				      ((fin->fin_daddr &
8580 					e->ipfe_arg0[i * 2 + 1]) ==
8581 				       e->ipfe_arg0[i * 2]);
8582 			}
8583 			break;
8584 
8585 #ifdef USE_INET6
8586 		case IPF_EXP_IP6_SRCADDR :
8587 			if (fin->fin_v != 6)
8588 				break;
8589 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8590 				rv |= IP6_MASKEQ(&fin->fin_src6,
8591 						 &e->ipfe_arg0[i * 8 + 4],
8592 						 &e->ipfe_arg0[i * 8]);
8593 			}
8594 			break;
8595 
8596 		case IPF_EXP_IP6_DSTADDR :
8597 			if (fin->fin_v != 6)
8598 				break;
8599 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8600 				rv |= IP6_MASKEQ(&fin->fin_dst6,
8601 						 &e->ipfe_arg0[i * 8 + 4],
8602 						 &e->ipfe_arg0[i * 8]);
8603 			}
8604 			break;
8605 
8606 		case IPF_EXP_IP6_ADDR :
8607 			if (fin->fin_v != 6)
8608 				break;
8609 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8610 				rv |= IP6_MASKEQ(&fin->fin_src6,
8611 						 &e->ipfe_arg0[i * 8 + 4],
8612 						 &e->ipfe_arg0[i * 8]) ||
8613 				      IP6_MASKEQ(&fin->fin_dst6,
8614 						 &e->ipfe_arg0[i * 8 + 4],
8615 						 &e->ipfe_arg0[i * 8]);
8616 			}
8617 			break;
8618 #endif
8619 
8620 		case IPF_EXP_UDP_PORT :
8621 		case IPF_EXP_TCP_PORT :
8622 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8623 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8624 				      (fin->fin_dport == e->ipfe_arg0[i]);
8625 			}
8626 			break;
8627 
8628 		case IPF_EXP_UDP_SPORT :
8629 		case IPF_EXP_TCP_SPORT :
8630 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8631 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8632 			}
8633 			break;
8634 
8635 		case IPF_EXP_UDP_DPORT :
8636 		case IPF_EXP_TCP_DPORT :
8637 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8638 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8639 			}
8640 			break;
8641 
8642 		case IPF_EXP_TCP_FLAGS :
8643 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
8644 				rv |= ((fin->fin_tcpf &
8645 					e->ipfe_arg0[i * 2 + 1]) ==
8646 				       e->ipfe_arg0[i * 2]);
8647 			}
8648 			break;
8649 		}
8650 		rv ^= e->ipfe_not;
8651 
8652 		if (rv == 0)
8653 			break;
8654 	}
8655 
8656 	return (rv);
8657 }
8658 
8659 
8660 /* ------------------------------------------------------------------------ */
8661 /* Function:    ipf_queueflush                                              */
8662 /* Returns:     int - number of entries flushed (0 = none)                  */
8663 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8664 /*              deletefn(I) - function to call to delete entry              */
8665 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8666 /*              userqs(I)   - top of the list of user defined timeouts      */
8667 /*                                                                          */
8668 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8669 /* need to try a bit harder to free up some space.  The algorithm used here */
8670 /* split into two parts but both halves have the same goal: to reduce the   */
8671 /* number of connections considered to be "active" to the low watermark.    */
8672 /* There are two steps in doing this:                                       */
8673 /* 1) Remove any TCP connections that are already considered to be "closed" */
8674 /*    but have not yet been removed from the state table.  The two states   */
8675 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8676 /*    candidates for this style of removal.  If freeing up entries in       */
8677 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8678 /*    we do not go on to step 2.                                            */
8679 /*                                                                          */
8680 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8681 /*    they are within the given window we are considering.  Where the       */
8682 /*    window starts and the steps taken to increase its size depend upon    */
8683 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8684 /*    last 30 seconds is not touched.                                       */
8685 /*                                              touched                     */
8686 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8687 /*           |          |        |           |     |     |                  */
8688 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8689 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8690 /*                                                                          */
8691 /* Points to note:                                                          */
8692 /* - tqe_die is the time, in the future, when entries die.                  */
8693 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8694 /*   ticks.                                                                 */
8695 /* - tqe_touched is when the entry was last used by NAT/state               */
8696 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8697 /*   ipf_ticks any given timeout queue and vice versa.                      */
8698 /* - both tqe_die and tqe_touched increase over time                        */
8699 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8700 /*   bottom and therefore the smallest values of each are at the top        */
8701 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8702 /*   queues representing each of the TCP states                             */
8703 /*                                                                          */
8704 /* We start by setting up a maximum range to scan for things to move of     */
8705 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8706 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8707 /* we start again with a new value for "iend" and "istart".  This is        */
8708 /* continued until we either finish the scan of 30 second intervals or the  */
8709 /* low water mark is reached.                                               */
8710 /* ------------------------------------------------------------------------ */
8711 int
8712 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8713 	ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8714 {
8715 	u_long interval, istart, iend;
8716 	ipftq_t *ifq, *ifqnext;
8717 	ipftqent_t *tqe, *tqn;
8718 	int removed = 0;
8719 
8720 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8721 		tqn = tqe->tqe_next;
8722 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8723 			removed++;
8724 	}
8725 	if ((*activep * 100 / size) > low) {
8726 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8727 		     ((tqe = tqn) != NULL); ) {
8728 			tqn = tqe->tqe_next;
8729 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8730 				removed++;
8731 		}
8732 	}
8733 
8734 	if ((*activep * 100 / size) <= low) {
8735 		return (removed);
8736 	}
8737 
8738 	/*
8739 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8740 	 *       used then the operations are upgraded to floating point
8741 	 *       and kernels don't like floating point...
8742 	 */
8743 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8744 		istart = IPF_TTLVAL(86400 * 4);
8745 		interval = IPF_TTLVAL(43200);
8746 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8747 		istart = IPF_TTLVAL(43200);
8748 		interval = IPF_TTLVAL(1800);
8749 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8750 		istart = IPF_TTLVAL(1800);
8751 		interval = IPF_TTLVAL(30);
8752 	} else {
8753 		return (0);
8754 	}
8755 	if (istart > softc->ipf_ticks) {
8756 		if (softc->ipf_ticks - interval < interval)
8757 			istart = interval;
8758 		else
8759 			istart = (softc->ipf_ticks / interval) * interval;
8760 	}
8761 
8762 	iend = softc->ipf_ticks - interval;
8763 
8764 	while ((*activep * 100 / size) > low) {
8765 		u_long try;
8766 
8767 		try = softc->ipf_ticks - istart;
8768 
8769 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8770 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8771 				if (try < tqe->tqe_touched)
8772 					break;
8773 				tqn = tqe->tqe_next;
8774 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8775 					removed++;
8776 			}
8777 		}
8778 
8779 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8780 			ifqnext = ifq->ifq_next;
8781 
8782 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8783 				if (try < tqe->tqe_touched)
8784 					break;
8785 				tqn = tqe->tqe_next;
8786 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8787 					removed++;
8788 			}
8789 		}
8790 
8791 		if (try >= iend) {
8792 			if (interval == IPF_TTLVAL(43200)) {
8793 				interval = IPF_TTLVAL(1800);
8794 			} else if (interval == IPF_TTLVAL(1800)) {
8795 				interval = IPF_TTLVAL(30);
8796 			} else {
8797 				break;
8798 			}
8799 			if (interval >= softc->ipf_ticks)
8800 				break;
8801 
8802 			iend = softc->ipf_ticks - interval;
8803 		}
8804 		istart -= interval;
8805 	}
8806 
8807 	return (removed);
8808 }
8809 
8810 
8811 /* ------------------------------------------------------------------------ */
8812 /* Function:    ipf_deliverlocal                                            */
8813 /* Returns:     int - 1 = local address, 0 = non-local address              */
8814 /* Parameters:  softc(I)     - pointer to soft context main structure       */
8815 /*              ipversion(I) - IP protocol version (4 or 6)                 */
8816 /*              ifp(I)       - network interface pointer                    */
8817 /*              ipaddr(I)    - IPv4/6 destination address                   */
8818 /*                                                                          */
8819 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
8820 /* the network interface represented by ifp.                                */
8821 /* ------------------------------------------------------------------------ */
8822 int
8823 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8824 	i6addr_t *ipaddr)
8825 {
8826 	i6addr_t addr;
8827 	int islocal = 0;
8828 
8829 	if (ipversion == 4) {
8830 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8831 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
8832 				islocal = 1;
8833 		}
8834 
8835 #ifdef USE_INET6
8836 	} else if (ipversion == 6) {
8837 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8838 			if (IP6_EQ(&addr, ipaddr))
8839 				islocal = 1;
8840 		}
8841 #endif
8842 	}
8843 
8844 	return (islocal);
8845 }
8846 
8847 
8848 /* ------------------------------------------------------------------------ */
8849 /* Function:    ipf_settimeout                                              */
8850 /* Returns:     int - 0 = success, -1 = failure                             */
8851 /* Parameters:  softc(I) - pointer to soft context main structure           */
8852 /*              t(I)     - pointer to tuneable array entry                  */
8853 /*              p(I)     - pointer to values passed in to apply             */
8854 /*                                                                          */
8855 /* This function is called to set the timeout values for each distinct      */
8856 /* queue timeout that is available.  When called, it calls into both the    */
8857 /* state and NAT code, telling them to update their timeout queues.         */
8858 /* ------------------------------------------------------------------------ */
8859 static int
8860 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8861 	ipftuneval_t *p)
8862 {
8863 
8864 	/*
8865 	 * ipf_interror should be set by the functions called here, not
8866 	 * by this function - it's just a middle man.
8867 	 */
8868 	if (ipf_state_settimeout(softc, t, p) == -1)
8869 		return (-1);
8870 	if (ipf_nat_settimeout(softc, t, p) == -1)
8871 		return (-1);
8872 	return (0);
8873 }
8874 
8875 
8876 /* ------------------------------------------------------------------------ */
8877 /* Function:    ipf_apply_timeout                                           */
8878 /* Returns:     int - 0 = success, -1 = failure                             */
8879 /* Parameters:  head(I)    - pointer to tuneable array entry                */
8880 /*              seconds(I) - pointer to values passed in to apply           */
8881 /*                                                                          */
8882 /* This function applies a timeout of "seconds" to the timeout queue that   */
8883 /* is pointed to by "head".  All entries on this list have an expiration    */
8884 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
8885 /* function should only be called when the delta is non-zero, the task is   */
8886 /* to walk the entire list and apply the change.  The sort order will not   */
8887 /* change.  The only catch is that this is O(n) across the list, so if the  */
8888 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
8889 /* could take a relatively long time to work through them all.              */
8890 /* ------------------------------------------------------------------------ */
8891 void
8892 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8893 {
8894 	u_int oldtimeout, newtimeout;
8895 	ipftqent_t *tqe;
8896 	int delta;
8897 
8898 	MUTEX_ENTER(&head->ifq_lock);
8899 	oldtimeout = head->ifq_ttl;
8900 	newtimeout = IPF_TTLVAL(seconds);
8901 	delta = oldtimeout - newtimeout;
8902 
8903 	head->ifq_ttl = newtimeout;
8904 
8905 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8906 		tqe->tqe_die += delta;
8907 	}
8908 	MUTEX_EXIT(&head->ifq_lock);
8909 }
8910 
8911 
8912 /* ------------------------------------------------------------------------ */
8913 /* Function:   ipf_settimeout_tcp                                           */
8914 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
8915 /* Parameters: t(I)   - pointer to tuneable to change                       */
8916 /*             p(I)   - pointer to new timeout information                  */
8917 /*             tab(I) - pointer to table of TCP queues                      */
8918 /*                                                                          */
8919 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
8920 /* updates all of the entries on the relevant timeout queue by calling      */
8921 /* ipf_apply_timeout().                                                     */
8922 /* ------------------------------------------------------------------------ */
8923 int
8924 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8925 {
8926 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8927 	    !strcmp(t->ipft_name, "tcp_established")) {
8928 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8929 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8930 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8931 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8932 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8933 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8934 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8935 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8936 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8937 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
8938 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8939 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8940 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8941 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
8942 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8943 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8944 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8945 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
8946 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
8947 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
8948 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8949 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
8950 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8951 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
8952 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
8953 	} else {
8954 		/*
8955 		 * ipf_interror isn't set here because it should be set
8956 		 * by whatever called this function.
8957 		 */
8958 		return (-1);
8959 	}
8960 	return (0);
8961 }
8962 
8963 
8964 /* ------------------------------------------------------------------------ */
8965 /* Function:   ipf_main_soft_create                                         */
8966 /* Returns:    NULL = failure, else success                                 */
8967 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
8968 /*                                                                          */
8969 /* Create the foundation soft context structure. In circumstances where it  */
8970 /* is not required to dynamically allocate the context, a pointer can be    */
8971 /* passed in (rather than NULL) to a structure to be initialised.           */
8972 /* The main thing of interest is that a number of locks are initialised     */
8973 /* here instead of in the where might be expected - in the relevant create  */
8974 /* function elsewhere.  This is done because the current locking design has */
8975 /* some areas where these locks are used outside of their module.           */
8976 /* Possibly the most important exercise that is done here is setting of all */
8977 /* the timeout values, allowing them to be changed before init().           */
8978 /* ------------------------------------------------------------------------ */
8979 void *
8980 ipf_main_soft_create(void *arg)
8981 {
8982 	ipf_main_softc_t *softc;
8983 
8984 	if (arg == NULL) {
8985 		KMALLOC(softc, ipf_main_softc_t *);
8986 		if (softc == NULL)
8987 			return (NULL);
8988 	} else {
8989 		softc = arg;
8990 	}
8991 
8992 	bzero((char *)softc, sizeof(*softc));
8993 
8994 	/*
8995 	 * This serves as a flag as to whether or not the softc should be
8996 	 * free'd when _destroy is called.
8997 	 */
8998 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
8999 
9000 	softc->ipf_tuners = ipf_tune_array_copy(softc,
9001 						sizeof(ipf_main_tuneables),
9002 						ipf_main_tuneables);
9003 	if (softc->ipf_tuners == NULL) {
9004 		ipf_main_soft_destroy(softc);
9005 		return (NULL);
9006 	}
9007 
9008 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9009 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9010 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9011 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9012 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9013 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9014 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9015 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9016 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9017 
9018 	softc->ipf_token_head = NULL;
9019 	softc->ipf_token_tail = &softc->ipf_token_head;
9020 
9021 	softc->ipf_tcpidletimeout = FIVE_DAYS;
9022 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9023 	softc->ipf_tcplastack = IPF_TTLVAL(30);
9024 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9025 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9026 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9027 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9028 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
9029 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9030 	softc->ipf_udptimeout = IPF_TTLVAL(120);
9031 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9032 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
9033 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9034 	softc->ipf_iptimeout = IPF_TTLVAL(60);
9035 
9036 #if defined(IPFILTER_DEFAULT_BLOCK)
9037 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9038 #else
9039 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9040 #endif
9041 	softc->ipf_minttl = 4;
9042 	softc->ipf_icmpminfragmtu = 68;
9043 	softc->ipf_flags = IPF_LOGGING;
9044 
9045 #ifdef LARGE_NAT
9046 	softc->ipf_large_nat = 1;
9047 #endif
9048 	ipf_fbsd_kenv_get(softc);
9049 
9050 	return (softc);
9051 }
9052 
9053 /* ------------------------------------------------------------------------ */
9054 /* Function:   ipf_main_soft_init                                           */
9055 /* Returns:    0 = success, -1 = failure                                    */
9056 /* Parameters: softc(I) - pointer to soft context main structure            */
9057 /*                                                                          */
9058 /* A null-op function that exists as a placeholder so that the flow in      */
9059 /* other functions is obvious.                                              */
9060 /* ------------------------------------------------------------------------ */
9061 /*ARGSUSED*/
9062 int
9063 ipf_main_soft_init(ipf_main_softc_t *softc)
9064 {
9065 	return (0);
9066 }
9067 
9068 
9069 /* ------------------------------------------------------------------------ */
9070 /* Function:   ipf_main_soft_destroy                                        */
9071 /* Returns:    void                                                         */
9072 /* Parameters: softc(I) - pointer to soft context main structure            */
9073 /*                                                                          */
9074 /* Undo everything that we did in ipf_main_soft_create.                     */
9075 /*                                                                          */
9076 /* The most important check that needs to be made here is whether or not    */
9077 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9078 /* value is stored in ipf_dynamic_main.                                     */
9079 /* ------------------------------------------------------------------------ */
9080 /*ARGSUSED*/
9081 void
9082 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9083 {
9084 
9085 	RW_DESTROY(&softc->ipf_frag);
9086 	RW_DESTROY(&softc->ipf_poolrw);
9087 	RW_DESTROY(&softc->ipf_nat);
9088 	RW_DESTROY(&softc->ipf_state);
9089 	RW_DESTROY(&softc->ipf_tokens);
9090 	RW_DESTROY(&softc->ipf_mutex);
9091 	RW_DESTROY(&softc->ipf_global);
9092 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
9093 	MUTEX_DESTROY(&softc->ipf_rw);
9094 
9095 	if (softc->ipf_tuners != NULL) {
9096 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9097 	}
9098 	if (softc->ipf_dynamic_softc == 1) {
9099 		KFREE(softc);
9100 	}
9101 }
9102 
9103 
9104 /* ------------------------------------------------------------------------ */
9105 /* Function:   ipf_main_soft_fini                                           */
9106 /* Returns:    0 = success, -1 = failure                                    */
9107 /* Parameters: softc(I) - pointer to soft context main structure            */
9108 /*                                                                          */
9109 /* Clean out the rules which have been added since _init was last called,   */
9110 /* the only dynamic part of the mainline.                                   */
9111 /* ------------------------------------------------------------------------ */
9112 int
9113 ipf_main_soft_fini(ipf_main_softc_t *softc)
9114 {
9115 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9116 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9117 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9118 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9119 
9120 	return (0);
9121 }
9122 
9123 
9124 /* ------------------------------------------------------------------------ */
9125 /* Function:   ipf_main_load                                                */
9126 /* Returns:    0 = success, -1 = failure                                    */
9127 /* Parameters: none                                                         */
9128 /*                                                                          */
9129 /* Handle global initialisation that needs to be done for the base part of  */
9130 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9131 /* arrays that get used by the state/NAT code.                              */
9132 /* ------------------------------------------------------------------------ */
9133 int
9134 ipf_main_load(void)
9135 {
9136 	int i;
9137 
9138 	/* fill icmp reply type table */
9139 	for (i = 0; i <= ICMP_MAXTYPE; i++)
9140 		icmpreplytype4[i] = -1;
9141 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9142 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9143 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9144 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9145 
9146 #ifdef  USE_INET6
9147 	/* fill icmp reply type table */
9148 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
9149 		icmpreplytype6[i] = -1;
9150 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9151 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9152 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9153 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9154 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9155 #endif
9156 
9157 	return (0);
9158 }
9159 
9160 
9161 /* ------------------------------------------------------------------------ */
9162 /* Function:   ipf_main_unload                                              */
9163 /* Returns:    0 = success, -1 = failure                                    */
9164 /* Parameters: none                                                         */
9165 /*                                                                          */
9166 /* A null-op function that exists as a placeholder so that the flow in      */
9167 /* other functions is obvious.                                              */
9168 /* ------------------------------------------------------------------------ */
9169 int
9170 ipf_main_unload(void)
9171 {
9172 	return (0);
9173 }
9174 
9175 
9176 /* ------------------------------------------------------------------------ */
9177 /* Function:   ipf_load_all                                                 */
9178 /* Returns:    0 = success, -1 = failure                                    */
9179 /* Parameters: none                                                         */
9180 /*                                                                          */
9181 /* Work through all of the subsystems inside IPFilter and call the load     */
9182 /* function for each in an order that won't lead to a crash :)              */
9183 /* ------------------------------------------------------------------------ */
9184 int
9185 ipf_load_all(void)
9186 {
9187 	if (ipf_main_load() == -1)
9188 		return (-1);
9189 
9190 	if (ipf_state_main_load() == -1)
9191 		return (-1);
9192 
9193 	if (ipf_nat_main_load() == -1)
9194 		return (-1);
9195 
9196 	if (ipf_frag_main_load() == -1)
9197 		return (-1);
9198 
9199 	if (ipf_auth_main_load() == -1)
9200 		return (-1);
9201 
9202 	if (ipf_proxy_main_load() == -1)
9203 		return (-1);
9204 
9205 	return (0);
9206 }
9207 
9208 
9209 /* ------------------------------------------------------------------------ */
9210 /* Function:   ipf_unload_all                                               */
9211 /* Returns:    0 = success, -1 = failure                                    */
9212 /* Parameters: none                                                         */
9213 /*                                                                          */
9214 /* Work through all of the subsystems inside IPFilter and call the unload   */
9215 /* function for each in an order that won't lead to a crash :)              */
9216 /* ------------------------------------------------------------------------ */
9217 int
9218 ipf_unload_all(void)
9219 {
9220 	if (ipf_proxy_main_unload() == -1)
9221 		return (-1);
9222 
9223 	if (ipf_auth_main_unload() == -1)
9224 		return (-1);
9225 
9226 	if (ipf_frag_main_unload() == -1)
9227 		return (-1);
9228 
9229 	if (ipf_nat_main_unload() == -1)
9230 		return (-1);
9231 
9232 	if (ipf_state_main_unload() == -1)
9233 		return (-1);
9234 
9235 	if (ipf_main_unload() == -1)
9236 		return (-1);
9237 
9238 	return (0);
9239 }
9240 
9241 
9242 /* ------------------------------------------------------------------------ */
9243 /* Function:   ipf_create_all                                               */
9244 /* Returns:    NULL = failure, else success                                 */
9245 /* Parameters: arg(I) - pointer to soft context main structure              */
9246 /*                                                                          */
9247 /* Work through all of the subsystems inside IPFilter and call the create   */
9248 /* function for each in an order that won't lead to a crash :)              */
9249 /* ------------------------------------------------------------------------ */
9250 ipf_main_softc_t *
9251 ipf_create_all(void *arg)
9252 {
9253 	ipf_main_softc_t *softc;
9254 
9255 	softc = ipf_main_soft_create(arg);
9256 	if (softc == NULL)
9257 		return (NULL);
9258 
9259 #ifdef IPFILTER_LOG
9260 	softc->ipf_log_soft = ipf_log_soft_create(softc);
9261 	if (softc->ipf_log_soft == NULL) {
9262 		ipf_destroy_all(softc);
9263 		return (NULL);
9264 	}
9265 #endif
9266 
9267 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9268 	if (softc->ipf_lookup_soft == NULL) {
9269 		ipf_destroy_all(softc);
9270 		return (NULL);
9271 	}
9272 
9273 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9274 	if (softc->ipf_sync_soft == NULL) {
9275 		ipf_destroy_all(softc);
9276 		return (NULL);
9277 	}
9278 
9279 	softc->ipf_state_soft = ipf_state_soft_create(softc);
9280 	if (softc->ipf_state_soft == NULL) {
9281 		ipf_destroy_all(softc);
9282 		return (NULL);
9283 	}
9284 
9285 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9286 	if (softc->ipf_nat_soft == NULL) {
9287 		ipf_destroy_all(softc);
9288 		return (NULL);
9289 	}
9290 
9291 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9292 	if (softc->ipf_frag_soft == NULL) {
9293 		ipf_destroy_all(softc);
9294 		return (NULL);
9295 	}
9296 
9297 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9298 	if (softc->ipf_auth_soft == NULL) {
9299 		ipf_destroy_all(softc);
9300 		return (NULL);
9301 	}
9302 
9303 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9304 	if (softc->ipf_proxy_soft == NULL) {
9305 		ipf_destroy_all(softc);
9306 		return (NULL);
9307 	}
9308 
9309 	return (softc);
9310 }
9311 
9312 
9313 /* ------------------------------------------------------------------------ */
9314 /* Function:   ipf_destroy_all                                              */
9315 /* Returns:    void                                                         */
9316 /* Parameters: softc(I) - pointer to soft context main structure            */
9317 /*                                                                          */
9318 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9319 /* function for each in an order that won't lead to a crash :)              */
9320 /*                                                                          */
9321 /* Every one of these functions is expected to succeed, so there is no      */
9322 /* checking of return values.                                               */
9323 /* ------------------------------------------------------------------------ */
9324 void
9325 ipf_destroy_all(ipf_main_softc_t *softc)
9326 {
9327 
9328 	if (softc->ipf_state_soft != NULL) {
9329 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9330 		softc->ipf_state_soft = NULL;
9331 	}
9332 
9333 	if (softc->ipf_nat_soft != NULL) {
9334 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9335 		softc->ipf_nat_soft = NULL;
9336 	}
9337 
9338 	if (softc->ipf_frag_soft != NULL) {
9339 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9340 		softc->ipf_frag_soft = NULL;
9341 	}
9342 
9343 	if (softc->ipf_auth_soft != NULL) {
9344 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9345 		softc->ipf_auth_soft = NULL;
9346 	}
9347 
9348 	if (softc->ipf_proxy_soft != NULL) {
9349 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9350 		softc->ipf_proxy_soft = NULL;
9351 	}
9352 
9353 	if (softc->ipf_sync_soft != NULL) {
9354 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9355 		softc->ipf_sync_soft = NULL;
9356 	}
9357 
9358 	if (softc->ipf_lookup_soft != NULL) {
9359 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9360 		softc->ipf_lookup_soft = NULL;
9361 	}
9362 
9363 #ifdef IPFILTER_LOG
9364 	if (softc->ipf_log_soft != NULL) {
9365 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9366 		softc->ipf_log_soft = NULL;
9367 	}
9368 #endif
9369 
9370 	ipf_main_soft_destroy(softc);
9371 }
9372 
9373 
9374 /* ------------------------------------------------------------------------ */
9375 /* Function:   ipf_init_all                                                 */
9376 /* Returns:    0 = success, -1 = failure                                    */
9377 /* Parameters: softc(I) - pointer to soft context main structure            */
9378 /*                                                                          */
9379 /* Work through all of the subsystems inside IPFilter and call the init     */
9380 /* function for each in an order that won't lead to a crash :)              */
9381 /* ------------------------------------------------------------------------ */
9382 int
9383 ipf_init_all(ipf_main_softc_t *softc)
9384 {
9385 
9386 	if (ipf_main_soft_init(softc) == -1)
9387 		return (-1);
9388 
9389 #ifdef IPFILTER_LOG
9390 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9391 		return (-1);
9392 #endif
9393 
9394 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9395 		return (-1);
9396 
9397 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9398 		return (-1);
9399 
9400 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9401 		return (-1);
9402 
9403 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9404 		return (-1);
9405 
9406 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9407 		return (-1);
9408 
9409 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9410 		return (-1);
9411 
9412 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9413 		return (-1);
9414 
9415 	return (0);
9416 }
9417 
9418 
9419 /* ------------------------------------------------------------------------ */
9420 /* Function:   ipf_fini_all                                                 */
9421 /* Returns:    0 = success, -1 = failure                                    */
9422 /* Parameters: softc(I) - pointer to soft context main structure            */
9423 /*                                                                          */
9424 /* Work through all of the subsystems inside IPFilter and call the fini     */
9425 /* function for each in an order that won't lead to a crash :)              */
9426 /* ------------------------------------------------------------------------ */
9427 int
9428 ipf_fini_all(ipf_main_softc_t *softc)
9429 {
9430 
9431 	ipf_token_flush(softc);
9432 
9433 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9434 		return (-1);
9435 
9436 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9437 		return (-1);
9438 
9439 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9440 		return (-1);
9441 
9442 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9443 		return (-1);
9444 
9445 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9446 		return (-1);
9447 
9448 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9449 		return (-1);
9450 
9451 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9452 		return (-1);
9453 
9454 #ifdef IPFILTER_LOG
9455 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9456 		return (-1);
9457 #endif
9458 
9459 	if (ipf_main_soft_fini(softc) == -1)
9460 		return (-1);
9461 
9462 	return (0);
9463 }
9464 
9465 
9466 /* ------------------------------------------------------------------------ */
9467 /* Function:    ipf_rule_expire                                             */
9468 /* Returns:     Nil                                                         */
9469 /* Parameters:  softc(I) - pointer to soft context main structure           */
9470 /*                                                                          */
9471 /* At present this function exists just to support temporary addition of    */
9472 /* firewall rules. Both inactive and active lists are scanned for items to  */
9473 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9474 /* loaded in.                                                               */
9475 /* ------------------------------------------------------------------------ */
9476 void
9477 ipf_rule_expire(ipf_main_softc_t *softc)
9478 {
9479 	frentry_t *fr;
9480 
9481 	if ((softc->ipf_rule_explist[0] == NULL) &&
9482 	    (softc->ipf_rule_explist[1] == NULL))
9483 		return;
9484 
9485 	WRITE_ENTER(&softc->ipf_mutex);
9486 
9487 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9488 		/*
9489 		 * Because the list is kept sorted on insertion, the fist
9490 		 * one that dies in the future means no more work to do.
9491 		 */
9492 		if (fr->fr_die > softc->ipf_ticks)
9493 			break;
9494 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9495 	}
9496 
9497 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9498 		/*
9499 		 * Because the list is kept sorted on insertion, the fist
9500 		 * one that dies in the future means no more work to do.
9501 		 */
9502 		if (fr->fr_die > softc->ipf_ticks)
9503 			break;
9504 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9505 	}
9506 
9507 	RWLOCK_EXIT(&softc->ipf_mutex);
9508 }
9509 
9510 
9511 static int ipf_ht_node_cmp(struct host_node_s *, struct host_node_s *);
9512 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9513 				      i6addr_t *);
9514 
9515 host_node_t RBI_ZERO(ipf_rb);
9516 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9517 
9518 
9519 /* ------------------------------------------------------------------------ */
9520 /* Function:    ipf_ht_node_cmp                                             */
9521 /* Returns:     int   - 0 == nodes are the same, ..                         */
9522 /* Parameters:  k1(I) - pointer to first key to compare                     */
9523 /*              k2(I) - pointer to second key to compare                    */
9524 /*                                                                          */
9525 /* The "key" for the node is a combination of two fields: the address       */
9526 /* family and the address itself.                                           */
9527 /*                                                                          */
9528 /* Because we're not actually interpreting the address data, it isn't       */
9529 /* necessary to convert them to/from network/host byte order. The mask is   */
9530 /* just used to remove bits that aren't significant - it doesn't matter     */
9531 /* where they are, as long as they're always in the same place.             */
9532 /*                                                                          */
9533 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9534 /* this is where individual ones will differ the most - but not true for    */
9535 /* for /48's, etc.                                                          */
9536 /* ------------------------------------------------------------------------ */
9537 static int
9538 ipf_ht_node_cmp(struct host_node_s *k1, struct host_node_s *k2)
9539 {
9540 	int i;
9541 
9542 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9543 	if (i != 0)
9544 		return (i);
9545 
9546 	if (k1->hn_addr.adf_family == AF_INET)
9547 		return (k2->hn_addr.adf_addr.in4.s_addr -
9548 			k1->hn_addr.adf_addr.in4.s_addr);
9549 
9550 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9551 	if (i != 0)
9552 		return (i);
9553 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9554 	if (i != 0)
9555 		return (i);
9556 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9557 	if (i != 0)
9558 		return (i);
9559 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9560 	return (i);
9561 }
9562 
9563 
9564 /* ------------------------------------------------------------------------ */
9565 /* Function:    ipf_ht_node_make_key                                        */
9566 /* Returns:     Nil                                                         */
9567 /* parameters:  htp(I)    - pointer to address tracking structure           */
9568 /*              key(I)    - where to store masked address for lookup        */
9569 /*              family(I) - protocol family of address                      */
9570 /*              addr(I)   - pointer to network address                      */
9571 /*                                                                          */
9572 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9573 /* copy the address passed in into the key structure whilst masking out the */
9574 /* bits that we don't want.                                                 */
9575 /*                                                                          */
9576 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9577 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9578 /* have to be wary of that and not allow 32-128 to happen.                  */
9579 /* ------------------------------------------------------------------------ */
9580 static void
9581 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9582 	i6addr_t *addr)
9583 {
9584 	key->hn_addr.adf_family = family;
9585 	if (family == AF_INET) {
9586 		u_32_t mask;
9587 		int bits;
9588 
9589 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9590 		bits = htp->ht_netmask;
9591 		if (bits >= 32) {
9592 			mask = 0xffffffff;
9593 		} else {
9594 			mask = htonl(0xffffffff << (32 - bits));
9595 		}
9596 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9597 #ifdef USE_INET6
9598 	} else {
9599 		int bits = htp->ht_netmask;
9600 
9601 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9602 		if (bits > 96) {
9603 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9604 					     htonl(0xffffffff << (128 - bits));
9605 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9606 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9607 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9608 		} else if (bits > 64) {
9609 			key->hn_addr.adf_addr.i6[3] = 0;
9610 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9611 					     htonl(0xffffffff << (96 - bits));
9612 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9613 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9614 		} else if (bits > 32) {
9615 			key->hn_addr.adf_addr.i6[3] = 0;
9616 			key->hn_addr.adf_addr.i6[2] = 0;
9617 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9618 					     htonl(0xffffffff << (64 - bits));
9619 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9620 		} else {
9621 			key->hn_addr.adf_addr.i6[3] = 0;
9622 			key->hn_addr.adf_addr.i6[2] = 0;
9623 			key->hn_addr.adf_addr.i6[1] = 0;
9624 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9625 					     htonl(0xffffffff << (32 - bits));
9626 		}
9627 #endif
9628 	}
9629 }
9630 
9631 
9632 /* ------------------------------------------------------------------------ */
9633 /* Function:    ipf_ht_node_add                                             */
9634 /* Returns:     int       - 0 == success,  -1 == failure                    */
9635 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9636 /*              htp(I)    - pointer to address tracking structure           */
9637 /*              family(I) - protocol family of address                      */
9638 /*              addr(I)   - pointer to network address                      */
9639 /*                                                                          */
9640 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9641 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9642 /*                                                                          */
9643 /* After preparing the key with the address information to find, look in    */
9644 /* the red-black tree to see if the address is known. A successful call to  */
9645 /* this function can mean one of two things: a new node was added to the    */
9646 /* tree or a matching node exists and we're able to bump up its activity.   */
9647 /* ------------------------------------------------------------------------ */
9648 int
9649 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9650 	i6addr_t *addr)
9651 {
9652 	host_node_t *h;
9653 	host_node_t k;
9654 
9655 	ipf_ht_node_make_key(htp, &k, family, addr);
9656 
9657 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9658 	if (h == NULL) {
9659 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9660 			return (-1);
9661 		KMALLOC(h, host_node_t *);
9662 		if (h == NULL) {
9663 			DT(ipf_rb_no_mem);
9664 			LBUMP(ipf_rb_no_mem);
9665 			return (-1);
9666 		}
9667 
9668 		/*
9669 		 * If there was a macro to initialise the RB node then that
9670 		 * would get used here, but there isn't...
9671 		 */
9672 		bzero((char *)h, sizeof(*h));
9673 		h->hn_addr = k.hn_addr;
9674 		h->hn_addr.adf_family = k.hn_addr.adf_family;
9675 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
9676 		htp->ht_cur_nodes++;
9677 	} else {
9678 		if ((htp->ht_max_per_node != 0) &&
9679 		    (h->hn_active >= htp->ht_max_per_node)) {
9680 			DT(ipf_rb_node_max);
9681 			LBUMP(ipf_rb_node_max);
9682 			return (-1);
9683 		}
9684 	}
9685 
9686 	h->hn_active++;
9687 
9688 	return (0);
9689 }
9690 
9691 
9692 /* ------------------------------------------------------------------------ */
9693 /* Function:    ipf_ht_node_del                                             */
9694 /* Returns:     int       - 0 == success,  -1 == failure                    */
9695 /* parameters:  htp(I)    - pointer to address tracking structure           */
9696 /*              family(I) - protocol family of address                      */
9697 /*              addr(I)   - pointer to network address                      */
9698 /*                                                                          */
9699 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9700 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9701 /*                                                                          */
9702 /* Try and find the address passed in amongst the leavese on this tree to   */
9703 /* be friend. If found then drop the active account for that node drops by  */
9704 /* one. If that count reaches 0, it is time to free it all up.              */
9705 /* ------------------------------------------------------------------------ */
9706 int
9707 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9708 {
9709 	host_node_t *h;
9710 	host_node_t k;
9711 
9712 	ipf_ht_node_make_key(htp, &k, family, addr);
9713 
9714 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9715 	if (h == NULL) {
9716 		return (-1);
9717 	} else {
9718 		h->hn_active--;
9719 		if (h->hn_active == 0) {
9720 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9721 			htp->ht_cur_nodes--;
9722 			KFREE(h);
9723 		}
9724 	}
9725 
9726 	return (0);
9727 }
9728 
9729 
9730 /* ------------------------------------------------------------------------ */
9731 /* Function:    ipf_rb_ht_init                                              */
9732 /* Returns:     Nil                                                         */
9733 /* Parameters:  head(I) - pointer to host tracking structure                */
9734 /*                                                                          */
9735 /* Initialise the host tracking structure to be ready for use above.        */
9736 /* ------------------------------------------------------------------------ */
9737 void
9738 ipf_rb_ht_init(host_track_t *head)
9739 {
9740 	RBI_INIT(ipf_rb, &head->ht_root);
9741 }
9742 
9743 
9744 /* ------------------------------------------------------------------------ */
9745 /* Function:    ipf_rb_ht_freenode                                          */
9746 /* Returns:     Nil                                                         */
9747 /* Parameters:  head(I) - pointer to host tracking structure                */
9748 /*              arg(I)  - additional argument from walk caller              */
9749 /*                                                                          */
9750 /* Free an actual host_node_t structure.                                    */
9751 /* ------------------------------------------------------------------------ */
9752 void
9753 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9754 {
9755 	KFREE(node);
9756 }
9757 
9758 
9759 /* ------------------------------------------------------------------------ */
9760 /* Function:    ipf_rb_ht_flush                                             */
9761 /* Returns:     Nil                                                         */
9762 /* Parameters:  head(I) - pointer to host tracking structure                */
9763 /*                                                                          */
9764 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
9765 /* and free'ing each one.                                                   */
9766 /* ------------------------------------------------------------------------ */
9767 void
9768 ipf_rb_ht_flush(host_track_t *head)
9769 {
9770 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9771 }
9772 
9773 
9774 /* ------------------------------------------------------------------------ */
9775 /* Function:    ipf_slowtimer                                               */
9776 /* Returns:     Nil                                                         */
9777 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
9778 /*                                                                          */
9779 /* Slowly expire held state for fragments.  Timeouts are set * in           */
9780 /* expectation of this being called twice per second.                       */
9781 /* ------------------------------------------------------------------------ */
9782 void
9783 ipf_slowtimer(ipf_main_softc_t *softc)
9784 {
9785 
9786 	ipf_token_expire(softc);
9787 	ipf_frag_expire(softc);
9788 	ipf_state_expire(softc);
9789 	ipf_nat_expire(softc);
9790 	ipf_auth_expire(softc);
9791 	ipf_lookup_expire(softc);
9792 	ipf_rule_expire(softc);
9793 	ipf_sync_expire(softc);
9794 	softc->ipf_ticks++;
9795 }
9796 
9797 
9798 /* ------------------------------------------------------------------------ */
9799 /* Function:    ipf_inet_mask_add                                           */
9800 /* Returns:     Nil                                                         */
9801 /* Parameters:  bits(I) - pointer to nat context information                */
9802 /*              mtab(I) - pointer to mask hash table structure              */
9803 /*                                                                          */
9804 /* When called, bits represents the mask of a new NAT rule that has just    */
9805 /* been added. This function inserts a bitmask into the array of masks to   */
9806 /* search when searching for a matching NAT rule for a packet.              */
9807 /* Prevention of duplicate masks is achieved by checking the use count for  */
9808 /* a given netmask.                                                         */
9809 /* ------------------------------------------------------------------------ */
9810 void
9811 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9812 {
9813 	u_32_t mask;
9814 	int i, j;
9815 
9816 	mtab->imt4_masks[bits]++;
9817 	if (mtab->imt4_masks[bits] > 1)
9818 		return;
9819 
9820 	if (bits == 0)
9821 		mask = 0;
9822 	else
9823 		mask = 0xffffffff << (32 - bits);
9824 
9825 	for (i = 0; i < 33; i++) {
9826 		if (ntohl(mtab->imt4_active[i]) < mask) {
9827 			for (j = 32; j > i; j--)
9828 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9829 			mtab->imt4_active[i] = htonl(mask);
9830 			break;
9831 		}
9832 	}
9833 	mtab->imt4_max++;
9834 }
9835 
9836 
9837 /* ------------------------------------------------------------------------ */
9838 /* Function:    ipf_inet_mask_del                                           */
9839 /* Returns:     Nil                                                         */
9840 /* Parameters:  bits(I) - number of bits set in the netmask                 */
9841 /*              mtab(I) - pointer to mask hash table structure              */
9842 /*                                                                          */
9843 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
9844 /* netmasks stored inside of mtab.                                          */
9845 /* ------------------------------------------------------------------------ */
9846 void
9847 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9848 {
9849 	u_32_t mask;
9850 	int i, j;
9851 
9852 	mtab->imt4_masks[bits]--;
9853 	if (mtab->imt4_masks[bits] > 0)
9854 		return;
9855 
9856 	mask = htonl(0xffffffff << (32 - bits));
9857 	for (i = 0; i < 33; i++) {
9858 		if (mtab->imt4_active[i] == mask) {
9859 			for (j = i + 1; j < 33; j++)
9860 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9861 			break;
9862 		}
9863 	}
9864 	mtab->imt4_max--;
9865 	ASSERT(mtab->imt4_max >= 0);
9866 }
9867 
9868 
9869 #ifdef USE_INET6
9870 /* ------------------------------------------------------------------------ */
9871 /* Function:    ipf_inet6_mask_add                                          */
9872 /* Returns:     Nil                                                         */
9873 /* Parameters:  bits(I) - number of bits set in mask                        */
9874 /*              mask(I) - pointer to mask to add                            */
9875 /*              mtab(I) - pointer to mask hash table structure              */
9876 /*                                                                          */
9877 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
9878 /* has just been added. This function inserts a bitmask into the array of   */
9879 /* masks to search when searching for a matching NAT rule for a packet.     */
9880 /* Prevention of duplicate masks is achieved by checking the use count for  */
9881 /* a given netmask.                                                         */
9882 /* ------------------------------------------------------------------------ */
9883 void
9884 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9885 {
9886 	i6addr_t zero;
9887 	int i, j;
9888 
9889 	mtab->imt6_masks[bits]++;
9890 	if (mtab->imt6_masks[bits] > 1)
9891 		return;
9892 
9893 	if (bits == 0) {
9894 		mask = &zero;
9895 		zero.i6[0] = 0;
9896 		zero.i6[1] = 0;
9897 		zero.i6[2] = 0;
9898 		zero.i6[3] = 0;
9899 	}
9900 
9901 	for (i = 0; i < 129; i++) {
9902 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
9903 			for (j = 128; j > i; j--)
9904 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9905 			mtab->imt6_active[i] = *mask;
9906 			break;
9907 		}
9908 	}
9909 	mtab->imt6_max++;
9910 }
9911 
9912 
9913 /* ------------------------------------------------------------------------ */
9914 /* Function:    ipf_inet6_mask_del                                          */
9915 /* Returns:     Nil                                                         */
9916 /* Parameters:  bits(I) - number of bits set in mask                        */
9917 /*              mask(I) - pointer to mask to remove                         */
9918 /*              mtab(I) - pointer to mask hash table structure              */
9919 /*                                                                          */
9920 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
9921 /* netmasks stored inside of mtab.                                          */
9922 /* ------------------------------------------------------------------------ */
9923 void
9924 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9925 {
9926 	i6addr_t zero;
9927 	int i, j;
9928 
9929 	mtab->imt6_masks[bits]--;
9930 	if (mtab->imt6_masks[bits] > 0)
9931 		return;
9932 
9933 	if (bits == 0)
9934 		mask = &zero;
9935 	zero.i6[0] = 0;
9936 	zero.i6[1] = 0;
9937 	zero.i6[2] = 0;
9938 	zero.i6[3] = 0;
9939 
9940 	for (i = 0; i < 129; i++) {
9941 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9942 			for (j = i + 1; j < 129; j++) {
9943 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9944 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
9945 					break;
9946 			}
9947 			break;
9948 		}
9949 	}
9950 	mtab->imt6_max--;
9951 	ASSERT(mtab->imt6_max >= 0);
9952 }
9953 #endif
9954